diff --git a/.gitignore b/.gitignore index c6b5441e46f166da4d6fef22f848a7d90bdbca64..25eb52fd74d5b7fc206b51665545d2251ea2a868 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,6 @@ node_modules/ _search_index_native*.so static/vendor/* !static/vendor/djvu-rs-reader/ -static/foliate-reader/ tests/__pycache__/ tests/performance/benchmark-results.json tests/snapshots/ diff --git a/Dockerfile b/Dockerfile index 3476d5e6833c9a9f7c8da3deb1c9ba3fe8ef46ef..9959799048ad441e6c467d7d22be0ecb14c36057 100644 --- a/Dockerfile +++ b/Dockerfile @@ -136,15 +136,12 @@ RUN npm install --global "esbuild@${ESBUILD_VERSION}" \ COPY static/ /build/static/ COPY scripts/build/build_static_assets.mjs /build/build_static_assets.mjs COPY scripts/build/copy_reader_vendor.mjs /build/copy_reader_vendor.mjs -COPY scripts/build/fetch_foliate_reader.mjs /build/fetch_foliate_reader.mjs -COPY scripts/build/foliate-local.patch.b64 /build/foliate-local.patch.b64 COPY scripts/build/check_reader_release.mjs /build/check_reader_release.mjs COPY scripts/build/compose_app.mjs /build/compose_app.mjs RUN mkdir -p /out \ && cp -a static/. /out/ \ - && node /build/fetch_foliate_reader.mjs /out/foliate-reader \ - && node /build/copy_reader_vendor.mjs /out/vendor --foliate-output /out/foliate-reader/vendor \ + && node /build/copy_reader_vendor.mjs /out/vendor \ && node /build/compose_app.mjs > /build/app-composed.js \ && esbuild /build/app-composed.js --minify --target=es2020 --charset=utf8 --legal-comments=none --outfile=/out/app.js \ && for file in $(node -e 'console.log(require("./static/reader-resources.js").buildFiles("hf").filter(f => f !== "app.js").join(" "))'); do \ diff --git a/backend/search/application/cached.py b/backend/search/application/cached.py index 23a604ac167d4d603db8c0f58686c239ca1645eb..90d0ae26e8f0e3392bf0db6f5d1124297ed979ab 100644 --- a/backend/search/application/cached.py +++ b/backend/search/application/cached.py @@ -142,9 +142,11 @@ def get_order(q: str, repos: Sequence[str] | None, extensions: Sequence[str] | N packed = indices if isinstance(indices, array) else array('I', indices) size = len(packed) * packed.itemsize if size <= deps.order_bytes(): + total_bytes = sum(len(v[1]) * v[1].itemsize for v in deps.orders().values()) while deps.orders() and (len(deps.orders()) >= deps.order_max() or - sum(len(v[1]) * v[1].itemsize for v in deps.orders().values()) + size > deps.order_bytes()): - deps.orders().popitem(last=False) + total_bytes + size > deps.order_bytes()): + _, (_, evicted) = deps.orders().popitem(last=False) + total_bytes -= len(evicted) * evicted.itemsize deps.orders()[key] = (now, packed) return packed diff --git a/config/types/jsconfig.check.json b/config/types/jsconfig.check.json index 371de4e7998e2e1c0b400c70fc7a4c8b073a99d5..4075e370c153f2b28f38f52c0c209cbfda71edf2 100644 --- a/config/types/jsconfig.check.json +++ b/config/types/jsconfig.check.json @@ -15,12 +15,6 @@ ], "/search/static/*": [ "../../static/*" - ], - "/static/foliate-reader/view.js": [ - "../../typings/foliate/view.d.ts" - ], - "/search/static/foliate-reader/view.js?reader-v1": [ - "../../typings/foliate/view.d.ts" ] } }, diff --git a/config/types/jsconfig.strict.json b/config/types/jsconfig.strict.json index 6e4f00fe805e417dc9bdaf7d42a88e7830301628..8a6f714c530c7dde813316100f3bcbfac9c96be4 100644 --- a/config/types/jsconfig.strict.json +++ b/config/types/jsconfig.strict.json @@ -14,9 +14,7 @@ "moduleResolution": "bundler", "paths": { "/static/*": ["../../static/*"], - "/search/static/*": ["../../static/*"], - "/static/foliate-reader/view.js": ["../../typings/foliate/view.d.ts"], - "/search/static/foliate-reader/view.js?reader-v1": ["../../typings/foliate/view.d.ts"] + "/search/static/*": ["../../static/*"] } }, "files": [ @@ -54,7 +52,6 @@ "../../static/reader/pdf/reader-pdf-text-runtime.mjs", "../../static/reader/pdf/reader-v3.mjs", "../../static/reader/core/reader-contract.js", - "../../static/reader/formats/reader-foliate-format.mjs", "../../static/reader/formats/reader-html-format.mjs", "../../static/reader/search/reader-book-text.js", "../../static/reader/search/reader-chapter-search.mjs", diff --git a/eslint.config.mjs b/eslint.config.mjs index 307d173f3911a219c237411b631095d47a947176..b4ec6c9a5706a816ebcf1049486600ad4cb2d887 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -12,7 +12,7 @@ const rules = Object.fromEntries([ export default [ // ESLint's global ignore also prevents parsing third-party minified files. - { ignores: ["**/vendor/**", "**/foliate-reader/**", "**/node_modules/**"] }, + { ignores: ["**/vendor/**", "**/node_modules/**"] }, { files: ["static/**/*.{js,mjs}"], languageOptions: { diff --git a/ruff.toml b/ruff.toml index 2df063fe7c579dbe2f91e94798f318559b71f665..c8f32ca055fe94a2d6630f37428f987c2dd76ae0 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,5 +1,5 @@ target-version = "py311" -extend-exclude = ["static/vendor", "static/foliate-reader"] +extend-exclude = ["static/vendor"] [lint] select = ["F", "E9", "S"] diff --git a/scripts/build/check_reader_release.mjs b/scripts/build/check_reader_release.mjs index 2082249f02978ad617b39b74e0dbdd4f7514ff80..d27e03ac5938e494bfcf8f3d078db4891fd9846b 100644 --- a/scripts/build/check_reader_release.mjs +++ b/scripts/build/check_reader_release.mjs @@ -19,7 +19,7 @@ const args = Object.fromEntries( ) ); const sourceRequired = ["reader.html", ...resources.readerFiles]; -const required = [...sourceRequired, ...resources.foliateFiles.map(file => `foliate-reader/${file}`)]; +const required = sourceRequired; // Source smoke assertions, not a substitute for runtime behavior tests. const behavioral = [ /\bVoiceOfMLReaderRuntime\s*\.\s*createReaderRuntime\s*\(/, @@ -90,15 +90,6 @@ function checkAssets(output, hashed = false) { for (const [file, digest] of Object.entries(djvuFiles)) assert(hash(path.join(output, "vendor/djvu-rs-reader", file)) === digest, `DjVu decoder integrity mismatch: ${file}`); assert(fs.statSync(path.join(output, "vendor/djvu-rs-reader/NOTICE.txt")).isFile(), "missing DjVu decoder notice"); - for (const vendor of Object.values(resources.foliateVendors)) { - const filename = path.join("foliate-reader/vendor", vendor.file); - assert(hash(path.join(output, filename)) === vendor.sha256, - `Foliate vendor integrity mismatch: ${filename}`); - } - for (const [name, filename] of [["pdf", "pdf.mjs"], ["pdfWorker", "pdf.worker.mjs"]]) { - assert(hash(path.join(output, "foliate-reader/vendor/pdfjs", filename)) === resources.vendors[name].sha256, - `Foliate PDF engine mismatch: ${filename}`); - } for (const vendor of Object.values(resources.vendors)) { assert( hash(path.join(output, vendor.path)) === vendor.sha256, @@ -151,12 +142,6 @@ function checkAssets(output, hashed = false) { `missing or empty Reader vendor directory: ${directory}` ); } - for (const directory of ["foliate-reader/vendor/pdfjs/cmaps", "foliate-reader/vendor/pdfjs/standard_fonts", - "foliate-reader/vendor/pdfjs/wasm"]) { - const target = path.join(output, directory); - assert(fs.existsSync(target) && fs.statSync(target).isDirectory() && fs.readdirSync(target).length > 0, - `missing or empty Foliate PDF.js directory: ${directory}`); - } } function currentAsset(output, filename) { @@ -192,6 +177,7 @@ function checkProject(root, artifact) { const output = staticRoot(root, artifact); checkAssets(output, !!artifact); if (artifact) { + assert(!fs.existsSync(path.join(output, "foliate-reader")), "obsolete Foliate runtime in release"); const project = args.project || (fs.existsSync(path.join(root, "Dockerfile")) ? "hf" : "github"); for (const file of resources.buildFiles(project)) currentAsset(output, file); const shellPath = fs.existsSync(path.join(output, "index.html")) @@ -215,10 +201,7 @@ function checkProject(root, artifact) { "unexpanded Reader cache inventory" ); } - const manifest = [ - ...sourceRequired.map(file => `${file}:${hash(path.join(source, file))}`), - ...resources.foliateFiles.map(file => `foliate-reader/${file}:${hash(path.join(output, "foliate-reader", file))}`) - ].join("\n"); + const manifest = sourceRequired.map(file => `${file}:${hash(path.join(source, file))}`).join("\n"); return crypto.createHash("sha256").update(manifest).digest("hex"); } @@ -331,7 +314,7 @@ function crossCheck(githubRoot, hfRoot) { `cross-project drift: ${file}` ); } - for (const file of ["compose_app.mjs", "copy_reader_vendor.mjs", "fetch_foliate_reader.mjs", "foliate-local.patch.b64", "check_reader_release.mjs"]) { + for (const file of ["compose_app.mjs", "copy_reader_vendor.mjs", "check_reader_release.mjs"]) { assert( hash(path.join(githubRoot, "scripts/build", file)) === hash(path.join(hfRoot, "scripts/build", file)), `cross-project drift: scripts/build/${file}` diff --git a/scripts/build/copy_reader_vendor.mjs b/scripts/build/copy_reader_vendor.mjs index c32586b2a49b5280994e885f0fcb2aadd40ee5c2..b1579d0d9cf9e6915191510b4ff5a16845974c49 100644 --- a/scripts/build/copy_reader_vendor.mjs +++ b/scripts/build/copy_reader_vendor.mjs @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, writeFileSync } from "node:fs"; import { Agent, get } from "node:https"; import { dirname, join } from "node:path"; import { gunzipSync } from "node:zlib"; @@ -8,13 +8,6 @@ import { setTimeout as delay } from "node:timers/promises"; const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js")); const output = process.argv[2] || "static/vendor"; -const foliateOutputArgument = process.argv.indexOf("--foliate-output"); -if (foliateOutputArgument >= 0 && !process.argv[foliateOutputArgument + 1]) - throw new Error("--foliate-output requires a directory"); -const foliateOutput = foliateOutputArgument >= 0 - ? process.argv[foliateOutputArgument + 1] - : process.argv.includes("--refresh-foliate") - ? join(process.cwd(), "static/foliate-reader/vendor") : null; // proxyEnv is supported by Node 22.21+, 24.5+, and later major versions. const [major, minor] = process.versions.node.split(".").map(Number); if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5)) @@ -82,8 +75,7 @@ async function downloadWithRetry(url, signal) { async function main() { const vendors = Object.entries(resources.vendors); - const foliateVendors = foliateOutput ? Object.values(resources.foliateVendors) : []; - const items = [resources.pdfArchive, ...vendors.map(([, value]) => value), ...foliateVendors, resources.ruffleArchive]; + const items = [resources.pdfArchive, ...vendors.map(([, value]) => value), resources.ruffleArchive]; const downloaded = new Array(items.length); let next = 0; const controller = new AbortController(); @@ -134,7 +126,6 @@ async function main() { // Prepare every operation before touching existing output. Disk errors during the // commit below can still leave partial updates; this is not an atomic rollback. const writes = []; - const removals = []; const ruffleOutput = join(output, resources.ruffleArchive.directory.slice("vendor/".length)); for (const [file, bytes] of extractedRuffle) writes.push([join(ruffleOutput, file), bytes]); const tar = gunzipSync(downloaded[0], { maxOutputLength: MAX_ARCHIVE_BYTES }); @@ -158,7 +149,6 @@ for (let offset = 0; offset < tar.length;) { const target = join(output, relative); const bytes = tar.subarray(offset + 512, offset + 512 + size); writes.push([target, bytes]); - if (foliateOutput) writes.push([join(foliateOutput, "pdfjs", relative), bytes]); } offset += 512 + Math.ceil(size / 512) * 512; } @@ -166,26 +156,15 @@ for (const group of pdfGroups) { if (![...pdfFiles].some(file => file.startsWith(group + "/"))) throw new Error(`PDF archive missing required files: ${group}`); } -for (const [index, [name, {path}]] of vendors.entries()) { +for (const [index, [, {path}]] of vendors.entries()) { const bytes = downloaded[index + 1]; const versioned = path.slice("vendor/".length); writes.push([join(output, versioned), bytes]); - if (foliateOutput && (name === "pdf" || name === "pdfWorker")) { - const filename = name === "pdf" ? "pdf.mjs" : "pdf.worker.mjs"; - writes.push([join(foliateOutput, "pdfjs", filename), bytes]); - removals.push(join(foliateOutput, "pdfjs", filename + ".map")); - } -} -if (foliateOutput) for (const [index, {file}] of foliateVendors.entries()) { - const bytes = downloaded[1 + vendors.length + index]; - const target = join(foliateOutput, file); - writes.push([target, bytes]); } for (const [target, bytes] of writes) { mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, bytes); } -for (const target of removals) rmSync(target, { force: true }); } main().catch((error) => { console.error(error); process.exitCode = 1; }); diff --git a/scripts/build/fetch_foliate_reader.mjs b/scripts/build/fetch_foliate_reader.mjs deleted file mode 100644 index 0c4896f60a3b75363d7cf115ccfa0fcc39d14da8..0000000000000000000000000000000000000000 --- a/scripts/build/fetch_foliate_reader.mjs +++ /dev/null @@ -1,157 +0,0 @@ -import { createHash } from "node:crypto"; -import { createRequire } from "node:module"; -import { dirname, join, relative, resolve, sep } from "node:path"; -import { fileURLToPath } from "node:url"; -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { Agent, get } from "node:https"; -import { gunzipSync } from "node:zlib"; - -// proxyEnv is supported by Node 22.21+, 24.5+, and later major versions. -const [major, minor] = process.versions.node.split(".").map(Number); -if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5)) - throw new Error("Node.js 22.21+, 24.5+, or later is required for proxy support"); - -const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js")); -const output = resolve(process.argv[2] || "static/foliate-reader"); -const scriptDir = dirname(fileURLToPath(import.meta.url)); -const encodedPatch = readFileSync(join(scriptDir, "foliate-local.patch.b64"), "ascii").replace(/\s/g, ""); -if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encodedPatch)) - throw new Error("Foliate local adaptation patch is not valid base64"); -const localPatch = Buffer.from(encodedPatch, "base64").toString("utf8"); - -// The proxy-aware agent honors HTTP(S)_PROXY and NO_PROXY, including on redirects. -const agent = new Agent({ proxyEnv: process.env }); - -function download(url, redirects = 0) { - return new Promise((resolvePromise, reject) => { - // Never propagate transport errors or URLs: either can contain proxy credentials. - const fail = () => reject(new Error("Foliate archive download failed")); - try { - const request = get(url, { agent }, (response) => { - if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location && redirects < 5) { - response.resume(); - try { return download(new URL(response.headers.location, url), redirects + 1).then(resolvePromise, reject); } - catch { return fail(); } - } - if (response.statusCode !== 200) { - response.resume(); - return reject(new Error(`Foliate archive download: HTTP ${response.statusCode}`)); - } - const chunks = []; - response.on("data", chunk => chunks.push(chunk)); - response.on("end", () => resolvePromise(Buffer.concat(chunks))); - response.on("error", fail); - response.on("aborted", fail); - }); - request.setTimeout(180000, () => request.destroy()); - request.on("error", fail); - } catch { fail(); } - }); -} - -async function downloadWithRetry(url) { - let lastError; - for (let attempt = 0; attempt < 4; attempt++) { - try { return await download(url); } - catch (error) { - lastError = error; - if (attempt < 3) await new Promise(resolvePromise => setTimeout(resolvePromise, 1000 * (2 ** attempt))); - } - } - throw lastError; -} - -function extractPinnedFiles(archive) { - const tar = gunzipSync(archive); - const allowed = new Set(resources.foliateFiles); - const extracted = new Set(); - const root = `foliate-js-${resources.foliateRevision}`; - for (let offset = 0; offset + 512 <= tar.length;) { - const header = tar.subarray(offset, offset + 512); - const name = header.subarray(0, 100).toString("utf8").replace(/\0.*$/, ""); - if (!name) break; - const prefix = header.subarray(345, 500).toString("utf8").replace(/\0.*$/, ""); - const path = prefix ? `${prefix}/${name}` : name; - const sizeText = header.subarray(124, 136).toString("ascii").replace(/\0.*$/, "").trim() || "0"; - const size = parseInt(sizeText, 8); - const type = String.fromCharCode(header[156] || 48); - const rootPrefix = `${root}/`; - if (!Number.isSafeInteger(size) || size < 0) throw new Error(`invalid Foliate tar entry size: ${path}`); - if (path.startsWith(rootPrefix) && (type === "0" || type === "\0")) { - const file = path.slice(rootPrefix.length); - if (allowed.has(file)) { - const target = resolve(output, file); - const rel = relative(output, target); - if (!rel || rel === ".." || rel.startsWith(`..${sep}`)) throw new Error(`unsafe Foliate path: ${file}`); - mkdirSync(dirname(target), { recursive: true }); - writeFileSync(target, tar.subarray(offset + 512, offset + 512 + size)); - extracted.add(file); - } - } - offset += 512 + Math.ceil(size / 512) * 512; - } - const missing = [...allowed].filter(file => !extracted.has(file)); - if (missing.length) throw new Error(`pinned Foliate archive is missing: ${missing.join(", ")}`); -} - -function applyLocalPatch(patch) { - const lines = patch.split(/\r?\n/); - let index = 0; - let changed = 0; - while (index < lines.length) { - const fileHeader = lines[index++].match(/^diff --git a\/(.+) b\/(.+)$/); - if (!fileHeader) continue; - const file = fileHeader[2]; - const target = resolve(output, file); - const rel = relative(output, target); - if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || !resources.foliateFiles.includes(file)) - throw new Error(`Foliate patch targets an unexpected path: ${file}`); - const original = readFileSync(target, "utf8").split("\n"); - const result = []; - let sourceIndex = 0; - while (index < lines.length && !lines[index].startsWith("diff --git ")) { - const hunk = lines[index].match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); - if (!hunk) { index++; continue; } - const oldStart = Number(hunk[1]); - const oldCount = hunk[2] === undefined ? 1 : Number(hunk[2]); - const targetIndex = oldCount === 0 ? oldStart : oldStart - 1; - while (sourceIndex < targetIndex) result.push(original[sourceIndex++]); - index++; - while (index < lines.length && !lines[index].startsWith("@@ ") && !lines[index].startsWith("diff --git ")) { - const line = lines[index++]; - if (line === "") { - if (index === lines.length) break; - throw new Error(`unexpected empty Foliate patch line in ${file}`); - } - const marker = line[0], text = line.slice(1); - if (marker === "\\") continue; - if (marker === " ") { - if (original[sourceIndex] !== text) throw new Error(`Foliate patch context mismatch in ${file}`); - result.push(original[sourceIndex++]); - } else if (marker === "-") { - if (original[sourceIndex] !== text) throw new Error(`Foliate patch removal mismatch in ${file}`); - sourceIndex++; - } else if (marker === "+") result.push(text); - else throw new Error(`invalid Foliate patch line in ${file}: ${line}`); - } - changed++; - } - result.push(...original.slice(sourceIndex)); - writeFileSync(target, result.join("\n")); - } - if (!changed) throw new Error("Foliate local adaptation patch was empty or invalid"); -} - -async function main() { - rmSync(output, { recursive: true, force: true }); - mkdirSync(output, { recursive: true }); - const archive = await downloadWithRetry(resources.foliateArchive.url); - const actual = createHash("sha256").update(archive).digest("hex"); - if (actual !== resources.foliateArchive.sha256) - throw new Error(`Foliate archive SHA-256 ${actual} does not match ${resources.foliateArchive.sha256}`); - extractPinnedFiles(archive); - applyLocalPatch(localPatch); - console.log(`Foliate ${resources.foliateRevision} fetched, verified, and locally adapted at ${output}`); -} - -main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/scripts/build/foliate-local.patch.b64 b/scripts/build/foliate-local.patch.b64 deleted file mode 100644 index 43030f5cee5b4eaf516e0b4d0479ce41eeab3fc2..0000000000000000000000000000000000000000 --- a/scripts/build/foliate-local.patch.b64 +++ /dev/null @@ -1 +0,0 @@ -ZGlmZiAtLWdpdCBhL2VwdWIuanMgYi9lcHViLmpzCmluZGV4IG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ignSW52YWxpZCBNT0JJIG5hdmlnYXRpb24gb2Zmc2V0JykKKyAgICAgICAgICAgIG9mZnNldHMucHVzaChTdHJpbmcob2Zmc2V0KSkKKyAgICAgICAgICAgIHJldHVybiB7IGxhYmVsOiB1bmVzY2FwZUhUTUwobGFiZWwpLCBocmVmOiBgZmlsZXBvczoke29mZnNldH1gLAorICAgICAgICAgICAgICAgIHN1Yml0ZW1zOiBtYXBOQ1goY2hpbGRyZW4pIH0KKyAgICAgICAgfSkKKyAgICAgICAgdHJ5IHsKKyAgICAgICAgICAgIHRoaXMudG9jID0gbWFwTkNYKG5jeCkKKyAgICAgICAgfSBjYXRjaCAoZSkgeworICAgICAgICAgICAgY29uc29sZS53YXJuKGUpCisgICAgICAgIH0KKyAgICAgICAgdGhpcy4jZmlsZXBvc0xpc3QgPSBbLi4ubmV3IFNldChbCisgICAgICAgICAgICAuLi5BcnJheS5mcm9tKHN0ci5tYXRjaEFsbChmaWxlcG9zUmVnZXgpLCBtID0+IG1bMV0pLCAuLi5vZmZzZXRzXSldCiAgICAgICAgICAgICAubWFwKGZpbGVwb3MgPT4gKHsgZmlsZXBvcywgbnVtYmVyOiBOdW1iZXIoZmlsZXBvcykgfSkpCiAgICAgICAgICAgICAuc29ydCgoYSwgYikgPT4gYS5udW1iZXIgLSBiLm51bWJlcikKIApAQCAtNzMzLDcgKzc1Miw3IEBAIGNsYXNzIE1PQkk2IHsKICAgICAgICAgICAgIHRoaXMubGFuZG1hcmtzID0gYXdhaXQgdGhpcy5nZXRHdWlkZSgpCiAgICAgICAgICAgICBjb25zdCB0b2NIcmVmID0gdGhpcy5sYW5kbWFya3MKICAgICAgICAgICAgICAgICAuZmluZCgoeyB0eXBlIH0pID0+IHR5cGU/LmluY2x1ZGVzKCd0b2MnKSk/LmhyZWYKLSAgICAgICAgICAgIGlmICh0b2NIcmVmKSB7CisgICAgICAgICAgICBpZiAodG9jSHJlZiAmJiAhdGhpcy50b2M/Lmxlbmd0aCkgewogICAgICAgICA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bGxlZCcpCisgICAgICAgIGxldCBtb3ZpbmcgPSBmYWxzZQorICAgICAgICBsZXQgcHJldmlvdXNTdGFydCA9IG51bGwKKyAgICAgICAgY29uc3QgbW92ZVNlY3Rpb24gPSBhc3luYyBkaXJlY3Rpb24gPT4geworICAgICAgICAgICAgY29uc3QgcmVuZGVyZXIgPSB0aGlzLnZpZXcucmVuZGVyZXIKKyAgICAgICAgICAgIGlmIChtb3ZpbmcgfHwgIXJlbmRlcmVyLnNjcm9sbGVkIHx8ICFkaXJlY3Rpb24pIHJldHVybgorICAgICAgICAgICAgY29uc3Qgc3RhcnQgPSByZW5kZXJlci5zdGFydAorICAgICAgICAgICAgY29uc3QgZW5kID0gcmVuZGVyZXIuZW5kCisgICAgICAgICAgICBjb25zdCB2aWV3U2l6ZSA9IHJlbmRlcmVyLnZpZXdTaXplCisgICAgICAgICAgICBpZiAoZGlyZWN0aW9uID4gMCAmJiBlbmQgPCB2aWV3U2l6ZSAtIDIpIHJldHVybgorICAgICAgICAgICAgaWYgKGRpcmVjdGlvbiA8IDAgJiYgc3RhcnQgPiAyKSByZXR1cm4KKyAgICAgICAgICAgIG1vdmluZyA9IHRydWUKKyAgICAgICAgICAgIHRyeSB7CisgICAgICAgICAgICAgICAgaWYgKGRpcmVjdGlvbiA+IDApIGF3YWl0IHRoaXMudmlldy5uZXh0KCkKKyAgICAgICAgICAgICAgICBlbHNlIGF3YWl0IHRoaXMudmlldy5wcmV2KCkKKyAgICAgICAgICAgIH0gZmluYWxseSB7CisgICAgICAgICAgICAgICAgbW92aW5nID0gZmFsc2UKKyAgICAgICAgICAgICAgICBwcmV2aW91c1N0YXJ0ID0gbnVsbAorICAgICAgICAgICAgfQorICAgICAgICB9CisgICAgICAgIGNvbnN0IG1vdmVBY3Jvc3NTZWN0aW9ucyA9ICgpID0+IHsKKyAgICAgICAgICAgIGNvbnN0IHJlbmRlcmVyID0gdGhpcy52aWV3LnJlbmRlcmVyCisgICAgICAgICAgICBjb25zdCBzdGFydCA9IHJlbmRlcmVyLnN0YXJ0CisgICAgICAgICAgICBjb25zdCBkaXJlY3Rpb24gPSBwcmV2aW91c1N0YXJ0ID09IG51bGwgPyAwIDogc3RhcnQgLSBwcmV2aW91c1N0YXJ0CisgICAgICAgICAgICBwcmV2aW91c1N0YXJ0ID0gc3RhcnQKKyAgICAgICAgICAgIG1vdmVTZWN0aW9uKGRpcmVjdGlvbikKKyAgICAgICAgfQorICAgICAgICBsZXQgYm91bmRDb250YWluZXIgPSBudWxsCisgICAgICAgIGNvbnN0IGJpbmRTY3JvbGxDb250YWluZXIgPSAoKSA9PiB7CisgICAgICAgICAgICBjb25zdCBjb250YWluZXIgPSB0aGlzLnZpZXcucmVuZGVyZXIuc2hhZG93Um9vdD8ucXVlcnlTZWxlY3RvcignI2NvbnRhaW5lcicpIHx8IHRoaXMudmlldy5yZW5kZXJlcgorICAgICAgICAgICAgaWYgKGNvbnRhaW5lciA9PT0gYm91bmRDb250YWluZXIpIHJldHVybgorICAgICAgICAgICAgYm91bmRDb250YWluZXIgPSBjb250YWluZXIKKyAgICAgICAgICAgIGNvbnRhaW5lci5hZGRFdmVudExpc3RlbmVyKCdzY3JvbGwnLCBtb3ZlQWNyb3NzU2VjdGlvbnMpCisgICAgICAgICAgICBjb250YWluZXIuYWRkRXZlbnRMaXN0ZW5lcignd2hlZWwnLCBldmVudCA9PiB7CisgICAgICAgICAgICBpZiAoZXZlbnQuZGVsdGFZKSBtb3ZlU2VjdGlvbihldmVudC5kZWx0YVkgPiAwID8gMSA6IC0xKQorICAgICAgICAgICAgfSwgeyBwYXNzaXZlOiB0cnVlIH0pCisgICAgICAgIH0KKyAgICAgICAgYmluZFNjcm9sbENvbnRhaW5lcigpCisgICAgICAgIHRoaXMudmlldy5yZW5kZXJlci5hZGRFdmVudExpc3RlbmVyKCdsb2FkJywgYmluZFNjcm9sbENvbnRhaW5lcikKKyAgICAgICAgc2V0SW50ZXJ2YWwoYmluZFNjcm9sbENvbnRhaW5lciwgMjA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CgpCisgICAgICAgIGF3YWl0IFByb21pc2UucmFjZShbCisgICAgICAgICAgICB0aGlzLnZpZXcuZ29UbygwKSwKKyAgICAgICAgICAgIG5ldyBQcm9taXNlKHJlc29sdmUgPT4gc2V0VGltZW91dChyZXNvbHZlLCAzMDAwKSksCisgICAgICAgIF0pCiAKICAgICAgICAgJCgnI2hlYWRlci1iYXInKS5zdHlsZS52aXNpYmlsaXR5ID0gJ3Zpc2libGUnCiAgICAgICAgICQoJyNuYXYtYmFyJykuc3R5bGUudmlzaWJpbGl0eSA9ICd2aXNpYmxlJwpAQCAtMTUxLDYgKzIwNCwxNSBAQCBjbGFzcyBSZWFkZXIgewogICAgICAgICAgICAgICAgIHRoaXMuY2xvc2VTaWRlQmFyKCkKICAgICAgICAgICAgIH0pCiAgICAgICAgICAgICAkKCcjdG9jLXZpZXcnKS5hcHBlbmQodGhpcy4jdG9jVmlldy5lbGVtZW50KQorICAgICAgICAgICAgY29uc3QgZW50cmllcyA9IFtdCisgICAgICAgICAgICBjb25zdCBhcHBlbmQgPSAoaXRlbXMsIGRlcHRoID0gMCkgPT4geworICAgICAgICAgICAgICAgIGZvciAoY29uc3QgaXRlbSBvZiBpdGVtcyB8fCBbXSkgeworICAgICAgICAgICAgICAgICAgICBlbnRyaWVzLnB1c2goeyBsYWJlbDogaXRlbS5sYWJlbCB8fCAn5pyq5ZG95ZCN56ug6IqCJywgaHJlZjogaXRlbS5ocmVmLCBkZXB0aCB9KQorICAgICAgICAgICAgICAgICAgICBhcHBlbmQoaXRlbS5zdWJpdGVtcywgZGVwdGggKyAxKQorICAgICAgICAgICAgICAgIH0KKyAgICAgICAgICAgIH0KKyAgICAgICAgICAgIGFwcGVuZCh0b2MpCisgICAgICAgICAgICBpZiAod2luZG93LnBhcmVudCAhPT0gd2luZG93KSB3aW5kb3cucGFyZW50LnBvc3RNZXNzYWdlKHsgdHlwZTogJ3ZvaWNlLWZvbGlhdGUtdG9jJywgZW50cmllcyB9LCBsb2NhdGlvbi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oc3RycywgcmFuZ2UpIH0gfQogICAgICAgICB9CiAgICAgICAgIHN1YnN0ckFyci5zaGlmdCgpCiAgICAgfQpAQCAtMTIxLDggKzEyMSwxNSBAQCBleHBvcnQgY29uc3Qgc2VhcmNoTWF0Y2hlciA9ICh0ZXh0V2Fsa2VyLCBvcHRzKSA9PiB7CiAgICAgICAgICAgICAgICAgOiAnYmFzZScsCiAgICAgICAgICAgICB9KSkgewogICAgICAgICAgICAgICAgIGNvbnN0IHsgc3RhcnRJbmRleCwgc3RhcnRPZmZzZXQsIGVuZEluZGV4LCBlbmRPZmZzZXQgfSA9IHJlc3VsdC5yYW5nZQotICAgICAgICAgICAgICAgIHJlc3VsdC5yYW5nZSA9IG1ha2VSYW5nZShzdGFydEluZGV4LCBzdGFydE9mZnNldCwgZW5kSW5kZXgsIGVuZE9mZnNldCkKLSAgICAgICAgICAgICAgICB5aWVsZCByZXN1bHQKKyAgICAgICAgICAgICAgICAvLyBDb3VudCBldmVyeSBtYXRjaCB3aXRob3V0IGJ1aWxkaW5nIGV4Y2VycHRzIG9yIERPTSByYW5nZXMKKyAgICAgICAgICAgICAgICAvLyBmb3IgcmVzdWx0cyBvdXRzaWRlIHRoZSByZXF1ZXN0ZWQgcGFnZS4KKyAgICAgICAgICAgICAgICBsZXQgcmFuZ2UKKyAgICAgICAgICAgICAgICB5aWVsZCB7CisgICAgICAgICAgICAgICAgICAgIGdldCByYW5nZSgpIHsKKyAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiByYW5nZSA/Pz0gbWFrZVJhbmdlKHN0YXJ0SW5kZXgsIHN0YXJ0T2Zmc2V0LCBlbmRJbmRleCwgZW5kT2Zmc2V0KQorICAgICAgICAgICAgICAgICAgICB9LAorICAgICAgICAgICAgICAgICAgICBnZXQgZXhjZXJwdCgpIHsgcmV0dXJuIHJlc3VsdC5leGNlcnB0IH0sCisgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgfQogICAgICAgICB9LCBhY2NlcHROb2RlKQog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IEhUTUxFbGVtZW50IHsKICAgICAgICAgICAgIGF3YWl0IGltcG9ydCgnLi9wYWdpbmF0b3IuanMnKQogICAgICAgICAgICAgdGhpcy5yZW5kZXJlciA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2ZvbGlhdGUtcGFnaW5hdG9yJykKICAgICAgICAgfQorICAgICAgICB0aGlzLnJlbmRlcmVyLnNldEF0dHJpYnV0ZSgnZmxvdycsICdzY3JvbGxlZCcpCiAgICAgICAgIHRoaXMucmVuZGVyZXIuc2V0QXR0cmlidXRlKCdleHBvcnRwYXJ0cycsICdoZWFkLGZvb3QsZmlsdGVyJykKICAgICAgICAgdGhpcy5yZW5kZXJlci5hZGRFdmVudExpc3RlbmVyKCdsb2FkJywgZSA9PiB0aGlzLiNvbkxvYWQoZS5kZXRhaWwpKQogICAgICAgICB0aGlzLnJlbmRlcmVyLmFkZEV2ZW50TGlzdGVuZXIoJ3JlbG9jYXRlJywgZSA9PiB0aGlzLiNvblJlbG9jYXRlKGUuZGV0YWlsKSkKQEAgLTI3Niw3ICsyNzksNyBAQCBleHBvcnQgY2xhc3MgVmlldyBleHRlbmRzIEhUTUxFbGVtZW50IHsKICAgICAgICAgICAgICAgICB0aGlzLnJlbmRlcmVyLmdvVG8ocmVzb2x2ZWQpCiAgICAgICAgICAgICAgICAgICAgIC50aGVuKCgpID0+IHsKICAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHsgZG9jIH0gPSB0aGlzLnJlbmRlcmVyLmdldENvbnRlbnRzKCkKLSAgICAgICAgICAgICAgICAgICAgICAgICAgICAuZmluZCh4ID0+IHguaW5kZXggPSByZXNvbHZlZC5pbmRleCkKKyAgICAgICAgICAgICAgICAgICAgICAgICAgICAuZmluZCh4ID0+IHguaW5kZXggPT09IHJlc29sdmVkLmluZGV4KQogICAgICAgICAgICAgICAgICAgICAgICAgY29uc3QgZWwgPSByZXNvbHZlZC5hbmNob3IoZG9jKQogICAgICAgICAgICAgICAgICAgICAgICAgZWwuY2xhc3NMaXN0LmFkZChhY3RpdmVDbGFzcykKICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChwbGF5YmFja0FjdGl2ZUNsYXNzKSBlbC5vd25lckRvY3VtZW50CkBAIC0zMDcsOSArMzEwLDcgQEAgZXhwb3J0IGNsYXNzIFZpZXcgZXh0ZW5kcyBIVE1MRWxlbWVudCB7CiAgICAgICAgIHRoaXMubWVkaWFPdmVybGF5ID0gbnVsbAogICAgIH0KICAgICBnb1RvVGV4dFN0YXJ0KCkgewotICAgICAgICByZXR1cm4gdGhpcy5nb1RvKHRoaXMuYm9vay5sYW5kbWFya3MKLSAgICAgICAgICAgID8uZmluZChtID0+IG0udHlwZS5pbmNsdWRlcygnYm9keW1hdHRlcicpIHx8IG0udHlwZS5pbmNsdWRlcygndGV4dCcpKQotICAgICAgICAgICAgPy5ocmVmID8/IHRoaXMuYm9vay5zZWN0aW9ucy5maW5kSW5kZXgocyA9PiBzLmxpbmVhciAhPT0gJ25vJykpCisgICAgICAgIHJldHVybiB0aGlzLmdvVG8oMCkKICAgICB9CiAgICAgYXN5bmMgaW5pdCh7IGxhc3RMb2NhdGlvbiwgc2hvd1RleHRTdGFydCB9KSB7CiAgICAgICAgIGNvbnN0IHJlc29sdmVkID0gbGFzdExvY2F0aW9uID8gdGhpcy5yZXNvbHZlTmF2aWdhdGlvbihsYXN0TG9jYXRpb24pIDogbnVsbApAQCAtNTQ3LDYgKzU0OCwzNyBAQCBleHBvcnQgY2xhc3MgVmlldyBleHRlbmRzIEhUTUxFbGVtZW50IHsKICAgICAgICAgY29uc3QgeyBxdWVyeSwgaW5kZXggfSA9IG9wdHMKICAgICAgICAgY29uc3QgbWF0Y2hlciA9IHNlYXJjaE1hdGNoZXIodGV4dFdhbGtlciwKICAgICAgICAgICAgIHsgZGVmYXVsdExvY2FsZTogdGhpcy5sYW5ndWFnZSwgLi4ub3B0cyB9KQorICAgICAgICBpZiAob3B0cy5sZWFuKSB7CisgICAgICAgICAgICBjb25zdCB7IHNlY3Rpb25zIH0gPSB0aGlzLmJvb2sKKyAgICAgICAgICAgIGNvbnN0IGluZGljZXMgPSBpbmRleCAhPSBudWxsID8gW2luZGV4XSA6IHNlY3Rpb25zLm1hcCgoXywgaSkgPT4gaSkKKyAgICAgICAgICAgIGNvbnN0IG9mZnNldCA9IE1hdGgubWF4KDAsIG9wdHMub2Zmc2V0IHx8IDApCisgICAgICAgICAgICBjb25zdCBsaW1pdCA9IE1hdGgubWF4KDAsIE1hdGgubWluKDUwLCBvcHRzLmxpbWl0ID8/IDUwKSkKKyAgICAgICAgICAgIGZvciAoY29uc3Qgc2VjdGlvbkluZGV4IG9mIGluZGljZXMpIHsKKyAgICAgICAgICAgICAgICBpZiAob3B0cy5jdXJyZW50Py4oKSA9PT0gZmFsc2UpIHJldHVybgorICAgICAgICAgICAgICAgIGNvbnN0IHNlY3Rpb24gPSBzZWN0aW9uc1tzZWN0aW9uSW5kZXhdCisgICAgICAgICAgICAgICAgaWYgKCFzZWN0aW9uPy5jcmVhdGVEb2N1bWVudCkgY29udGludWUKKyAgICAgICAgICAgICAgICBjb25zdCBkb2MgPSBhd2FpdCBzZWN0aW9uLmNyZWF0ZURvY3VtZW50KCkKKyAgICAgICAgICAgICAgICBpZiAob3B0cy5jdXJyZW50Py4oKSA9PT0gZmFsc2UpIHJldHVybgorICAgICAgICAgICAgICAgIGxldCBjb3VudCA9IDAKKyAgICAgICAgICAgICAgICBjb25zdCBzdWJpdGVtcyA9IFtdCisgICAgICAgICAgICAgICAgZm9yIChjb25zdCBtYXRjaCBvZiBtYXRjaGVyKGRvYywgcXVlcnkpKSB7CisgICAgICAgICAgICAgICAgICAgIGlmIChjb3VudCA+PSBvZmZzZXQgJiYgc3ViaXRlbXMubGVuZ3RoIDwgbGltaXQpIHsKKyAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHsgcmFuZ2UsIGV4Y2VycHQgfSA9IG1hdGNoCisgICAgICAgICAgICAgICAgICAgICAgICBzdWJpdGVtcy5wdXNoKHsgY2ZpOiB0aGlzLmdldENGSShzZWN0aW9uSW5kZXgsIHJhbmdlKSwgZXhjZXJwdCB9KQorICAgICAgICAgICAgICAgICAgICB9CisgICAgICAgICAgICAgICAgICAgIGNvdW50KysKKyAgICAgICAgICAgICAgICAgICAgaWYgKGNvdW50ICUgMjA0OCA9PT0gMCkgeworICAgICAgICAgICAgICAgICAgICAgICAgYXdhaXQgbmV3IFByb21pc2UocmVzb2x2ZSA9PiBzZXRUaW1lb3V0KHJlc29sdmUsIDApKQorICAgICAgICAgICAgICAgICAgICAgICAgaWYgKG9wdHMuY3VycmVudD8uKCkgPT09IGZhbHNlKSByZXR1cm4KKyAgICAgICAgICAgICAgICAgICAgfQorICAgICAgICAgICAgICAgICAgICBpZiAoaW5kZXggIT0gbnVsbCAmJiBzdWJpdGVtcy5sZW5ndGggPT09IGxpbWl0KSBicmVhaworICAgICAgICAgICAgICAgIH0KKyAgICAgICAgICAgICAgICBpZiAob3B0cy5jdXJyZW50Py4oKSA9PT0gZmFsc2UpIHJldHVybgorICAgICAgICAgICAgICAgIHlpZWxkIHsgaW5kZXg6IHNlY3Rpb25JbmRleCwgY291bnQsIHN1Yml0ZW1zLAorICAgICAgICAgICAgICAgICAgICBsYWJlbDogdGhpcy4jdG9jUHJvZ3Jlc3MuZ2V0UHJvZ3Jlc3Moc2VjdGlvbkluZGV4KT8ubGFiZWwgPz8gJycgfQorICAgICAgICAgICAgfQorICAgICAgICAgICAgcmV0dXJuCisgICAgICAgIH0KICAgICAgICAgY29uc3QgaXRlciA9IGluZGV4ICE9IG51bGwKICAgICAgICAgICAgID8gdGhpcy4jc2VhcmNoU2VjdGlvbihtYXRjaGVyLCBxdWVyeSwgaW5kZXgpCiAgICAgICAgICAgICA6IHRoaXMuI3NlYXJjaEJvb2sobWF0Y2hlciwgcXVlcnkpCg== diff --git a/scripts/check_markup.mjs b/scripts/check_markup.mjs index 7d27fb5cc8d75fa5c678b55c5ff0c18c2153fd2d..f6c648e718ffda7670be358b4c649a27ad4d5a54 100644 --- a/scripts/check_markup.mjs +++ b/scripts/check_markup.mjs @@ -63,7 +63,7 @@ function html(file) { function visitDirectory(directory) { for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - if (entry.name === "vendor" || entry.name === "foliate-reader") continue; + if (entry.name === "vendor") continue; const file = path.join(directory, entry.name); if (entry.isDirectory()) visitDirectory(file); else if (entry.isFile() && entry.name.endsWith(".html")) html(file); diff --git a/scripts/reader/check_reader_lifecycle_coverage.mjs b/scripts/reader/check_reader_lifecycle_coverage.mjs index db0c06044145d8de49d6e34a84f57a0c5e013dcb..1ca448a442124fd999185ce8c156eee6e05bac82 100644 --- a/scripts/reader/check_reader_lifecycle_coverage.mjs +++ b/scripts/reader/check_reader_lifecycle_coverage.mjs @@ -24,7 +24,7 @@ const required = [ 'error classification preserves dynamic getter access and uncoerced matching codes', 'navigation warnings require a current generation and ignore aborts', 'waitForReader rejects on cancellation and resolves on its timer', - 'reader readiness preserves Foliate anchor only when loading node is connected', + 'reader readiness preserves chapter anchor only when loading node is connected', 'phase and stage forward return values unchanged', 'dispose is idempotent, releases observer and clears all timer handles', 'failure cleanup preserves message, lifecycle stage and retry control semantics', diff --git a/scripts/reader/check_reader_media_coverage.mjs b/scripts/reader/check_reader_media_coverage.mjs index b5bf970f6e2d916c2e00d0f19d320c86ba80565a..0388b663c4b6e3a1ddd7a19a5d96a8daa7429b57 100644 --- a/scripts/reader/check_reader_media_coverage.mjs +++ b/scripts/reader/check_reader_media_coverage.mjs @@ -43,7 +43,7 @@ if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => v } else { // Keep these independent of the TAP and coverage checks above. for (const args of [ - ['--test', '--test-concurrency=1', '--test-reporter=tap', 'tests/reader/copy_reader_vendor.test.mjs', 'tests/reader/test_foliate_proxy.mjs'], + ['--test', '--test-concurrency=1', '--test-reporter=tap', 'tests/reader/copy_reader_vendor.test.mjs'], ['tests/reader/media/test_ruffle_closure.mjs'], ['tests/service_worker/test_ruffle_retention.js'] ]) { diff --git a/static/app.js b/static/app.js index da67a8e6cfd27d373ff38cb12eb64049f9dfaf2e..3a7adfade232086d322fc3e2e953a7bbb5da1b76 100644 --- a/static/app.js +++ b/static/app.js @@ -1975,8 +1975,7 @@ function warmReaderIntent(rawUrl, urgent = false) { /** @param {string} href */ const preload = (href) => { const link = document.createElement("link"); - // Foliate files are all ES modules; a classic preload would not be reused. - const module = href.endsWith(".mjs") || href.includes("/foliate-reader/") || (href.endsWith(".js") && !engineAssets.includes(href)); + const module = href.endsWith(".mjs") || (href.endsWith(".js") && !engineAssets.includes(href)); link.rel = module ? "modulepreload" : "preload"; if (!module) link.as = href.endsWith(".css") ? "style" : "script"; link.fetchPriority = "low"; diff --git a/static/reader-resources.js b/static/reader-resources.js index 36f3abe0eb82d79df4a21c4dca6d95391746352b..fef8dc63c89a19fcda07ea5005be926dc072e236 100644 --- a/static/reader-resources.js +++ b/static/reader-resources.js @@ -28,6 +28,16 @@ file: "purify.min.js", sha256: "8053ee2a6a09f9d50f7fcd6fb7f07072f52c7f3fa9aa12147cab4feaf65ee970" }, + zip: { + url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/index.min.js", + file: "zip.js", + sha256: "715a4067bb71d750d4af8e60390e48894072f65501e0442e53f252cbfc45cfbc" + }, + zipLicense: { + url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/LICENSE", + file: "LICENSE_zipjs.txt", + sha256: "1b7ebc8d7889ed25491484ab2b102370742ca6c0b26650a0c62cc2269b579b84" + }, ruffle: { url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js", file: "ruffle.js", @@ -62,54 +72,11 @@ url: "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", sha256: "7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa" }); - const foliateRevision = "78914aef4466eb960965702401634c2cb348e9b1"; - const foliateArchive = Object.freeze({ - url: `https://codeload.github.com/johnfactotum/foliate-js/tar.gz/${foliateRevision}`, - sha256: "4878cd5f04073af5046ea543da73a963a7f9e1a4b30ddc63ac86cea5adf02f38" - }); - const foliateFiles = Object.freeze([ - "LICENSE", "comic-book.js", "epub.js", "epubcfi.js", "fb2.js", "fixed-layout.js", - "mobi.js", "overlayer.js", "paginator.js", "pdf.js", "progress.js", "reader.html", - "reader.js", "search.js", "text-walker.js", "tts.js", "ui/menu.js", "ui/tree.js", "view.js" - ]); - const foliateVendors = { - fflateLicense: { - url: "https://cdn.jsdelivr.net/npm/fflate@0.8.3/LICENSE", - file: "LICENSE_fflate", - sha256: "0a1df3a083d0c010560aa342e87959c8c1070e6fd54545741f083f22d0c8b551" - }, - zipLicense: { - url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/LICENSE", - file: "LICENSE_zipjs", - sha256: "1b7ebc8d7889ed25491484ab2b102370742ca6c0b26650a0c62cc2269b579b84" - }, - fflate: { - url: "https://cdn.jsdelivr.net/npm/fflate@0.8.3/esm/browser.js", - file: "fflate.js", - sha256: "b7ca4450b19559a1d50eb381adcee94b82449674be4cd17789d9beba7e6122a1" - }, - zip: { - url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/index.min.js", - file: "zip.js", - sha256: "715a4067bb71d750d4af8e60390e48894072f65501e0442e53f252cbfc45cfbc" - }, - textLayer: { - url: "https://cdn.jsdelivr.net/gh/mozilla/pdf.js@v6.5.438/web/text_layer_builder.css", - file: "pdfjs/text_layer_builder.css", - sha256: "5b21bcb7d703cae5b8eebf9c8579435409aaf351b62e7518327ada60bdd0946f" - }, - annotationLayer: { - url: "https://cdn.jsdelivr.net/gh/mozilla/pdf.js@v6.5.438/web/annotation_layer_builder.css", - file: "pdfjs/annotation_layer_builder.css", - sha256: "eb7905a0db3e35b4a069c7ba47048fc131ccc2eccc8c4205e4e20dac58c80176" - } - }; - for (const vendor of Object.values(foliateVendors)) Object.freeze(vendor); const readerComponentFiles = Object.freeze([ "reader/ui/reader-document-styles.mjs", - "reader/core/reader-diagnostics.mjs", "reader/core/reader-lifecycle.mjs", "reader/core/reader-source.mjs", "reader/ui/reader-ui.mjs", + "reader/core/reader-shared-content.mjs", "reader/core/reader-diagnostics.mjs", "reader/core/reader-lifecycle.mjs", "reader/core/reader-source.mjs", "reader/ui/reader-ui.mjs", "reader/ui/reader-toc.mjs", "reader/search/reader-search-backends.mjs", "reader/pdf/reader-pdf-scheduler.mjs", "reader/ui/reader-navigation.mjs", - "reader/formats/reader-foliate-format.mjs", "reader/ui/reader-progress.mjs", "reader/ui/reader-bookmarks.mjs", "reader/formats/reader-media-format.mjs", + "reader/ui/reader-progress.mjs", "reader/ui/reader-bookmarks.mjs", "reader/formats/reader-media-format.mjs", "reader/core/reader-document-loader.mjs", "reader/pdf/reader-pdf-page-window.mjs", "reader/pdf/reader-pdf-text-runtime.mjs", "reader/formats/reader-html-format.mjs", "reader/pdf/reader-pdf-renderer.mjs", "reader/formats/reader-text-format.mjs", "reader/formats/reader-chapter-format.mjs", "reader/formats/reader-format-controller.mjs", @@ -235,8 +202,8 @@ const djvuDecoderAssets = (base) => ["scalar/djvu_rs.js", "scalar/djvu_rs_bg.wasm", "simd128/djvu_rs.js", "simd128/djvu_rs_bg.wasm"].map(file => base + "vendor/djvu-rs-reader/release-06c82c74447d-03087b1edf0c/" + file); - /** @param {string} extension @param {string} base @param {string} [foliateSuffix] @param {string} [workerWrapper] @returns {string[]} */ - function engineAssets(extension, base, foliateSuffix = "", workerWrapper = base + "reader/pdf/pdf-worker-wrapper.mjs") { + /** @param {string} extension @param {string} base @param {string} [_unusedSuffix] @param {string} [workerWrapper] @returns {string[]} */ + function engineAssets(extension, base, _unusedSuffix = "", workerWrapper = base + "reader/pdf/pdf-worker-wrapper.mjs") { if (extension === "pdf") return [ vendorUrl("pdf", base), @@ -245,15 +212,6 @@ ...pdfSupportAssets(base) ]; if (["djvu", "djv"].includes(extension)) return djvuSelectedAssets(base); - // view.js statically imports these leaf modules; warm them with it so they - // are not discovered one round trip later. Format modules follow makeBook. - /** @param {...string} files */ - const foliate = (...files) => [base + "foliate-reader/view.js" + foliateSuffix, - ...["epubcfi.js", "progress.js", "overlayer.js", "text-walker.js", ...files].map(file => base + "foliate-reader/" + file)]; - if (extension === "epub") return foliate("vendor/zip.js", "epub.js", "paginator.js"); - if (["mobi", "azw", "azw3"].includes(extension)) return foliate("mobi.js", "vendor/fflate.js", "paginator.js"); - if (extension === "fb2") return foliate("fb2.js", "paginator.js"); - if (extension === "fbz") return foliate("vendor/zip.js", "fb2.js", "paginator.js"); if (["md", "markdown"].includes(extension)) return [vendorUrl("marked", base), vendorUrl("purify", base)]; if (["html", "htm"].includes(extension)) return [vendorUrl("purify", base)]; @@ -331,10 +289,6 @@ } const resources = Object.freeze({ vendors: Object.freeze(vendors), - foliateVendors: Object.freeze(foliateVendors), - foliateRevision, - foliateArchive, - foliateFiles, pdfArchive, ruffleArchive, ruffleAssets, diff --git a/static/reader.css b/static/reader.css index b322ea6f51efe0f443b0be7e8ac05643d53a4eea..b215e4d3a4552e2b2e325e552b63dff1873a9e5b 100644 --- a/static/reader.css +++ b/static/reader.css @@ -1250,86 +1250,13 @@ body { text-align: center; line-height: 1.6; } -/* Chapter bundles and Foliate hosts. Chapter Shadow DOM has its own stylesheet. */ +/* Chapter bundles. */ .epub-frame { width: 100%; height: auto; min-height: 100%; background: #181b1e; } -.foliate-reader-view { - display: block; - width: 100%; - height: 100%; - min-height: 100%; - background: #181b1e; -} -.foliate-continuous { - --reader-book-link: #8ab4e8; - width: min(100%, 900px); - min-height: 100%; - margin: 0 auto; - padding: 24px 20px 64px; - background: #181b1e; - color: #e7e9eb; -} -.foliate-continuous > article { - min-height: 0 !important; - height: auto !important; - margin: 0 auto 32px; - padding-top: 0 !important; - line-height: 1.7; - break-before: auto !important; - page-break-before: auto !important; - font-size: calc(var(--reader-prose-size, 1em) * var(--reader-zoom)); -} -/* Virtualized chapters must reserve their measured height. */ -.foliate-continuous > article.foliate-section-placeholder { - height: var(--foliate-placeholder-height) !important; - min-height: var(--foliate-placeholder-height) !important; - padding: 0 !important; - contain: strict; - pointer-events: none; -} -.foliate-continuous > article > :first-child { - margin-top: 0 !important; -} -.foliate-continuous a { - color: #8ab4e8 !important; -} -.foliate-continuous a[href]:not([href^="http:"]):not([href^="https:"]) { - text-decoration: none !important; -} -.foliate-continuous :is(p, div, span, li, td, th, blockquote, pre, code, h1, h2, h3, h4, h5, h6) { - color: inherit !important; -} -.foliate-continuous img, -.foliate-continuous svg, -.foliate-continuous video { - max-width: 100%; - height: auto; -} -:root[data-theme="light"] .foliate-continuous { - --reader-book-link: #185abc; - background: #fff; - color: #202124; -} -:root[data-theme="light"] .foliate-continuous a { - color: #185abc !important; -} -.reader-content[data-mode="foliate"] { - width: 100%; - height: calc(100vh - var(--reader-toolbar-height)); - height: calc(100dvh - var(--reader-toolbar-height)); - min-height: calc(100vh - var(--reader-toolbar-height)); - min-height: calc(100dvh - var(--reader-toolbar-height)); - padding: 0; -} -.reader-content[data-mode="foliate"] > .foliate-reader-view { - width: 100%; - height: 100%; - min-height: 320px; -} /* Isolated HTML */ .html-frame { display: block; @@ -1491,8 +1418,7 @@ body { --reader-paper: #f7f3eb; } .reader-viewport:has(> .reader-content:is([data-mode="text"], [data-mode="markdown"])), - .reader-content[data-mode="epub-chapters"] > .epub-frame, - .reader-content[data-mode="foliate"] > .foliate-continuous { + .reader-content[data-mode="epub-chapters"] > .epub-frame { background-color: var(--reader-paper); } } @@ -1580,10 +1506,7 @@ body { outline: 3px solid currentColor; outline-offset: 2px; } - /* Shadow-root chapter links need this preference in their JS-owned stylesheet. */ - .reader-content a, - .foliate-continuous a, - .foliate-continuous a[href]:not([href^="http:"]):not([href^="https:"]) { + .reader-content a { text-decoration: underline !important; } .reader-pdf-text span.full-search-highlight, @@ -1695,12 +1618,6 @@ body { max-width: none; overflow-wrap: anywhere; } - .foliate-continuous { - padding: 16px 12px 48px; - } - .foliate-continuous > article { - overflow-wrap: anywhere; - } .html-frame { height: calc(100dvh - var(--reader-toolbar-height)); } diff --git a/static/reader.js b/static/reader.js index 474db536010f0ce84dedb79c978dd43743b5e097..e6e633da5bb38a9cab2e9907a78f43be10b02e5d 100644 --- a/static/reader.js +++ b/static/reader.js @@ -1,6 +1,7 @@ import { createReaderDomSearch, fullSearchEscape, fullSearchSnippet, fullSearchPageOffset } from "./reader/search/reader-dom-search.mjs"; import { createReaderSearchController } from "./reader/search/reader-search-controller.mjs"; import { createReaderImageLoader } from "./reader/formats/reader-image-loader.mjs"; +import { chapterAnchorCandidates, createImageSettler } from "./reader/core/reader-shared-content.mjs"; import "/static/reader-resources.js"; import "/static/reader/core/reader-contract.js"; import "/static/reader/core/reader-request-manager.js"; @@ -30,7 +31,6 @@ import { createReaderSearchBackends, createReaderPdfScheduler, createReaderNavigation, - createReaderFoliateFormat, createReaderProgress, createReaderBookmarks, createReaderMediaFormat, @@ -56,8 +56,6 @@ const readerContext = { get DISCOURSE_TITLE_SELECTOR() { return DISCOURSE_TITLE_SELECTOR; }, get EPUB_HTML_TAGS() { return EPUB_HTML_TAGS; }, get EPUB_HTML_VOID_TAGS() { return EPUB_HTML_VOID_TAGS; }, - get FOLIATE_LOADED_SECTION_LIMIT() { return FOLIATE_LOADED_SECTION_LIMIT; }, - get FOLIATE_PREFETCH_MARGIN() { return FOLIATE_PREFETCH_MARGIN; }, get HTML_FRAME_STYLE() { return HTML_FRAME_STYLE; }, get MARKED_URL() { return MARKED_URL; }, get PDFJS_CMAP_URL() { return PDFJS_CMAP_URL; }, @@ -91,7 +89,6 @@ const readerContext = { get seedPdfPageGeometry() { return seedPdfPageGeometry; }, set seedPdfPageGeometry(value) { seedPdfPageGeometry = value; }, get acquirePdfRenderSlot() { return acquirePdfRenderSlot; }, set acquirePdfRenderSlot(value) { acquirePdfRenderSlot = value; }, get acquirePdfTextSlot() { return acquirePdfTextSlot; }, set acquirePdfTextSlot(value) { acquirePdfTextSlot = value; }, - get activateFoliateTocEntry() { return activateFoliateTocEntry; }, set activateFoliateTocEntry(value) { activateFoliateTocEntry = value; }, get applyChapterSearchPage() { return applyChapterSearchPage; }, get applyInitialRestoration() { return applyInitialRestoration; }, set applyInitialRestoration(value) { applyInitialRestoration = value; }, get applyReaderMetadata() { return applyReaderMetadata; }, set applyReaderMetadata(value) { applyReaderMetadata = value; }, @@ -108,7 +105,6 @@ const readerContext = { get cancelSpeculativePdfRenders() { return cancelSpeculativePdfRenders; }, set cancelSpeculativePdfRenders(value) { cancelSpeculativePdfRenders = value; }, get capability() { return capability; }, set capability(value) { capability = value; }, get captureChapterPosition() { return captureChapterPosition; }, set captureChapterPosition(value) { captureChapterPosition = value; }, - get captureFoliateBookmarkPosition() { return captureFoliateBookmarkPosition; }, set captureFoliateBookmarkPosition(value) { captureFoliateBookmarkPosition = value; }, get chapterManifestCleanup() { return chapterManifestCleanup; }, set chapterManifestCleanup(value) { chapterManifestCleanup = value; }, get chapterManifestLoader() { return chapterManifestLoader; }, set chapterManifestLoader(value) { chapterManifestLoader = value; }, get chapterManifestObserver() { return chapterManifestObserver; }, set chapterManifestObserver(value) { chapterManifestObserver = value; }, @@ -138,9 +134,7 @@ const readerContext = { get downloadUrl() { return downloadUrl; }, set downloadUrl(value) { downloadUrl = value; }, get drainPdfTextWaiters() { return drainPdfTextWaiters; }, set drainPdfTextWaiters(value) { drainPdfTextWaiters = value; }, get emptyPanel() { return emptyPanel; }, set emptyPanel(value) { emptyPanel = value; }, - get epubBook() { return epubBook; }, set epubBook(value) { epubBook = value; }, get epubContentBody() { return epubContentBody; }, set epubContentBody(value) { epubContentBody = value; }, - get epubRendition() { return epubRendition; }, set epubRendition(value) { epubRendition = value; }, get epubSeekFrame() { return epubSeekFrame; }, set epubSeekFrame(value) { epubSeekFrame = value; }, get epubSeekPromise() { return epubSeekPromise; }, set epubSeekPromise(value) { epubSeekPromise = value; }, get epubSeekTarget() { return epubSeekTarget; }, set epubSeekTarget(value) { epubSeekTarget = value; }, @@ -151,16 +145,7 @@ const readerContext = { get filterPanel() { return filterPanel; }, set filterPanel(value) { filterPanel = value; }, get folderNavigationTarget() { return folderNavigationTarget; }, set folderNavigationTarget(value) { folderNavigationTarget = value; }, get folderReturnUrl() { return folderReturnUrl; }, - get foliateChapterRepository() { return foliateChapterRepository; }, set foliateChapterRepository(value) { foliateChapterRepository = value; }, - get foliateContinuous() { return foliateContinuous; }, set foliateContinuous(value) { foliateContinuous = value; }, - get foliateScrollAnchors() { return foliateScrollAnchors; }, - get foliateScrollFrame() { return foliateScrollFrame; }, set foliateScrollFrame(value) { foliateScrollFrame = value; }, - get foliateSectionLoader() { return foliateSectionLoader; }, set foliateSectionLoader(value) { foliateSectionLoader = value; }, - get foliateSectionObserver() { return foliateSectionObserver; }, set foliateSectionObserver(value) { foliateSectionObserver = value; }, - get foliateSectionRoot() { return foliateSectionRoot; }, set foliateSectionRoot(value) { foliateSectionRoot = value; }, - get foliateSectionSettler() { return foliateSectionSettler; }, set foliateSectionSettler(value) { foliateSectionSettler = value; }, - get foliateSectionVirtualizer() { return foliateSectionVirtualizer; }, set foliateSectionVirtualizer(value) { foliateSectionVirtualizer = value; }, - get foliateWindowFrame() { return foliateWindowFrame; }, set foliateWindowFrame(value) { foliateWindowFrame = value; }, + get chapterScrollAnchors() { return chapterScrollAnchors; }, get formatAdapters() { return formatAdapters; }, get formatMediaTime() { return formatMediaTime; }, set formatMediaTime(value) { formatMediaTime = value; }, get fullSearchButton() { return fullSearchButton; }, @@ -187,7 +172,6 @@ const readerContext = { get imageLoader() { return imageLoader; }, get independentTextCaret() { return independentTextCaret; }, get initialReaderPage() { return initialReaderPage; }, set initialReaderPage(value) { initialReaderPage = value; }, - get initialReaderTargetSection() { return initialReaderTargetSection; }, set initialReaderTargetSection(value) { initialReaderTargetSection = value; }, get installReaderTapSelectionClear() { return installReaderTapSelectionClear; }, set installReaderTapSelectionClear(value) { installReaderTapSelectionClear = value; }, get isPdfPageVisible() { return isPdfPageVisible; }, set isPdfPageVisible(value) { isPdfPageVisible = value; }, get isReaderGenerationCurrent() { return isReaderGenerationCurrent; }, set isReaderGenerationCurrent(value) { isReaderGenerationCurrent = value; }, @@ -335,7 +319,6 @@ const readerContext = { get releasePdfWorker() { return releasePdfWorker; }, set releasePdfWorker(value) { releasePdfWorker = value; }, get renderBookmarks() { return renderBookmarks; }, set renderBookmarks(value) { renderBookmarks = value; }, get renderChapterManifest() { return renderChapterManifest; }, set renderChapterManifest(value) { renderChapterManifest = value; }, - get renderFoliate() { return renderFoliate; }, set renderFoliate(value) { renderFoliate = value; }, get renderFullSearchResults() { return renderFullSearchResults; }, get renderHtml() { return renderHtml; }, set renderHtml(value) { renderHtml = value; }, get renderImageDocument() { return renderImageDocument; }, set renderImageDocument(value) { renderImageDocument = value; }, @@ -358,20 +341,17 @@ const readerContext = { get resolvedReaderData() { return resolvedReaderData; }, set resolvedReaderData(value) { resolvedReaderData = value; }, get restorationFailed() { return restorationFailed; }, set restorationFailed(value) { restorationFailed = value; }, get restoreChapterPosition() { return restoreChapterPosition; }, set restoreChapterPosition(value) { restoreChapterPosition = value; }, - get restoreFoliateBookmarkPosition() { return restoreFoliateBookmarkPosition; }, set restoreFoliateBookmarkPosition(value) { restoreFoliateBookmarkPosition = value; }, get restoreFormat() { return restoreFormat; }, set restoreFormat(value) { restoreFormat = value; }, get retryReaderProxy() { return retryReaderProxy; }, set retryReaderProxy(value) { retryReaderProxy = value; }, get retryableReaderProxyError() { return retryableReaderProxyError; }, set retryableReaderProxyError(value) { retryableReaderProxyError = value; }, get returnHistoryKey() { return returnHistoryKey; }, get runFullSearch() { return runFullSearch; }, get sanitizeEpubDocument() { return sanitizeEpubDocument; }, set sanitizeEpubDocument(value) { sanitizeEpubDocument = value; }, - get sanitizeFoliateStyles() { return sanitizeFoliateStyles; }, set sanitizeFoliateStyles(value) { sanitizeFoliateStyles = value; }, get saveDeadline() { return saveDeadline; }, set saveDeadline(value) { saveDeadline = value; }, get saveProgress() { return saveProgress; }, set saveProgress(value) { saveProgress = value; }, get progressNotSaved() { return progressNotSaved; }, get captureProgressEntry() { return captureProgressEntry; }, get saveTimer() { return saveTimer; }, set saveTimer(value) { saveTimer = value; }, - get scheduleFoliateScrollSync() { return scheduleFoliateScrollSync; }, set scheduleFoliateScrollSync(value) { scheduleFoliateScrollSync = value; }, get scheduleMarkerSync() { return scheduleMarkerSync; }, set scheduleMarkerSync(value) { scheduleMarkerSync = value; }, get schedulePdfBookSearchPrefetch() { return schedulePdfBookSearchPrefetch; }, set schedulePdfBookSearchPrefetch(value) { schedulePdfBookSearchPrefetch = value; }, get schedulePdfManifestPrefetch() { return schedulePdfManifestPrefetch; }, set schedulePdfManifestPrefetch(value) { schedulePdfManifestPrefetch = value; }, @@ -379,7 +359,6 @@ const readerContext = { get scheduleSave() { return scheduleSave; }, set scheduleSave(value) { scheduleSave = value; }, get searchConcentratedPdf() { return searchConcentratedPdf; }, set searchConcentratedPdf(value) { searchConcentratedPdf = value; }, get searchState() { return searchState; }, - get seekFoliateProgress() { return seekFoliateProgress; }, set seekFoliateProgress(value) { seekFoliateProgress = value; }, get selectPanel() { return selectPanel; }, set selectPanel(value) { selectPanel = value; }, get setPdfPageLoadingState() { return setPdfPageLoadingState; }, set setPdfPageLoadingState(value) { setPdfPageLoadingState = value; }, get setReaderPanelOpen() { return setReaderPanelOpen; }, set setReaderPanelOpen(value) { setReaderPanelOpen = value; }, @@ -399,7 +378,6 @@ const readerContext = { get swfPlayer() { return swfPlayer; }, set swfPlayer(value) { swfPlayer = value; }, get syncCapabilityControls() { return syncCapabilityControls; }, set syncCapabilityControls(value) { syncCapabilityControls = value; }, get syncCurrentPageFromMarker() { return syncCurrentPageFromMarker; }, set syncCurrentPageFromMarker(value) { syncCurrentPageFromMarker = value; }, - get syncFoliateScrollLocation() { return syncFoliateScrollLocation; }, set syncFoliateScrollLocation(value) { syncFoliateScrollLocation = value; }, get syncHeadingLocation() { return syncHeadingLocation; }, set syncHeadingLocation(value) { syncHeadingLocation = value; }, get takePdfManifestPrefetch() { return takePdfManifestPrefetch; }, set takePdfManifestPrefetch(value) { takePdfManifestPrefetch = value; }, get themeAnimationTimer() { return themeAnimationTimer; }, set themeAnimationTimer(value) { themeAnimationTimer = value; }, @@ -484,8 +462,6 @@ const readerContext = { get cancelPdfManifestPrefetch() { return cancelPdfManifestPrefetch; }, set cancelPdfManifestPrefetch(value) { cancelPdfManifestPrefetch = value; }, get chapterSearchModule() { return chapterSearchModule; }, set chapterSearchModule(value) { chapterSearchModule = value; }, get cleanTocLabel() { return cleanTocLabel; }, set cleanTocLabel(value) { cleanTocLabel = value; }, - get cloneFoliateDocument() { return cloneFoliateDocument; }, set cloneFoliateDocument(value) { cloneFoliateDocument = value; }, - get createFoliateSection() { return createFoliateSection; }, set createFoliateSection(value) { createFoliateSection = value; }, get createHeadingLocationCache() { return createHeadingLocationCache; }, set createHeadingLocationCache(value) { createHeadingLocationCache = value; }, get createPdfShellWindow() { return createPdfShellWindow; }, set createPdfShellWindow(value) { createPdfShellWindow = value; }, get createTocRow() { return createTocRow; }, set createTocRow(value) { createTocRow = value; }, @@ -496,10 +472,6 @@ const readerContext = { get estimatePdfTextContentBytes() { return estimatePdfTextContentBytes; }, set estimatePdfTextContentBytes(value) { estimatePdfTextContentBytes = value; }, get excerptFromCaret() { return excerptFromCaret; }, set excerptFromCaret(value) { excerptFromCaret = value; }, get fetchWithReaderTimeout() { return fetchWithReaderTimeout; }, set fetchWithReaderTimeout(value) { fetchWithReaderTimeout = value; }, - get foliateSearchAnchor() { return foliateSearchAnchor; }, set foliateSearchAnchor(value) { foliateSearchAnchor = value; }, - get foliateSectionQuery() { return foliateSectionQuery; }, set foliateSectionQuery(value) { foliateSectionQuery = value; }, - get foliateTocEntries() { return foliateTocEntries; }, set foliateTocEntries(value) { foliateTocEntries = value; }, - get fullSearchFoliateMatches() { return fullSearchFoliateMatches; }, set fullSearchFoliateMatches(value) { fullSearchFoliateMatches = value; }, get getPdfPersistentTextStore() { return getPdfPersistentTextStore; }, set getPdfPersistentTextStore(value) { getPdfPersistentTextStore = value; }, get highlightPanelItem() { return highlightPanelItem; }, set highlightPanelItem(value) { highlightPanelItem = value; }, get loadPdfEngine() { return loadPdfEngine; }, set loadPdfEngine(value) { loadPdfEngine = value; }, @@ -526,20 +498,15 @@ const readerContext = { get publishSearchResults() { return publishSearchResults; }, set publishSearchResults(value) { publishSearchResults = value; }, get readPdfOcrJson() { return readPdfOcrJson; }, set readPdfOcrJson(value) { readPdfOcrJson = value; }, get readerAssetObjectFamily() { return readerAssetObjectFamily; }, set readerAssetObjectFamily(value) { readerAssetObjectFamily = value; }, - get refreshFoliateWindow() { return refreshFoliateWindow; }, set refreshFoliateWindow(value) { refreshFoliateWindow = value; }, get renderPdfImageShell() { return renderPdfImageShell; }, set renderPdfImageShell(value) { renderPdfImageShell = value; }, get renderVirtualToc() { return renderVirtualToc; }, set renderVirtualToc(value) { renderVirtualToc = value; }, get repairHtmlContrast() { return repairHtmlContrast; }, set repairHtmlContrast(value) { repairHtmlContrast = value; }, get resolveReaderSource() { return resolveReaderSource; }, set resolveReaderSource(value) { resolveReaderSource = value; }, get restoreInitialPosition() { return restoreInitialPosition; }, set restoreInitialPosition(value) { restoreInitialPosition = value; }, - get rewriteFoliateResources() { return rewriteFoliateResources; }, set rewriteFoliateResources(value) { rewriteFoliateResources = value; }, get sanitizeOfflineHtml() { return sanitizeOfflineHtml; }, set sanitizeOfflineHtml(value) { sanitizeOfflineHtml = value; }, get sanitizeReaderDocument() { return sanitizeReaderDocument; }, set sanitizeReaderDocument(value) { sanitizeReaderDocument = value; }, - get scheduleFoliateWindowRefresh() { return scheduleFoliateWindowRefresh; }, set scheduleFoliateWindowRefresh(value) { scheduleFoliateWindowRefresh = value; }, get searchChapterBook() { return searchChapterBook; }, set searchChapterBook(value) { searchChapterBook = value; }, get setBookmarkDialogModal() { return setBookmarkDialogModal; }, set setBookmarkDialogModal(value) { setBookmarkDialogModal = value; }, - get setupFoliateWindow() { return setupFoliateWindow; }, set setupFoliateWindow(value) { setupFoliateWindow = value; }, - get trimFoliateSections() { return trimFoliateSections; }, set trimFoliateSections(value) { trimFoliateSections = value; }, get trimPdfManifestPrefetches() { return trimPdfManifestPrefetches; }, set trimPdfManifestPrefetches(value) { trimPdfManifestPrefetches = value; }, get trimPdfSurfaces() { return trimPdfSurfaces; }, set trimPdfSurfaces(value) { trimPdfSurfaces = value; }, get waitForSpreadsheetImages() { return waitForSpreadsheetImages; }, set waitForSpreadsheetImages(value) { waitForSpreadsheetImages = value; } @@ -579,7 +546,7 @@ let { let { updateSearchState, publishSearchResults, clearSearchHighlights, chapterSearchModule, - searchChapterBook, navigateChapterSearchResult, fullSearchFoliateMatches, navigateFoliateSearchResult, + searchChapterBook, navigateChapterSearchResult, searchReaderText } = createReaderSearchBackends(readerContext); @@ -600,14 +567,6 @@ let { navigateReader, notePdfScrollIntent, installReaderTapSelectionClear } = createReaderNavigation(readerContext); -let { - foliateSectionRoot, foliateSectionQuery, foliateSectionCandidates, syncFoliateScrollLocation, - refreshFoliateWindow, scheduleFoliateWindowRefresh, trimFoliateSections, scheduleFoliateScrollSync, - activateFoliateTocEntry, cloneFoliateDocument, foliateSearchAnchor, settleReaderImages, - rewriteFoliateResources, createFoliateSection, setupFoliateWindow, foliateTocEntries, - renderFoliate -} = createReaderFoliateFormat(readerContext); - let { scheduleSave, saveProgress, progressNotSaved, captureProgressEntry, placeReadingProgress, currentReaderUrl, loadReaderRestoration, getInitialReaderRestoration, initialReaderPage, readerProgressPercent, @@ -618,8 +577,7 @@ let { } = createReaderProgress(readerContext); let { - consumeBookmarkHandoff, excerptFromCaret, bookmarkExcerpt, captureFoliateBookmarkPosition, - restoreFoliateBookmarkPosition, seekFoliateProgress, renderBookmarks, captureBookmarkSnapshot, + consumeBookmarkHandoff, excerptFromCaret, bookmarkExcerpt, renderBookmarks, captureBookmarkSnapshot, setBookmarkDialogModal, openBookmarkPopover, closeBookmarkPopover } = createReaderBookmarks(readerContext); @@ -649,7 +607,7 @@ let { } = createReaderPdfTextRuntime(readerContext); let { - normalizeEpubDocument, sanitizeReaderDocument, sanitizeEpubDocument, sanitizeFoliateStyles, parseChapterDocument, + normalizeEpubDocument, sanitizeReaderDocument, sanitizeEpubDocument, parseChapterDocument, epubContentBody, renderText, sanitizeOfflineHtml, buildDiscourseDocument, prepareHtmlDocument, buildHtmlFrameSource, waitForSpreadsheetImages, renderHtml, detectHtmlEncoding, repairHtmlContrast @@ -893,29 +851,8 @@ let pdfManifestPrefetchCount = 0; let pdfManifestPrefetchWrapped = false; readerBindings.ownPdfPrefetchAndQueues(); -/** @type {import('../typings/reader-foliate-format-strict').FoliateView | null} */ -let epubRendition = null; -/** @type {import('../typings/reader-foliate-format-strict').FoliateBook | null} */ -let epubBook = null; -let foliateContinuous = false; -/** @type {ReturnType | null} */ -let foliateChapterRepository = null; -/** @type {ReturnType | null} */ -let foliateSectionVirtualizer = null; -/** @type {import('../typings/reader-foliate-format-strict').FoliateLoader | null} */ -let foliateSectionLoader = null; -/** @type {(() => Promise) | null} */ -let foliateSectionSettler = null; -/** @type {IntersectionObserver | null} */ -let foliateSectionObserver = null; -let foliateScrollFrame = 0, foliateWindowFrame = 0; -/** @type {number | null} */ -let initialReaderTargetSection = null; /** @type {import('../typings/reader-entry-strict').ReaderEntryFormatState['chapterManifestCleanup']} */ let chapterManifestCleanup = null; -const FOLIATE_PREFETCH_SECTIONS = 6; -const FOLIATE_PREFETCH_MARGIN = 4000; -const FOLIATE_LOADED_SECTION_LIMIT = 12; const PDF_PREFETCH_MARGIN = 2400; const TOC_VIRTUALIZATION_THRESHOLD = 500; const TOC_VIRTUAL_ROW_HEIGHT = 40; @@ -1083,10 +1020,11 @@ const holdReaderDestination = (target, offset = 0) => { return release; }; -const foliateScrollAnchors = readerRuntime.track( +let settleReaderImages = createImageSettler(readerContext); +const chapterScrollAnchors = readerRuntime.track( VoiceOfMLReaderScroll.createScrollAnchorManager({ viewport, - candidates: foliateSectionCandidates + candidates: () => chapterAnchorCandidates(content) }) ); @@ -1145,9 +1083,6 @@ readerBindings.bindSelectionAndPageLifecycle(); // Resolve once, then keep source URLs, capability, and presentation in sync. -// Foliate keeps a source-to-rendered text mapping because CFI addresses the -// original document, before sanitization and insertion into a shadow root. - // Reading progress controls and undo. const progressTools = document.createElement("div"); readerBindings.mountProgressControls(); @@ -1171,7 +1106,7 @@ readerBindings.bindProgressActions(); const domSearch = createReaderDomSearch({ content, runtime: readerRuntime, isCurrent: isReaderGenerationCurrent, yieldTask: waitForReader, getTocEntries: () => navigationState.tocEntries, - unwrapRoot: foliateSectionRoot, + unwrapRoot: root => root, publishPage: (page, loader, partial) => { fullSearchSession.pageLoader = loader; fullSearchSession.page = page; @@ -1200,8 +1135,7 @@ const fullSearchController = createReaderSearchController({ pdfClient: () => pdfBookSearchClient, chapterResult: result => ({ ...result, activate: (generation = readerRuntime.currentGeneration("navigation")) => navigateChapterSearchResult(result, generation) }), - activate: (result, generation) => "activate" in result - ? result.activate(generation) : navigateFoliateSearchResult(result, generation) + activate: (result, generation) => result.activate(generation) }, navigation: { begin: beginReaderNavigation, diff --git a/static/reader/core/reader-bindings.mjs b/static/reader/core/reader-bindings.mjs index cf54f0ae6ca3c327be6017baf7714ab18593ffd4..acaca732bd8ce60f88bcacdcfc8ce50bb4576cd2 100644 --- a/static/reader/core/reader-bindings.mjs +++ b/static/reader/core/reader-bindings.mjs @@ -22,7 +22,7 @@ export function createReaderBindings(readerContext) { if (window.VoiceOfMLReaderPdfDiagnostics === readerContext.pdfDiagnostics) delete window.VoiceOfMLReaderPdfDiagnostics; }); - // Polyfills for vendor engines (pdf.js, foliate): neither helper has a direct + // Polyfills for pdf.js: neither helper has a direct // caller in first-party code, but both are required by pinned vendor bundles. if (!Map.prototype.getOrInsertComputed) { Map.prototype.getOrInsertComputed = function (key, callback) { @@ -274,16 +274,6 @@ export function createReaderBindings(readerContext) { function applyMetadataAndWatchSanitizedContent() { readerContext.applyReaderMetadata(readerContext.resolvedReaderData); - readerContext.contentSanitizerObserver = new MutationObserver(() => { - const seen = new Set(); - for (const article of /** @type {NodeListOf} */ (document.querySelectorAll(".foliate-continuous > article[data-section]"))) { - article.querySelectorAll("style,link[rel=stylesheet]").forEach((node) => node.remove()); - const index = article.dataset.section; - if (seen.has(index)) article.remove(); - else seen.add(index); - } - }); - readerContext.contentSanitizerObserver.observe(readerContext.content, { childList: true, subtree: true }); readerContext.bookmarkPopover.className = "bookmark-popover"; readerContext.bookmarkPopover.setAttribute("role", "dialog"); readerContext.bookmarkPopover.setAttribute("aria-modal", "true"); @@ -487,34 +477,6 @@ export function createReaderBindings(readerContext) { readerContext.trackReaderResource(() => document.removeEventListener("click", readerContext.handleReaderOutsideClick)); readerContext.trackReaderResource(() => { readerContext.headingLocationCache?.dispose(); readerContext.headingLocationCache = null; }); - document.addEventListener("click", async (event) => { - const path = event.composedPath(), - link = /** @type {Element | undefined} */ (path.find((node) => node instanceof Element && node.matches?.("a[href]"))), - article = /** @type {HTMLElement | undefined} */ (path.find( - (node) => - node instanceof Element && node.matches?.(".foliate-continuous article[data-section]") - )); - if (!link || !article || !readerContext.epubRendition?.book) return; - const raw = link.getAttribute("href") || ""; - if (raw.startsWith("/api/reader-resource?")) return; - if (!raw || readerContext.epubRendition.book.isExternal?.(raw) || /^(?:https?:|mailto:|tel:)/i.test(raw)) - return; - event.preventDefault(); - const generation = readerContext.beginReaderNavigation(), - index = Number(article.dataset.section), - section = index < 0 ? readerContext.epubRendition.book.sections[-index - 1] - : readerContext.epubRendition.book.sections.filter((item) => item.linear !== "no")[index]; - let href = raw; - try { - href = section?.resolveHref?.(raw) || raw; - } catch (_) {} - try { - await readerContext.activateFoliateTocEntry({ href }, generation); - } catch (error) { - readerContext.reportNavigationError(error, generation); - } - }); - // Bookmark dialog owns focus and temporarily makes only its siblings inert. readerContext.bookmarkRibbon.addEventListener("click", () => readerContext.openBookmarkPopover(readerContext.bookmarkRibbon)); @@ -803,7 +765,6 @@ export function createReaderBindings(readerContext) { }); window.addEventListener("pageshow", (event) => { if (event.persisted && !readerContext.readerLifecycle.disposed) { - readerContext.scheduleFoliateScrollSync(); readerContext.updateProgressTools(); } }); diff --git a/static/reader/core/reader-contract.js b/static/reader/core/reader-contract.js index becf10817041d2b3379f693ec4b8df78cd0b53d2..280795323677c254c7110b115ecbc1881f940665 100644 --- a/static/reader/core/reader-contract.js +++ b/static/reader/core/reader-contract.js @@ -118,12 +118,6 @@ "pdf-pages": "pdf-pages", "image-pages": "image-pages", image: "image", - epub: "foliate", - mobi: "foliate", - azw: "foliate", - azw3: "foliate", - fb2: "foliate", - fbz: "foliate", "epub-chapters": "epub-chapters", html: "html", htm: "html", @@ -174,14 +168,6 @@ pagination: true, media: false }, - foliate: { - toc: true, - search: true, - zoom: true, - bookmarks: true, - pagination: false, - media: false - }, "epub-chapters": { toc: true, search: true, diff --git a/static/reader/core/reader-lifecycle.mjs b/static/reader/core/reader-lifecycle.mjs index c583d189e1a3a3178d94b79ab4ee4d55a9ae10e1..52bb30c55552a6d1d3fd05199ded6f5cdef5980b 100644 --- a/static/reader/core/reader-lifecycle.mjs +++ b/static/reader/core/reader-lifecycle.mjs @@ -16,13 +16,11 @@ * @property {number} themeAnimationTimer * @property {number} panelAnimationTimer * @property {number} markerFrame - * @property {number} foliateScrollFrame - * @property {number} foliateWindowFrame * @property {number} epubSeekFrame * @property {{mode: string | null} | null | undefined} capability * @property {HTMLElement} loadingIndicator * @property {HTMLElement} loadingStatus - * @property {{preserve(change: () => T): T}} foliateScrollAnchors + * @property {{preserve(change: () => T): T}} chapterScrollAnchors * @property {(open: boolean) => unknown} setReaderPanelOpen * @property {() => unknown} stopReaderWork * @property {{dispose(): unknown}} readerRequestManager @@ -123,8 +121,8 @@ export function createReaderLifecycle(readerContext) { } function markReaderContentReady() { - if ((readerContext.capability?.mode === "foliate" || readerContext.capability?.mode === "epub-chapters") && readerContext.loadingIndicator.isConnected) - readerContext.foliateScrollAnchors.preserve(() => readerContext.loadingIndicator.remove()); + if (readerContext.capability?.mode === "epub-chapters" && readerContext.loadingIndicator.isConnected) + readerContext.chapterScrollAnchors.preserve(() => readerContext.loadingIndicator.remove()); else readerContext.loadingIndicator.remove(); readerContext.loadingStatus.hidden = true; } @@ -156,14 +154,12 @@ export function createReaderLifecycle(readerContext) { clearTimeout(readerContext.saveTimer); clearTimeout(readerContext.themeAnimationTimer); clearTimeout(readerContext.panelAnimationTimer); - for (const frame of [readerContext.markerFrame, readerContext.foliateScrollFrame, readerContext.foliateWindowFrame, readerContext.epubSeekFrame]) + for (const frame of [readerContext.markerFrame, readerContext.epubSeekFrame]) if (frame) cancelAnimationFrame(frame); readerContext.saveTimer = readerContext.themeAnimationTimer = readerContext.panelAnimationTimer = readerContext.markerFrame = - readerContext.foliateScrollFrame = - readerContext.foliateWindowFrame = readerContext.epubSeekFrame = 0; VoiceOfMLReaderStore.dispose?.(); diff --git a/static/reader/core/reader-runtime.js b/static/reader/core/reader-runtime.js index 953dc537bd014f942a6c23634babe999cf9dc313..be50a72eaa7db94a03076434738fb954f193f154 100644 --- a/static/reader/core/reader-runtime.js +++ b/static/reader/core/reader-runtime.js @@ -67,7 +67,7 @@ navigation: { tocEntries: [], currentChapterIndex: -1 }, search: { query: "", results: [], index: -1 }, panel: { open: false, selected: "toc", showingAllBookmarks: false, editingBookmark: null }, - formats: { active: null, pdf: {}, foliate: {}, html: {}, media: {} }, + formats: { active: null, pdf: {}, html: {}, media: {} }, capability: null, ...(options.initialState || {}) }; diff --git a/static/reader/core/reader-shared-content.mjs b/static/reader/core/reader-shared-content.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9b5a3a36eb2692cf7dfafc2d2f5625ee819434db --- /dev/null +++ b/static/reader/core/reader-shared-content.mjs @@ -0,0 +1,51 @@ +/** Shared content helpers for the chapter reader and HTML documents. + * @param {Element} content + */ +export function chapterAnchorCandidates(content) { + return [...content.querySelectorAll('.reader-epub-chapter')].flatMap(article => [ + article, + ...article.querySelectorAll(':is(h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,img,table)') + ]); +} + +/** @param {{assertReaderActive: () => void, awaitReader: (value: Promise) => Promise}} readerContext */ +export function createImageSettler(readerContext) { + /** @param {ParentNode} root @param {number} [timeoutMs] */ + return async function settleReaderImages(root, timeoutMs = 2500) { + readerContext.assertReaderActive(); + const images = [...root.querySelectorAll(/** @type {'img'} */ ('img[src],img[srcset]'))]; + if (!images.length) return; + let timeout = 0, active = true; + /** @type {Set<() => void>} */ + const cleanups = new Set(); + const decoded = Promise.allSettled(images.map(async image => { + image.loading = 'eager'; + image.decoding = 'async'; + if (!image.complete) await /** @type {Promise} */ (new Promise(resolve => { + const finish = () => { + image.removeEventListener('load', finish); + image.removeEventListener('error', finish); + cleanups.delete(finish); + resolve(); + }; + cleanups.add(finish); + image.addEventListener('load', finish, { once: true }); + image.addEventListener('error', finish, { once: true }); + if (image.complete) finish(); + })); + if (active) { + try { await image.decode?.(); } catch (_) {} + } + })); + try { + await readerContext.awaitReader(Promise.race([ + decoded, + new Promise(resolve => { timeout = setTimeout(resolve, timeoutMs); }) + ])); + } finally { + active = false; + clearTimeout(timeout); + for (const cleanup of cleanups) cleanup(); + } + }; +} diff --git a/static/reader/formats/reader-chapter-format.mjs b/static/reader/formats/reader-chapter-format.mjs index 1e81a63fab2526a9493eafd0becb379809f41024..018c26f8ccfd448797cd5e9db02fd31cc75e7f63 100644 --- a/static/reader/formats/reader-chapter-format.mjs +++ b/static/reader/formats/reader-chapter-format.mjs @@ -224,10 +224,10 @@ export function createReaderChapterFormat(readerContext) { } else frame.insertBefore(article, next || null); }; const preservePosition = chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration); - if (preservePosition) readerContext.foliateScrollAnchors.preserve(insert); + if (preservePosition) readerContext.chapterScrollAnchors.preserve(insert); else insert(); /** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).observe(article); - if (preservePosition) readerContext.foliateScrollAnchors.observe(article); + if (preservePosition) readerContext.chapterScrollAnchors.observe(article); return article; }; /** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter @param {boolean} [previous] */ @@ -253,7 +253,7 @@ export function createReaderChapterFormat(readerContext) { ".reader-epub-chapter[data-chapter], .reader-chapter-sentinel[data-chapter]"); const insert = () => frame.insertBefore(marker, next || null); if (chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) - readerContext.foliateScrollAnchors.preserve(insert); + readerContext.chapterScrollAnchors.preserve(insert); else insert(); /** @type {IntersectionObserver} */ (previous ? chapterPreviousObserver : readerContext.chapterManifestObserver).observe(marker); return marker; @@ -425,7 +425,7 @@ export function createReaderChapterFormat(readerContext) { readerContext.assertReaderActive(); if (loaded.has(chapter.index)) return Promise.resolve(); return chapterScheduler.load(chapter.index, demand, exclusive).then(() => { - readerContext.foliateScrollAnchors.whenIdle(trimChapterWindow); + readerContext.chapterScrollAnchors.whenIdle(trimChapterWindow); }).catch(error => { if (error.name !== "AbortError" && !readerContext.readerAbortController.signal.aborted) { const marker = ensureSentinel(chapter); @@ -454,11 +454,11 @@ export function createReaderChapterFormat(readerContext) { } catch (_) {} const anchor = chapterTarget(/** @type {Element} */ (node), id); if (!anchor) throw new Error("EPUB_MISSING_ANCHOR"); - readerContext.foliateScrollAnchors.invalidate(); + readerContext.chapterScrollAnchors.invalidate(); // Measure the anchor instead of using scrollIntoView: the demanded landing line is // this viewport's top edge, and scrollIntoView can also move ancestor scrollers. readerContext.alignReaderDestination(anchor); - readerContext.foliateScrollAnchors.remember(); + readerContext.chapterScrollAnchors.remember(); // Chapter images and lazy placeholders keep changing height after the jump; hold // the anchor on the landing line until the layout settles. readerContext.holdReaderDestination(anchor); @@ -559,7 +559,7 @@ export function createReaderChapterFormat(readerContext) { marker.style.marginBottom = style.marginBottom; marker.setAttribute("aria-hidden", "true"); /** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).unobserve(article); - readerContext.foliateScrollAnchors.unobserve(article); + readerContext.chapterScrollAnchors.unobserve(article); for (const entry of chapterTocEntries(index)) entry.target = null; for (const image of article.querySelectorAll("img")) image.removeAttribute("src"); article.replaceWith(marker); @@ -569,7 +569,7 @@ export function createReaderChapterFormat(readerContext) { chapterBudget.release(retainedBytes.get(index)); retainedBytes.delete(index); }, - preserve: change => readerContext.foliateScrollAnchors.preserve(change) + preserve: change => readerContext.chapterScrollAnchors.preserve(change) }); function trimChapterWindow() { if (chapterWindowReady && !chapterNavigating) chapterVirtualizer.trim(navigationTargetChapter || chapterFocusIndex); @@ -611,7 +611,7 @@ export function createReaderChapterFormat(readerContext) { current.top < view.bottom) fetchChapter(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(chapterFocusIndex))).catch(() => {}); if (!chapterNavigating) chapterScheduler.prefetch(chapterPrefetchIndices()); - readerContext.foliateScrollAnchors.whenIdle(trimChapterWindow); + readerContext.chapterScrollAnchors.whenIdle(trimChapterWindow); } function scheduleChapterWindow() { if (!chapterWindowFrame) chapterWindowFrame = requestAnimationFrame(refreshChapterWindow); @@ -657,7 +657,7 @@ export function createReaderChapterFormat(readerContext) { if (limit !== progressEnd.limit || limit - viewport.scrollTop > 1) { progressEnd.limit = limit; viewport.scrollTop = limit; - readerContext.foliateScrollAnchors.remember(); + readerContext.chapterScrollAnchors.remember(); } } readerContext.updateProgressTools(); @@ -739,8 +739,8 @@ export function createReaderChapterFormat(readerContext) { }); } chapterWindowReady = true; - if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.foliateScrollAnchors.invalidate(); - for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.foliateScrollAnchors.observe(article); + if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate(); + for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(article); frame.style.overflowAnchor = "none"; scheduleChapterWindow(); readerContext.assertReaderActive(); @@ -798,7 +798,7 @@ export function createReaderChapterFormat(readerContext) { : chapterProgressHeight(rect, marker, last) * progressFraction; viewport.scrollTop += rect.top - marker + offset; } - readerContext.foliateScrollAnchors.remember(); + readerContext.chapterScrollAnchors.remember(); readerContext.syncHeadingLocation(); readerContext.updateProgressTools(); readerContext.scheduleSave(); diff --git a/static/reader/formats/reader-foliate-format.mjs b/static/reader/formats/reader-foliate-format.mjs deleted file mode 100644 index a80f2c3622d28dc1dc8fac58b6cb52ee147e46a0..0000000000000000000000000000000000000000 --- a/static/reader/formats/reader-foliate-format.mjs +++ /dev/null @@ -1,773 +0,0 @@ -import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs"; - -/** @param {import('../../../typings/reader-foliate-format-strict').FoliateFormatContext} readerContext */ -export function createReaderFoliateFormat(readerContext) { - /** @param {Element} article */ - function foliateSectionRoot(article) { - return article?.shadowRoot || article; - } - - /** @param {Element} article @param {string} selector */ - function foliateSectionQuery(article, selector) { - return readerContext.foliateSectionRoot(article)?.querySelector(selector) || null; - } - - function foliateSectionCandidates() { - return [ - ...readerContext.content.querySelectorAll( - ".foliate-continuous > article[data-section]:not(.foliate-section-placeholder), .reader-epub-chapter" - ) - ].flatMap((article) => [ - article, - ...readerContext.foliateSectionRoot(article).querySelectorAll( - ":is(h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,img,table)" - ) - ]); - } - - /** @typedef {{sectionIndex: number, anchor?: import('../../../typings/reader-foliate-format-strict').FoliateAnchor | null, fragment?: string, target?: {getBoundingClientRect(): {top: number}} | null}} LocationEntry */ - /** @param {unknown} entry @returns {entry is LocationEntry} */ - function isFoliateLocationEntry(entry) { - if (typeof entry !== "object" || entry === null || !("sectionIndex" in entry) || typeof entry.sectionIndex !== "number") return false; - if ("anchor" in entry && entry.anchor != null && typeof entry.anchor !== "function") return false; - if ("fragment" in entry && entry.fragment !== undefined && typeof entry.fragment !== "string") return false; - if ("target" in entry && entry.target != null && (typeof entry.target !== "object" || !("getBoundingClientRect" in entry.target) || typeof entry.target.getBoundingClientRect !== "function")) return false; - return true; - } - - /** @type {unknown[] | undefined} */ - let indexedToc; - /** @type {Map} */ - const locations = new Map(); - - /** @param {unknown[]} entries @param {number} section */ - function sectionLocations(entries, section) { - // Foliate resolves sectionIndex before publishing a new TOC array. - if (indexedToc !== entries) { - indexedToc = entries; - locations.clear(); - for (const [index, entry] of entries.entries()) { - if (!isFoliateLocationEntry(entry)) continue; - const key = entry.sectionIndex; - if (Number.isNaN(key)) continue; - const bucket = locations.get(key); - if (bucket) bucket.push([index, entry]); - else locations.set(key, [[index, entry]]); - } - } - return locations.get(section) || []; - } - - function syncFoliateScrollLocation() { - const toc = readerContext.navigationState.tocEntries; - if (!readerContext.foliateContinuous || !toc.length) return; - const rows = /** @type {NodeListOf} */ (document.querySelectorAll(".foliate-continuous article[data-section]")), - top = readerContext.viewport.getBoundingClientRect().top + 80; - let sectionTop = 0, sectionNode = null; - for (const row of rows) { - if (row.hidden) continue; - const rowTop = row.getBoundingClientRect().top; - if (rowTop <= top) { sectionTop = rowTop; sectionNode = row; } - } - if (!sectionNode) return; - const entries = sectionLocations(toc, Number(sectionNode.dataset.section)); - let best = -1; - let bestPosition = -Infinity; - for (const [index, entry] of entries) { - let position = sectionTop; - try { - if (entry.anchor) { - const root = readerContext.foliateSectionRoot(sectionNode); - const anchor = entry.anchor({ - getElementById: (id) => root.querySelector(`[id="${CSS.escape(id)}"]`), - querySelector: (selector) => root.querySelector(selector) - }); - if (anchor) position = anchor.getBoundingClientRect().top; - } - if (entry.fragment) { - const anchor = readerContext.foliateSectionQuery( - sectionNode, - `[id="${CSS.escape(entry.fragment)}"], [name="${CSS.escape(entry.fragment)}"]` - ); - if (anchor) position = anchor.getBoundingClientRect().top; - } - } catch (_) { continue; } - if (position <= top && (position > bestPosition || (position === bestPosition && index > best))) { - best = index; - bestPosition = position; - } - } - if (best < 0) { - let firstPosition = Infinity; - for (const [index, entry] of entries) { - let position; - try { position = entry.target?.getBoundingClientRect?.().top; } catch (_) { continue; } - if (position !== undefined && Number.isFinite(position) && position < firstPosition) { - best = index; - firstPosition = position; - } - } - } - if (best >= 0 && best !== readerContext.navigationState.currentChapterIndex) { - readerContext.updateNavigationState({ currentChapterIndex: best }); - readerContext.updateTocCurrentMark(); - readerContext.updateProgressTools(); - } - } - - function refreshFoliateWindow() { - readerContext.foliateWindowFrame = 0; - readerContext.foliateSectionLoader?.refresh?.(); - } - - function scheduleFoliateWindowRefresh() { - if (!readerContext.foliateWindowFrame) readerContext.foliateWindowFrame = requestAnimationFrame(readerContext.refreshFoliateWindow); - } - - function trimFoliateSections() { - if (!readerContext.foliateContinuous || !readerContext.foliateSectionVirtualizer || - readerContext.content.querySelector(".foliate-supplement-active")) return; - const marker = readerContext.viewport.getBoundingClientRect().top + 80, - rows = [...document.querySelectorAll(".foliate-continuous article[data-section]")].map(row => /** @type {HTMLElement} */ (row)), - current = - rows.find((row) => { - const rect = row.getBoundingClientRect(); - return rect.top <= marker && rect.bottom > marker; - }) || rows.find((row) => row.getBoundingClientRect().top > marker); - if (current) readerContext.foliateSectionVirtualizer.trim(Number(current.dataset.section)); - } - - function scheduleFoliateScrollSync() { - if (readerContext.foliateScrollFrame) return; - readerContext.foliateScrollFrame = requestAnimationFrame(() => { - readerContext.foliateScrollFrame = 0; - readerContext.syncFoliateScrollLocation(); - readerContext.foliateScrollAnchors.whenIdle(readerContext.trimFoliateSections); - }); - } - - /** @param {import('../../../typings/reader-foliate-format-strict').FoliateTocEntry} entry @param {number} [generation] @param {{closePanel?: boolean}} [options] */ - async function activateFoliateTocEntry(entry, generation = readerContext.beginReaderNavigation(), { closePanel = true } = {}) { - const book = readerContext.epubRendition?.book, - href = String(entry.href || ""), - target = await readerContext.epubRendition?.book?.resolveHref(href); - if (!book || !target || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - const section = target && book.sections[target.index], - sections = book.sections.filter((item) => item.linear !== "no"), - visibleIndex = section ? sections.indexOf(section) : -1, - destinationIndex = visibleIndex >= 0 ? visibleIndex : -target.index - 1; - if (!section || !readerContext.foliateSectionLoader) return false; - let node = await readerContext.foliateSectionLoader(destinationIndex); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - // Background neighbors are not part of a demanded TOC destination. - await readerContext.waitForReader(0, true); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - if (!node?.isConnected) node = await readerContext.foliateSectionLoader(destinationIndex); - if (!node?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - const root = readerContext.foliateSectionRoot(node), - /** @type {import('../../../typings/reader-foliate-format-strict').FoliateAnchorDocument} */ - anchorDocument = { - getElementById: (id) => root.querySelector(`[id="${CSS.escape(id)}"]`), - querySelector: (selector) => root.querySelector(selector) - }; - let anchor = null; - try { - anchor = typeof target.anchor === "function" ? target.anchor(anchorDocument) : null; - } catch (_) {} - if (!anchor) { - try { - const fragment = href.split("#")[1] || "", - id = fragment ? decodeURIComponent(fragment) : ""; - anchor = id ? root.querySelector(`[id="${CSS.escape(id)}"], [name="${CSS.escape(id)}"]`) : null; - } catch (_) {} - } - const destination = anchor || node; - readerContext.foliateScrollAnchors.invalidate(); - const landing = readerContext.alignReaderDestination(destination, 8); - readerContext.foliateScrollAnchors.remember(); - // Section heights and images keep settling after the jump; hold the destination on - // the landing line until the layout stops moving. - readerContext.holdReaderDestination(destination, 8); - readerContext.syncFoliateScrollLocation(); - readerContext.updateTocCurrentMark(); - readerContext.updateProgressTools(); - readerContext.scheduleSave(); - if (closePanel) readerContext.setReaderPanelOpen(false, true); - readerContext.foliateScrollAnchors.remember(); - return true; - } - - /** @param {Document} source */ - function cloneFoliateDocument(source) { - const doc = /** @type {Document} */ (source.cloneNode(true)), - original = source.createTreeWalker(source, NodeFilter.SHOW_TEXT), - cloned = doc.createTreeWalker(doc, NodeFilter.SHOW_TEXT); - /** @type {WeakMap} */ - const sourceNodes = new WeakMap(); - while (original.nextNode() && cloned.nextNode()) - sourceNodes.set(cloned.currentNode, original.currentNode); - return { doc: readerContext.sanitizeEpubDocument(doc, { keepBlobImports: true }), sourceNodes }; - } - - /** @param {Document} source @param {WeakMap} sourceNodes @param {Element} body @param {Element} renderedBody */ - function foliateSearchAnchor(source, sourceNodes, body, renderedBody) { - const sourceWalker = body.ownerDocument.createTreeWalker(body, NodeFilter.SHOW_TEXT); - /** @type {{original: Text; offset: number}[]} */ - const pairs = []; - let offset = 0; - while (sourceWalker.nextNode()) { - const node = /** @type {Text} */ (sourceWalker.currentNode); - const original = sourceNodes.get(node); - if (original) pairs.push({ original: /** @type {Text} */ (original), offset }); - offset += node.length; - } - return (/** @type {import('../../../typings/reader-foliate-format-strict').SearchAnchor} */ anchor) => { - const range = anchor(source); - if (!range || typeof range.intersectsNode !== "function") return null; - const intervals = []; - for (const { original, offset } of pairs) { - if (!range.intersectsNode(original)) continue; - const start = range.startContainer === original ? range.startOffset : 0; - const end = range.endContainer === original ? range.endOffset : original.length; - if (end > start) intervals.push({ start: offset + start, end: offset + end }); - } - const walker = document.createTreeWalker(renderedBody, NodeFilter.SHOW_TEXT), - selected = []; - let offset = 0; - while (walker.nextNode()) { - const node = /** @type {Text} */ (walker.currentNode), - end = offset + node.length; - for (const interval of intervals) - if (interval.start < end && interval.end > offset) - selected.push({ - node, - start: Math.max(0, interval.start - offset), - end: Math.min(node.length, interval.end - offset) - }); - offset = end; - } - return selected; - }; - } - - /** @param {ParentNode} root @param {number} [timeoutMs] */ - async function settleReaderImages(root, timeoutMs = 2500) { - readerContext.assertReaderActive(); - const images = [...root.querySelectorAll(/** @type {'img'} */ ("img[src],img[srcset]"))]; - if (!images.length) return; - let timeout = 0, active = true; - /** @type {Set<() => void>} */ - const cleanups = new Set(); - const decoded = Promise.allSettled( - images.map(async (image) => { - // Sections are prepared off-DOM; lazy images cannot enter a viewport yet. - image.loading = "eager"; - image.decoding = "async"; - if (!image.complete) await /** @type {Promise} */ (new Promise((resolve) => { - const finish = () => { - image.removeEventListener("load", finish); - image.removeEventListener("error", finish); - cleanups.delete(finish); - resolve(); - }; - cleanups.add(finish); - image.addEventListener("load", finish, { once: true }); - image.addEventListener("error", finish, { once: true }); - if (image.complete) finish(); - })); - if (active) { - try { await image.decode?.(); } catch (_) {} - } - }) - ); - try { - await readerContext.awaitReader( - Promise.race([ - decoded, - new Promise((resolve) => { - timeout = setTimeout(resolve, timeoutMs); - }) - ]) - ); - } finally { - active = false; - clearTimeout(timeout); - for (const cleanup of cleanups) cleanup(); - } - } - - /** @param {Document} doc @param {import('../../../typings/reader-foliate-format-strict').FoliateSection} section */ - function rewriteFoliateResources(doc, section) { - /** @param {string | null | undefined} value */ - const safeEmbeddedValue = (value) => - /^(?:blob:|data:image\/(?:gif|png|jpe?g|webp);)/i.test(String(value || "").trim()); - /** @param {string | null | undefined} value */ - const archiveResourceUrl = (value) => { - const valueText = String(value || "").trim(); - if (!valueText || valueText.startsWith("#") || safeEmbeddedValue(valueText)) - return safeEmbeddedValue(valueText) ? valueText : null; - const hash = valueText.indexOf("#"), - raw = hash < 0 ? valueText : valueText.slice(0, hash); - let fragment = ""; - try { - if (hash >= 0) fragment = `#${encodeURIComponent(decodeURIComponent(valueText.slice(hash + 1)))}`; - } catch (_) { return null; } - if (!raw || /[?#\\\x00-\x1f\x7f]/.test(raw)) return null; - if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(raw)) return null; - try { - const resolved = String( - (section.resolveResourceHref - ? section.resolveResourceHref(raw) - : section.resolveHref?.(raw)) || "" - ); - if ( - !resolved || - /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(resolved) || - /[\\\x00]/.test(resolved) || - resolved.split("/").some((part) => !part || part === "." || part === "..") - ) - return null; - return `/api/reader-resource?book=${encodeURIComponent(readerContext.sourceUrl)}&path=${encodeURIComponent(resolved)}${fragment}`; - } catch (_) { - return null; - } - }; - // Every src-bearing element (including input[type=image] and track) uses - // the archive-only resource policy, not just images and media. - for (const element of doc.querySelectorAll("[src],video[poster]")) { - for (const name of ["src", "poster"]) - if (element.hasAttribute(name)) { - const safe = archiveResourceUrl(element.getAttribute(name)); - if (safe) element.setAttribute(name, safe); - else element.removeAttribute(name); - } - } - for (const element of doc.querySelectorAll("[srcset]")) { - const value = element.getAttribute("srcset") || ""; - const candidates = value - .split(",") - .map((part) => { - const [raw, ...descriptor] = part.trim().split(/\s+/); - const safe = archiveResourceUrl(raw); - return safe ? [safe, ...descriptor].join(" ") : null; - }) - .filter(Boolean); - if (candidates.length) element.setAttribute("srcset", candidates.join(", ")); - else element.removeAttribute("srcset"); - } - for (const image of doc.querySelectorAll("image")) { - const value = - image.getAttributeNS("http://www.w3.org/1999/xlink", "href") || - image.getAttribute("xlink:href") || - image.getAttribute("href"); - const safe = archiveResourceUrl(value); - if (safe) { - image.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", safe); - image.setAttribute("href", safe); - } else { - image.removeAttributeNS("http://www.w3.org/1999/xlink", "href"); - image.removeAttribute("xlink:href"); - image.removeAttribute("href"); - } - } - // Other SVG references (feImage, use, textPath...) may only point inside the - // chapter; feImage may also use a packaged image like . - for (const element of doc.querySelectorAll("*")) { - if (element.namespaceURI !== "http://www.w3.org/2000/svg" || ["a", "image"].includes(element.localName)) continue; - for (const attribute of [...element.attributes]) { - if (attribute.localName !== "href" || - (attribute.namespaceURI && attribute.namespaceURI !== "http://www.w3.org/1999/xlink")) continue; - const value = attribute.value.trim(); - if (value.startsWith("#")) continue; - const safe = element.localName === "feImage" ? archiveResourceUrl(value) : null; - if (safe) attribute.value = safe; - else element.removeAttributeNode(attribute); - } - } - for (const link of doc.querySelectorAll(/** @type {'a'} */ ("a[href]"))) { - const href = link.getAttribute("href") || ""; - // An in-book link to a packaged image opens the image itself, not a dead chapter URL. - if (/\.(?:gif|png|jpe?g|webp)(?:#.*)?$/i.test(href)) { - const resource = archiveResourceUrl(href); - if (resource) { - link.setAttribute("href", resource); - link.target = "_blank"; - link.rel = "noopener noreferrer"; - } - } - if (/^(?:https?:|mailto:|tel:)/i.test(href)) { - link.target = "_blank"; - link.rel = "noopener noreferrer"; - } - } - } - - /** @param {import('../../../typings/reader-foliate-format-strict').FoliateSection} section @param {number} index @param {AbortSignal} [signal] @param {'high' | 'low'} [priority] */ - async function createFoliateSection(section, index, signal, priority) { - signal = signal || readerContext.readerAbortController.signal; - priority = priority || "high"; - const source = await readerContext.awaitReader(section.createDocument(), signal); - const { doc, sourceNodes } = readerContext.cloneFoliateDocument(source); - readerContext.assertReaderActive(); - readerContext.rewriteFoliateResources(doc, section); - // Packaged CSS is loaded from Foliate blob: URLs; inline it sanitized so - // remote url()/@import references cannot bypass the archive-only policy. - const styles = await readerContext.sanitizeFoliateStyles([...doc.querySelectorAll("style,link")]); - signal.throwIfAborted(); - readerContext.assertReaderActive(); - for (const node of doc.querySelectorAll("style,link")) node.remove(); - const article = /** @type {import('../../../typings/reader-foliate-format-strict').FoliateArticle} */ (document.createElement("article")); - article.dataset.section = String(index); - const shadow = article.attachShadow({ mode: "open" }), - baseStyle = document.createElement("style"), - layoutStyle = document.createElement("style"), - sectionBody = document.createElement("div"); - // Chapter styles live in a shadow root, so document-level preferences cannot reach them. - baseStyle.textContent = ` - :host { display: block; color: inherit; } - * { box-sizing: border-box; } - .reader-section-body { display: block; color: inherit; line-height: inherit; } - .reader-section-body > :first-child { margin-top: 0 !important; } - :host(.reader-document-dark) .reader-section-body, - :host(.reader-document-dark) .reader-section-body :where(:not(svg, svg *, img, canvas, video, audio, math, math *)) { - color: inherit !important; - background-color: transparent !important; - border-color: #4a5056 !important; - text-shadow: none !important; - } - a { color: var(--reader-book-link) !important; } - :host(.reader-document-dark) .reader-section-body a { color: var(--reader-book-link) !important; } - img, svg, video { max-width: 100%; height: auto; } - mark.full-search-highlight { background: #ffd54f; color: #111; } - :host(.reader-document-dark) .reader-section-body mark.full-search-highlight { background: #ffd54f !important; color: #111 !important; } - @media (prefers-contrast: more) { - .reader-section-body a[href] { text-decoration: underline !important; } - .reader-section-body mark.full-search-highlight { outline: 2px solid currentColor; } - } - `; - sectionBody.className = "reader-section-body"; - const body = readerContext.epubContentBody(doc); - // Import the sanitized nodes directly. Serializing and reparsing legacy - // nested anchors lets HTML's adoption rules reorder footnotes and citations. - if (body) - sectionBody.append(...[...body.childNodes].map((node) => document.importNode(node, true))); - wrapEbookTables(sectionBody); - article._resolveSearchAnchor = readerContext.foliateSearchAnchor(source, sourceNodes, body, sectionBody); - layoutStyle.textContent = EBOOK_LAYOUT_STYLE; - shadow.append(baseStyle, ...styles, layoutStyle, sectionBody); - for (const image of sectionBody.querySelectorAll("img")) { - image.loading = priority === "high" ? "eager" : "lazy"; - image.fetchPriority = priority; - image.decoding = "async"; - } - signal.throwIfAborted(); - readerContext.assertReaderActive(); - article.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark"); - return article; - } - - /** @param {HTMLElement} stream @param {import('../../../typings/reader-foliate-format-strict').FoliateSection[]} sections */ - function setupFoliateWindow(stream, sections) { - let focus = readerContext.initialReaderTargetSection ?? 0, targetPending = false; - stream.style.overflowAnchor = "none"; - /** @param {number} index */ - const existing = index => /** @type {import('../../../typings/reader-foliate-format-strict').FoliateArticle | null} */ (stream.querySelector(`article[data-section="${index}"]:not(.foliate-section-placeholder)`)); - /** @param {number} index */ - const ensurePlaceholder = index => { - if (!sections[index] || stream.querySelector(`article[data-section="${index}"]`)) return; - const placeholder = document.createElement("article"); - placeholder.className = "foliate-section-placeholder"; - placeholder.dataset.section = String(index); - placeholder.hidden = stream.classList.contains("foliate-supplement-active"); - placeholder.style.setProperty("--foliate-placeholder-height", `${Math.max(400, readerContext.viewport.clientHeight)}px`); - placeholder.setAttribute("aria-label", `加载第 ${index + 1} 节`); - const next = [...stream.children].find(node => Number(/** @type {HTMLElement} */ (node).dataset.section) > index); - readerContext.foliateScrollAnchors.preserve(() => stream.insertBefore(placeholder, next || null)); - observer.observe(placeholder); - }; - const warm = () => { - const indices = []; - for (const offset of [-1, 1, -2, 2, 3, 4, 5, 6]) { - const index = focus + offset; - if (sections[index] && !existing(index)) indices.push(index); - } - scheduler.prefetch(document.hidden ? [] : indices); - }; - const refresh = () => { - if (readerContext.readerAbortController.signal.aborted || stream.classList.contains("foliate-supplement-active")) return; - const marker = readerContext.viewport.getBoundingClientRect().top + 80; - const rows = [...stream.children]; - const current = rows.find(node => { - const rect = node.getBoundingClientRect(); - return rect.top <= marker && rect.bottom > marker; - }) || rows.find(node => node.getBoundingClientRect().top > marker); - const index = current ? Number(/** @type {HTMLElement} */ (current).dataset.section) : focus; - if (targetPending && index !== focus && !readerContext.foliateScrollAnchors.scrolling) return; - targetPending = false; - focus = index; - if (current?.classList.contains("foliate-section-placeholder")) scheduler.load(index).catch(() => {}); - warm(); - readerContext.foliateScrollAnchors.whenIdle(readerContext.trimFoliateSections); - }; - const observer = new IntersectionObserver(readerContext.scheduleFoliateWindowRefresh, - { root: readerContext.viewport, rootMargin: `${readerContext.FOLIATE_PREFETCH_MARGIN}px` }); - readerContext.foliateSectionObserver = observer; - /** @param {number} index @param {import('../../../typings/reader-foliate-format-strict').FoliateArticle} article */ - const commitSection = (index, article) => - readerContext.foliateScrollAnchors.preserve(() => { - const placeholder = stream.querySelector( - `article.foliate-section-placeholder[data-section="${index}"]` - ), - next = [...stream.querySelectorAll("article[data-section]")].find( - (item) => Number(/** @type {HTMLElement} */ (item).dataset.section) > index - ); - if (stream.classList.contains("foliate-supplement-active")) article.hidden = true; - if (placeholder) { - observer.unobserve(placeholder); - placeholder.replaceWith(article); - } else stream.insertBefore(article, next || null); - observer.observe(article); - readerContext.foliateScrollAnchors.observe(article); - ensurePlaceholder(index - 1); - ensurePlaceholder(index + 1); - return article; - }); - const scheduler = readerContext.readerRuntime.track(VoiceOfMLReaderChapters.createChapterScheduler({ - create: async (index, signal, priority) => { - const section = sections[index]; - if (!section) throw new RangeError("Foliate section is unavailable"); - const article = await readerContext.createFoliateSection(section, index, signal, priority); - signal.throwIfAborted(); - if (existing(index)) return existing(index); - return commitSection(index, article); - } - })); - readerContext.foliateChapterRepository = VoiceOfMLReaderChapters.createChapterRepository({ - count: sections.length, find: existing, create: index => scheduler.load(index) - }); - readerContext.foliateSectionVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({ - limit: readerContext.FOLIATE_LOADED_SECTION_LIMIT, - getLoaded: () => [ - .../** @type {NodeListOf} */ (stream.querySelectorAll("article[data-section]:not(.foliate-section-placeholder)")) - ], - getIndex: (article) => Number(article.dataset.section), - getHeight: (article) => article.getBoundingClientRect().height, - canVirtualize: (article) => { - const rect = article.getBoundingClientRect(), - viewportRect = readerContext.viewport.getBoundingClientRect(); - return ( - rect.bottom < viewportRect.top - readerContext.FOLIATE_PREFETCH_MARGIN || - rect.top > viewportRect.bottom + readerContext.FOLIATE_PREFETCH_MARGIN - ) && !article.contains(document.activeElement) && !article.shadowRoot?.activeElement && - !readerContext.foliateSectionRoot(article).querySelector("mark.full-search-highlight") && - ![window.getSelection(), /** @type {(ShadowRoot & {getSelection?: () => Selection | null}) | null} */ (article.shadowRoot)?.getSelection?.()].some(selection => - selection && !selection.isCollapsed && (selection.containsNode(article, true) || - selection.anchorNode?.getRootNode() === article.shadowRoot)); - }, - virtualize: (article, index, height) => { - const placeholder = document.createElement("article"); - placeholder.className = "foliate-section-placeholder"; - placeholder.dataset.section = String(index); - placeholder.style.setProperty("--foliate-placeholder-height", `${height}px`); - placeholder.setAttribute("aria-hidden", "true"); - observer.unobserve(article); - readerContext.foliateScrollAnchors.unobserve(article); - for (const image of readerContext.foliateSectionRoot(article).querySelectorAll("img")) { - image.removeAttribute("src"); - image.removeAttribute("srcset"); - } - article._resolveSearchAnchor = null; - article.replaceWith(placeholder); - observer.observe(placeholder); - return placeholder; - }, - release: (index) => readerContext.foliateChapterRepository?.release(index) ?? false, - preserve: (change) => readerContext.foliateScrollAnchors.preserve(change) - }); - // Negative indices encode the original spine index, preserving existing linear - // bookmark indices while keeping supplemental sections out of progression. - let supplementGeneration = 0; - readerContext.foliateSectionLoader = /** @type {import('../../../typings/reader-foliate-format-strict').FoliateLoader} */ (index => { - if (index < 0) { - const source = readerContext.epubBook?.sections[-index - 1]; - if (!Number.isInteger(index) || !source || source.linear !== "no") return Promise.resolve(null); - const generation = ++supplementGeneration; - const present = existing(index); - const task = present ? Promise.resolve(present) : readerContext.createFoliateSection(source, index); - return task.then(article => { - if (generation !== supplementGeneration || readerContext.readerAbortController.signal.aborted) return null; - for (const old of stream.querySelectorAll("article[data-supplement]")) if (old !== article) old.remove(); - article.dataset.supplement = "true"; - if (!article.isConnected) stream.append(article); - for (const row of stream.children) if (row !== article) /** @type {HTMLElement} */ (row).hidden = true; - stream.classList.add("foliate-supplement-active"); - return article; - }); - } - ++supplementGeneration; - if (stream.classList.contains("foliate-supplement-active")) { - for (const row of stream.children) /** @type {HTMLElement} */ (row).hidden = false; - for (const old of stream.querySelectorAll("article[data-supplement]")) old.remove(); - stream.classList.remove("foliate-supplement-active"); - } - focus = index; - targetPending = true; - const task = existing(index) ? Promise.resolve(existing(index)) : scheduler.load(index, true, true); - warm(); - return task; - }); - readerContext.foliateSectionLoader.refresh = refresh; - readerContext.foliateSectionSettler = () => readerContext.waitForReader(0, true); - const scroll = readerContext.scheduleFoliateWindowRefresh; - readerContext.viewport.addEventListener("scroll", scroll, { passive: true }); - document.addEventListener("visibilitychange", scroll); - readerContext.trackReaderResource(() => { - readerContext.viewport.removeEventListener("scroll", scroll); - document.removeEventListener("visibilitychange", scroll); - }); - } - - /** @param {import('../../../typings/reader-foliate-format-strict').FoliateView} view @param {import('../../../typings/reader-foliate-format-strict').FoliateSection[]} sections */ - async function foliateTocEntries(view, sections) { - readerContext.assertReaderActive(); - /** @type {import('../../../typings/reader-foliate-format-strict').FoliateTocEntry[]} */ - const entries = []; - /** @param {import('../../../typings/reader-foliate-format-strict').FoliateTocItem[] | undefined} items @param {number} [depth] */ - const append = (items, depth = 0) => { - for (const item of items || []) { - const href = item?.href ? String(item.href) : ""; - if (href || item?.label) - entries.push({ - label: item.label || "未命名章节", - href, - depth, - group: !href, - activate: () => view.goTo(href) - }); - append(item.subitems, depth + 1); - } - }; - append(view.book.toc); - /** @type {Map} */ - const sectionIndices = new Map(); - for (const [index, section] of sections.entries()) - if (!sectionIndices.has(section)) sectionIndices.set(section, index); - let next = 0, yieldDeadline = performance.now() + 8; - /** @type {Promise | null} */ - let yieldTask = null; - const resolveEntries = async () => { - while (next < entries.length) { - readerContext.assertReaderActive(); - if (yieldTask || performance.now() >= yieldDeadline) { - yieldTask ||= readerContext.waitForReader().finally(() => { - yieldTask = null; - yieldDeadline = performance.now() + 8; - }); - await yieldTask; - continue; - } - const entry = entries[next++]; - if (!entry) continue; - if (entry.group) { - entry.sectionIndex = -1; - entry.fragment = ""; - continue; - } - try { - const target = await view.book.resolveHref(entry.href), - section = target && view.book.sections[target.index]; - readerContext.assertReaderActive(); - entry.sectionIndex = section ? sectionIndices.get(section) ?? -target.index - 1 : -1; - entry.anchor = typeof target?.anchor === "function" ? target.anchor : null; - const fragment = entry.href.split("#")[1] || ""; - try { entry.fragment = fragment ? decodeURIComponent(fragment) : ""; } - catch (_) { entry.fragment = ""; } - } catch (_) { - readerContext.assertReaderActive(); - entry.sectionIndex = -1; - entry.fragment = ""; - } - } - }; - await readerContext.awaitReader(Promise.all(Array.from({ length: Math.min(8, entries.length) }, resolveEntries))); - readerContext.assertReaderActive(); - return entries; - } - - async function renderFoliate() { - const foliateModuleUrl = "/static/foliate-reader/view.js"; - const prepared = readerContext.prepareReaderDocument([import(foliateModuleUrl)]); - const [response, bytes] = await Promise.all([prepared.response,readerContext.readPreparedBytes( - prepared.response,prepared.engines,VoiceOfMLReaderSecurity.LIMITS.archiveCompressedBytes)]); - readerContext.assertReaderActive(); - if (VoiceOfMLReaderSecurity.isZipContainer(readerContext.extension, bytes)) - VoiceOfMLReaderSecurity.inspectZip(bytes); - const view = /** @type {import('../../../typings/reader-foliate-format-strict').FoliateView} */ (/** @type {unknown} */ (document.createElement("foliate-view"))), - stream = document.createElement("div"); - view.className = "foliate-reader-view"; - stream.className = "foliate-continuous"; - readerContext.content.replaceChildren(readerContext.loadingIndicator, view, stream); - readerContext.epubRendition = view; - await view.open( - new File([bytes], new URL(readerContext.sourceUrl).pathname.split("/").pop() || "book.epub", { - type: response.headers.get("content-type") || "application/epub+zip" - }) - ); - readerContext.assertReaderActive(); - readerContext.epubBook = view.book; - view.style.display = "none"; - const sections = view.book.sections.filter((section) => section.linear !== "no"); - await readerContext.getInitialReaderRestoration(); - const savedSection = Number(readerContext.readerRestorationEntry?.foliateSection); - const initialSection = Number.isInteger(savedSection) && savedSection < 0 && view.book.sections[-savedSection - 1]?.linear === "no" - ? 0 : Number.isInteger(savedSection) - ? Math.max(0, Math.min(sections.length - 1, savedSection)) - : 0; - readerContext.initialReaderTargetSection = readerContext.readerRestorationEntry?.foliateSection == null ? null : initialSection; - readerContext.setupFoliateWindow(stream, sections); - const repository = readerContext.foliateChapterRepository; - if (!repository) throw new Error("Foliate chapter repository not initialized"); - if (sections[initialSection]) await repository.load(initialSection); - if (savedSection < 0 && view.book.sections[-savedSection - 1]?.linear === "no") - await readerContext.foliateSectionLoader?.(savedSection); - readerContext.assertReaderActive(); - readerContext.markReaderContentReady(); - // Restoration targets the selected section; an unrelated slow previous - // section is loaded in the background and remains retryable. - if (initialSection > 0) repository.load(initialSection - 1).catch(error => { - if (!readerContext.readerAbortController.signal.aborted) - console.warn("Previous EPUB chapter could not be loaded", error); - }); - // Resolving every TOC href can be expensive for large books. The first - // chapter is already visible, so finish the opening path before enriching - // the navigation panel in the background. - readerContext.foliateTocEntries(view, sections) - .then((entries) => { - if (entries.length && !readerContext.readerAbortController.signal.aborted) readerContext.setToc(entries); - }) - .catch(() => {}); - readerContext.scheduleFoliateScrollSync(); - readerContext.markReaderContentReady(); - readerContext.status.textContent = "EPUB"; - } - - return { - foliateSectionRoot, - foliateSectionQuery, - foliateSectionCandidates, - syncFoliateScrollLocation, - refreshFoliateWindow, - scheduleFoliateWindowRefresh, - trimFoliateSections, - scheduleFoliateScrollSync, - activateFoliateTocEntry, - cloneFoliateDocument, - foliateSearchAnchor, - settleReaderImages, - rewriteFoliateResources, - createFoliateSection, - setupFoliateWindow, - foliateTocEntries, - renderFoliate - }; -} diff --git a/static/reader/formats/reader-format-controller.mjs b/static/reader/formats/reader-format-controller.mjs index 05890d10c614493c9915433236527d4698ff3877..4e44a3433f91c0f871ae2e285eccf3941c79feaa 100644 --- a/static/reader/formats/reader-format-controller.mjs +++ b/static/reader/formats/reader-format-controller.mjs @@ -36,22 +36,6 @@ export function createReaderFormatController(readerContext) { } for (const image of readerContext.content.querySelectorAll(".reader-page img")) image.removeAttribute("src"); } - if (mode === "foliate") { - readerContext.foliateSectionObserver?.disconnect(); - readerContext.foliateSectionObserver = null; - readerContext.foliateSectionVirtualizer?.dispose(); - readerContext.foliateChapterRepository?.dispose(); - readerContext.foliateSectionVirtualizer = null; - readerContext.foliateChapterRepository = null; - readerContext.foliateSectionLoader = null; - readerContext.foliateSectionSettler = null; - try { - const closing = readerContext.epubRendition?.close?.(); - if (closing) closing.catch?.(() => {}); - } catch (_) {} - readerContext.epubRendition = null; - readerContext.epubBook = null; - } if (mode === "html") { readerContext.htmlFrame?.remove(); readerContext.htmlFrame = null; @@ -102,8 +86,7 @@ export function createReaderFormatController(readerContext) { "epub-chapters": pair(readerContext.loadChapterManifestDocument, readerContext.renderChapterManifest), audio: pair(readerContext.loadMediaDocument, () => readerContext.renderMedia("audio")), video: pair(readerContext.loadMediaDocument, () => readerContext.renderMedia("video")), - swf: pair(readerContext.loadSwfDocument, readerContext.renderSwf), - foliate: pair(readerContext.loadMediaDocument, readerContext.renderFoliate) + swf: pair(readerContext.loadSwfDocument, readerContext.renderSwf) }; for (const [mode, {open, render}] of Object.entries(formats)) readerContext.formatAdapters.register(mode, { @@ -169,13 +152,6 @@ export function createReaderFormatController(readerContext) { readerContext.readerSourcePromise = readerContext.measurePdf(readerContext.resolveReaderSource(), "resolve"); await readerContext.readerSourcePromise; readerContext.assertReaderActive(); - if (readerContext.readerId && /\/calibre-chm-epub-[^/]+\/document\.epub(?:$|\?)/i.test(readerContext.sourceUrl)) { - readerContext.extension = "epub"; - readerContext.readerRuntime.update("source", { extension: readerContext.extension }); - readerContext.capability = readerContext.readerRuntime.negotiate(VoiceOfMLReader.capability(readerContext.extension)); - readerContext.content.dataset.mode = readerContext.capability.mode || "unsupported"; - /** @type {HTMLElement} */ (document.querySelector(".page-controls")).hidden = true; - } readerContext.syncCapabilityControls(); /** @type {HTMLAnchorElement} */ (readerContext.downloadButton).href = readerContext.readerDownloadUrl(readerContext.documentState.title, readerContext.downloadUrl); if ( @@ -186,22 +162,6 @@ export function createReaderFormatController(readerContext) { readerContext.formatAdapters.activate(readerContext.capability.mode); readerContext.applyReaderMetadata(readerContext.resolvedReaderData); try { - if (readerContext.capability.mode === "foliate") { - readerContext.setReaderStage("foliate"); - readerContext.foliateContinuous = true; - const restorationPromise = readerContext.loadReaderRestoration(); - readerContext.readerRestorationPromise = restorationPromise; - await readerContext.awaitReader(readerContext.renderFoliate()); - readerContext.assertReaderActive(); - const restored = await readerContext.awaitReader(restorationPromise); - await readerContext.applyInitialRestoration(restored, generation); - readerContext.initialReaderTargetSection = null; - readerContext.assertReaderActive(); - if (!readerContext.setReaderPhase("ready")) return; - readerContext.updateDocumentState({ restorationReady: !readerContext.restorationFailed }); - readerContext.scheduleSave(); - return; - } readerContext.setReaderStage("prepare"); const restorationPromise = readerContext.loadReaderRestoration(); readerContext.readerRestorationPromise = restorationPromise; @@ -268,7 +228,7 @@ export function createReaderFormatController(readerContext) { console.error(error); const message = detail && "code" in detail && detail.code === "READER_PDF_RATE_LIMIT" ? "请求过于频繁,请稍后重试加载。" : detail && "message" in detail && typeof detail.message === "string" && detail.message ? detail.message : "原文件加载失败"; - const fallback = readerContext.capability.mode === "foliate" ? "READER_CORRUPT" : "READER_PARSE"; + const fallback = "READER_PARSE"; const code = readerContext.classifyReaderError(error, fallback); readerContext.fail(message, typeof code === "string" ? code : fallback); } diff --git a/static/reader/formats/reader-html-format.mjs b/static/reader/formats/reader-html-format.mjs index cda6f9738013323821dea6e0e33d9fd0d66ace9b..4c70eb9045b595c01a9abbe25a7e96fb766d1390 100644 --- a/static/reader/formats/reader-html-format.mjs +++ b/static/reader/formats/reader-html-format.mjs @@ -25,7 +25,6 @@ export function createReaderHtmlFormat(readerContext) { } // HTML parsing treats prefixed void tags as containers. Keep the following // content as siblings: serializing real
/
/ drops their children. - // Move the existing text nodes so Foliate's source/CFI mapping stays intact. const fragment = doc.createDocumentFragment(); fragment.appendChild(replacement); if (readerContext.EPUB_HTML_VOID_TAGS.has(localName)) { @@ -116,8 +115,6 @@ export function createReaderHtmlFormat(readerContext) { const CSS_REFERENCE_FUNCTIONS = new Set([ "url", "src", "image", "image-set", "-webkit-image-set", "cross-fade", "-webkit-cross-fade" ]); - const CSS_BLOB_STYLESHEET_MAX_BYTES = 4 * 1024 * 1024; - const CSS_IMPORT_MAX_DEPTH = 4; const CSS_IMPORT_MAX_PER_SHEET = 32; /** @param {number} code */ @@ -379,99 +376,6 @@ export function createReaderHtmlFormat(readerContext) { return scanCss(css, options); } - /** @param {string} url */ - async function readBlobStylesheet(url) { - try { - const response = await fetch(url); - if (!response.ok) return null; - const declared = Number(response.headers.get("content-length") || 0); - if (declared > CSS_BLOB_STYLESHEET_MAX_BYTES) return null; - const blob = await response.blob(); - return blob.size > CSS_BLOB_STYLESHEET_MAX_BYTES ? null : await blob.text(); - } catch (_) { - return null; - } - } - - // Replace blob @imports with their sanitized contents, preserving cascade - // position and media conditions. Cycles, excessive depth and unreadable - // sheets are dropped rather than loaded unsanitized. - /** @param {string} css @param {number} [depth] @param {Set} [ancestors] @returns {Promise} */ - async function inlineCssImports(css, depth = 0, ancestors = new Set()) { - /** @type {{url: string, media: string}[]} */ - const blobImports = []; - const nonce = `reader-import-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`; - const sanitized = scanCss(css, { blobImports, nonce }); - if (!blobImports.length) return sanitized; - const bodies = await Promise.all(blobImports.map(async ({ url, media }) => { - if (depth >= CSS_IMPORT_MAX_DEPTH || ancestors.has(url)) return ""; - const text = await readBlobStylesheet(url); - if (text === null) return ""; - const body = (await inlineCssImports(text, depth + 1, new Set([...ancestors, url]))) - .replace(/^\ufeff/, "").replace(/^\s*@charset\s+"[^"]*"\s*;/i, ""); - return media && !/^all$/i.test(media) ? `@media ${media} {\n${body}\n}` : body; - })); - return sanitized.replace(new RegExp(`/\\*${nonce}:(\\d+)\\*/`, "g"), (_, index) => bodies[Number(index)] ?? ""); - } - - // Foliate rewrites chapter stylesheets to blob: URLs. Load them as sanitized - // inline styles so remote references inside packaged CSS cannot escape the - // archive-only resource policy. Results are cached per blob URL. - /** @type {Map>} */ - const foliateStyleCache = new Map(); - const FOLIATE_STYLE_CACHE_MAX = 64; - - /** @param {Element} node @returns {Promise} */ - async function sanitizeFoliateStyle(node) { - if (node.localName !== "link") { - const style = /** @type {Element} */ (node.cloneNode(false)); - style.textContent = await inlineCssImports(node.textContent || ""); - return style; - } - const href = node.getAttribute("href") || ""; - if (!/^blob:/i.test(href)) return null; - let pending = foliateStyleCache.get(href); - if (!pending) { - pending = readBlobStylesheet(href).then(text => { - if (text !== null) return inlineCssImports(text, 0, new Set([href])); - // An old failed read must not evict a newer entry after cache rotation. - if (foliateStyleCache.get(href) === pending) foliateStyleCache.delete(href); - return null; - }); - foliateStyleCache.set(href, pending); - while (foliateStyleCache.size > FOLIATE_STYLE_CACHE_MAX) { - const oldest = foliateStyleCache.keys().next(); - if (oldest.done) break; - foliateStyleCache.delete(oldest.value); - } - } - const text = await pending; - if (text === null) return null; - const style = document.createElement("style"); - const media = node.getAttribute("media"); - if (media) style.setAttribute("media", media); - style.textContent = text; - return style; - } - - /** @param {Iterable} nodes */ - async function sanitizeFoliateStyles(nodes) { - const ordered = Array.from(nodes); - /** @type {(Element | null)[]} */ - const output = []; - let next = 0; - // Overlap the archive's independent sheets without starting every read at - // once. Insert only sanitized output, in the original cascade order. - await Promise.all(Array.from({ length: Math.min(3, ordered.length) }, async () => { - while (next < ordered.length) { - readerContext.assertReaderActive(); - const index = next++; - output[index] = await sanitizeFoliateStyle(/** @type {Element} */ (ordered[index])); - } - })); - return output.filter(style => style !== null); - } - /** @param {Document} doc @param {{keepBlobImports?: boolean}} [options] */ function sanitizeEpubDocument(doc, options = {}) { return readerContext.sanitizeReaderDocument(readerContext.normalizeEpubDocument(doc), { ...options, preserveEpubStyles: true }); @@ -842,7 +746,6 @@ export function createReaderHtmlFormat(readerContext) { sanitizeReaderDocument, sanitizeEpubDocument, sanitizeCssReferences, - sanitizeFoliateStyles, parseChapterDocument, epubContentBody, renderText, diff --git a/static/reader/pdf/reader-engine-preload.js b/static/reader/pdf/reader-engine-preload.js index 1288a88867bbd6f7ffa4b622b144e0f1acc53173..fc66e34e9e959b8ea5484b7360392db304e6f14f 100644 --- a/static/reader/pdf/reader-engine-preload.js +++ b/static/reader/pdf/reader-engine-preload.js @@ -44,7 +44,7 @@ for (const href of assets) { if (support.includes(href) || href.endsWith(".wasm")) continue; const link = document.createElement("link"); - link.rel = /\.mjs(?:\?|$)/.test(href) || href.includes("/foliate-reader/") ? "modulepreload" : "preload"; + link.rel = /\.mjs(?:\?|$)/.test(href) ? "modulepreload" : "preload"; if (link.rel === "preload") link.as = "script"; link.href = href; document.head.appendChild(link); diff --git a/static/reader/reader-components.mjs b/static/reader/reader-components.mjs index 20633e5a98d65e7a590fd6a006c86571b751165f..0139fb143e669e2af2ab60be98621f9e09f99367 100644 --- a/static/reader/reader-components.mjs +++ b/static/reader/reader-components.mjs @@ -6,7 +6,6 @@ export { createReaderToc } from "./ui/reader-toc.mjs"; export { createReaderSearchBackends } from "./search/reader-search-backends.mjs"; export { createReaderPdfScheduler } from "./pdf/reader-pdf-scheduler.mjs"; export { createReaderNavigation } from "./ui/reader-navigation.mjs"; -export { createReaderFoliateFormat } from "./formats/reader-foliate-format.mjs"; export { createReaderProgress } from "./ui/reader-progress.mjs"; export { createReaderBookmarks } from "./ui/reader-bookmarks.mjs"; export { createReaderMediaFormat } from "./formats/reader-media-format.mjs"; diff --git a/static/reader/search/reader-dom-search.mjs b/static/reader/search/reader-dom-search.mjs index 68fa20467095d7d73e325a79ab3fec8b87e73159..ac485511af241dcc96e02c119492a834cfc6b4e9 100644 --- a/static/reader/search/reader-dom-search.mjs +++ b/static/reader/search/reader-dom-search.mjs @@ -376,8 +376,6 @@ export function createReaderDomSearch({ const chunks = []; const breaks = cached ? cached.breaks : []; const findLineBreaks = query.includes(BLOCK_SEPARATOR); - // Foliate's section-ordinal fallback must count the same concatenated text - // matches as the Foliate engine which produced the ordinal. const respectBlocks = progressive || occurrence === null; let length = 0; /** @type {(node: Text, start: number, end: number) => void} */ diff --git a/static/reader/search/reader-search-backends.mjs b/static/reader/search/reader-search-backends.mjs index 32c4de3eb68ee96d8f1a540d0831151a29e65456..1f1cae172f41238b5b41779145455b9f5f0fc6d4 100644 --- a/static/reader/search/reader-search-backends.mjs +++ b/static/reader/search/reader-search-backends.mjs @@ -81,9 +81,9 @@ export function createReaderSearchBackends(readerContext) { parts.unshift({ node: /** @type {Text} */ (heading.firstChild), start, end: Math.min(start + result.length, headText.length) }); } const [mark] = readerContext.highlightTextParts(parts); - readerContext.foliateScrollAnchors.invalidate(); + readerContext.chapterScrollAnchors.invalidate(); (mark || article).scrollIntoView({ block: "center" }); - readerContext.foliateScrollAnchors.remember(); + readerContext.chapterScrollAnchors.remember(); const tocIndex = readerContext.navigationState.tocEntries.findIndex( (entry) => entry.chapterIndex === result.chapterIndex ); @@ -96,147 +96,6 @@ export function createReaderSearchBackends(readerContext) { return true; } - /** @param {string} query @param {number} generation */ - async function fullSearchFoliateMatches(query, generation) { - if (!readerContext.epubRendition?.search) return []; - /** @type {{index: number, count: number, label: string}[]} */ - const groups = []; - /** @type {ReaderSearchBackends.FoliateResult[]} */ - const firstPage = []; - // Cache only visited pages for this query; never retain every match in the book. - /** @type {Map>} */ - const cachedPages = new Map(); - let total = 0; - /** @param {ReaderSearchBackends.FoliateItem} item @param {string} label @param {number} occurrence */ - const toResult = (item, label, occurrence) => { - const excerpt = item.excerpt || { pre: "", match: query, post: "" }; - return { - location: label || "电子书位置", - cfi: item.cfi, - occurrence, - snippet: { - text: `${excerpt.pre}${excerpt.match}${excerpt.post}`, - matchStart: excerpt.pre.length, - matchLength: excerpt.match.length, - prefix: "", - suffix: "" - } - }; - }; - readerContext.fullSearchSession.pageLoader = async (requestedOffset, pageGeneration = readerContext.readerRuntime.currentGeneration("search")) => { - const pageSize = 50; - const offset = readerContext.fullSearchPageOffset(total, requestedOffset, pageSize); - if (!offset) return { total, offset, pageSize, results: firstPage.slice() }; - const cached = cachedPages.get(offset); - if (cached) { - cachedPages.delete(offset); - cachedPages.set(offset, cached); - return cached; - } - /** @type {ReaderSearchBackends.FoliateResult[]} */ - const results = []; - let passed = 0; - for (const group of groups) { - if (passed + group.count <= offset) { passed += group.count; continue; } - const sectionOffset = Math.max(0, offset - passed); - const limit = Math.min(pageSize - results.length, group.count - sectionOffset); - for await (const batch of /** @type {ReaderSearchBackends.Rendition} */ (readerContext.epubRendition).search({ - query, index: group.index, offset: sectionOffset, limit, lean: true, - current: () => readerContext.isReaderGenerationCurrent("search", pageGeneration) - })) - for (const [index, item] of batch.subitems.entries()) - results.push(toResult(item, group.label, sectionOffset + index)); - passed += group.count; - if (results.length === pageSize) break; - } - const page = { total, offset, pageSize, results }; - if (readerContext.isReaderGenerationCurrent("search", pageGeneration) && JSON.stringify(page).length <= 128 * 1024) { - cachedPages.set(offset, page); - if (cachedPages.size > 4) cachedPages.delete(/** @type {number} */ (cachedPages.keys().next().value)); - } - return page; - }; - for await (const group of readerContext.epubRendition.search({ - query, lean: true, limit: 50, - current: () => readerContext.isReaderGenerationCurrent("search", generation) - })) { - if (!readerContext.isReaderGenerationCurrent("search", generation)) return []; - if (group.count) groups.push({ index: group.index, count: group.count, label: group.label }); - for (const [index, item] of group.subitems.entries()) { - if (firstPage.length === 50) break; - firstPage.push(toResult(item, group.label, index)); - } - total += group.count; - readerContext.fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() }; - readerContext.updateSearchState({ results: firstPage.slice(), index: -1 }); - readerContext.renderFullSearchResults(); - readerContext.fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`; - await readerContext.waitForReader(); - if (!readerContext.isReaderGenerationCurrent("search", generation)) return []; - } - readerContext.fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() }; - return firstPage; - } - - /** @param {ReaderSearchBackends.FoliateResult} result @param {number} generation */ - async function navigateFoliateSearchResult(result, generation) { - const resolved = await readerContext.epubRendition?.resolveNavigation?.(result.cfi); - if (!resolved || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - const section = readerContext.epubBook?.sections?.[resolved.index], - sections = readerContext.epubBook?.sections?.filter((item) => item.linear !== "no") || [], - visibleIndex = section ? sections.indexOf(section) : -1, - destinationIndex = visibleIndex >= 0 ? visibleIndex : -resolved.index - 1; - if (!section || !readerContext.foliateSectionLoader) return false; - let node = await readerContext.foliateSectionLoader(destinationIndex); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - await readerContext.waitForReader(0, true); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - if (!node?.isConnected) node = await readerContext.foliateSectionLoader(destinationIndex); - if (!node?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - readerContext.clearFullSearchMarks(); - let target; - if (typeof resolved.anchor === "function" && node._resolveSearchAnchor) { - let parts; - try { parts = node._resolveSearchAnchor(resolved.anchor); } catch (_) { return false; } - if (!parts?.length) return false; - [target] = readerContext.highlightTextParts(parts); - } else { - // Some non-CFI engines expose only a section locator. - const matches = await readerContext.fullSearchDomMatches( - node, - "电子书位置", - readerContext.searchState.query, - readerContext.readerRuntime.currentGeneration("search"), - false, - result.occurrence || 0, - generation - ); - target = matches[0]?.target; - } - if (!readerContext.isReaderGenerationCurrent("navigation", generation) || !target) return false; - const targetRect = target.getBoundingClientRect(), - viewportRect = readerContext.viewport.getBoundingClientRect(); - readerContext.foliateScrollAnchors.invalidate(); - readerContext.viewport.scrollTop = Math.max( - 0, - readerContext.viewport.scrollTop + - targetRect.top - - viewportRect.top - - (readerContext.viewport.clientHeight - targetRect.height) / 2 - ); - const tocIndex = readerContext.navigationState.tocEntries.findIndex( - (entry) => entry.sectionIndex === destinationIndex - ); - if (tocIndex >= 0) { - readerContext.updateNavigationState({ currentChapterIndex: tocIndex }); - readerContext.updateTocCurrentMark(); - } - readerContext.updateProgressTools(); - readerContext.scheduleSave(); - readerContext.foliateScrollAnchors.remember(); - return true; - } - /** @param {string} query @param {number} generation */ async function searchReaderText(query, generation) { if (readerContext.capability.mode === "pdf" && !readerContext.ocrManifestUrl) { @@ -244,8 +103,6 @@ export function createReaderSearchBackends(readerContext) { } else if (/** @type {(string | null | undefined)[]} */ (["pdf", "pdf-pages"]).includes(readerContext.capability.mode)) readerContext.publishSearchResults(generation, await readerContext.searchConcentratedPdf(query, generation)); - else if (readerContext.capability.mode === "foliate") - readerContext.publishSearchResults(generation, await readerContext.fullSearchFoliateMatches(query, generation)); else if (readerContext.capability.mode === "epub-chapters") await readerContext.searchChapterBook(query, generation); else if (/** @type {(string | null | undefined)[]} */ (["text", "markdown"]).includes(readerContext.capability.mode)) readerContext.publishSearchResults( @@ -275,8 +132,6 @@ export function createReaderSearchBackends(readerContext) { chapterSearchModule, searchChapterBook, navigateChapterSearchResult, - fullSearchFoliateMatches, - navigateFoliateSearchResult, searchReaderText }; } diff --git a/static/reader/search/reader-search-controller.mjs b/static/reader/search/reader-search-controller.mjs index 753ae122f99c3160898110ddf8eae5ca9928ecaa..7630d0e9e39676f450fbc08a1c6f8870d256f226 100644 --- a/static/reader/search/reader-search-controller.mjs +++ b/static/reader/search/reader-search-controller.mjs @@ -176,7 +176,7 @@ export function createReaderSearchController({ initialSearch = null; if (interrupted) { if (mode === "epub-chapters") backend.chapterClient()?.cancel(); - else if (mode === "pdf" || mode === "pdf-pages" || mode === "foliate") backend.pdfClient()?.cancel(); + else if (mode === "pdf" || mode === "pdf-pages") backend.pdfClient()?.cancel(); resetResults(); } cancel.hidden = retry.hidden = true; @@ -251,7 +251,7 @@ export function createReaderSearchController({ state.failedPage = null; const generation = nextGeneration(); navigation.begin(); - if (!(/** @type {(string | null)[]} */ (["foliate", "epub-chapters"])).includes(backend.mode())) cancel.hidden = false; + if (backend.mode() !== "epub-chapters") cancel.hidden = false; retry.hidden = true; status.textContent = `${state.page.total} 个结果`; try { diff --git a/static/reader/ui/reader-bookmarks.mjs b/static/reader/ui/reader-bookmarks.mjs index 3743a20e8ddc879b0935ca3c549a37234516fea4..1e1f30de7bc64a3d384dc84013de5d19f1c585ed 100644 --- a/static/reader/ui/reader-bookmarks.mjs +++ b/static/reader/ui/reader-bookmarks.mjs @@ -147,121 +147,11 @@ export function createReaderBookmarks(readerContext) { } catch (_) {} const exact = readerContext.excerptFromCaret(document, readerContext.content, x, y); if (exact) return exact; - const sourceText = readerContext.foliateContinuous - ? [ - ...readerContext.content.querySelectorAll( - ".foliate-continuous article[data-section]:not(.foliate-section-placeholder)" - ) - ] - .map((article) => readerContext.foliateSectionRoot(article).textContent) - .join(" ") - : readerContext.content.textContent, - text = sourceText.replace(/\s+/g, " ").trim(), + const text = readerContext.content.textContent.replace(/\s+/g, " ").trim(), start = Math.floor((text.length * readerContext.readerProgressPercent()) / 100); return text.slice(start, start + 160).trim(); } - function captureFoliateBookmarkPosition() { - if (!readerContext.foliateContinuous) return null; - const marker = readerContext.viewport.getBoundingClientRect().top + 8; - const rows = /** @type {NodeListOf} */ (document.querySelectorAll(".foliate-continuous article[data-section]")); - /** @type {{article: HTMLElement, top: number} | null} */ - let following = null, last = null; - for (const article of rows) { - if (article.hidden) continue; - const { top, bottom } = article.getBoundingClientRect(); - last = { article, top }; - if (top <= marker && bottom > marker) { following = last; break; } - if (!following && top > marker) following = last; - } - const current = following || last; - return current ? { - foliateSection: Number(current.article.dataset.section), - foliateOffset: marker - current.top, - foliateTocIndex: readerContext.navigationState.currentChapterIndex - } : null; - } - - /** @param {import('../../../typings/reader-progress-strict').ProgressState} entry @param {number} [generation] */ - async function restoreFoliateBookmarkPosition(entry, generation = readerContext.beginReaderNavigation()) { - try { - if ( - !readerContext.foliateSectionLoader || - !Number.isInteger(entry.foliateSection) || - !readerContext.isReaderGenerationCurrent("navigation", generation) - ) - return false; - const section = /** @type {number} */ (entry.foliateSection); - let article = await readerContext.foliateSectionLoader(section); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - await readerContext.waitForReader(0, true); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - if (!article?.isConnected) article = await readerContext.foliateSectionLoader(section); - if (!article?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - const marker = readerContext.viewport.getBoundingClientRect().top + 8; - const offset = Number(entry.foliateOffset) || 0; - const start = !offset - ? readerContext.foliateSectionRoot(article).querySelector("h1,h2,h3,h4,h5,h6,p,li,blockquote,pre") || article - : article; - readerContext.foliateScrollAnchors.invalidate(); - readerContext.viewport.scrollTop = Math.max( - 0, - readerContext.viewport.scrollTop + - start.getBoundingClientRect().top - - marker + - offset - ); - readerContext.syncFoliateScrollLocation(); - readerContext.updateTocCurrentMark(); - readerContext.updateProgressTools(); - readerContext.scheduleSave(); - readerContext.setReaderPanelOpen(false, true); - readerContext.foliateScrollAnchors.remember(); - return true; - } catch (error) { - readerContext.reportNavigationError(error, generation); - return false; - } - } - - /** @param {number} percent @param {number} generation */ - async function seekFoliateProgress(percent, generation) { - try { - const sections = readerContext.epubBook?.sections?.filter((section) => section.linear !== "no") || []; - if ( - !sections.length || - !readerContext.foliateSectionLoader || - !readerContext.isReaderGenerationCurrent("navigation", generation) - ) - return; - const position = Math.max(0, Math.min(0.999999, Number(percent) / 100)) * sections.length, - index = Math.min(sections.length - 1, Math.floor(position)); - let article = await readerContext.foliateSectionLoader(index); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return; - await readerContext.waitForReader(0, true); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return; - if (!article?.isConnected) article = await readerContext.foliateSectionLoader(index); - if (!article?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return; - const marker = readerContext.viewport.getBoundingClientRect().top + 8, - offset = article.getBoundingClientRect().height * (position - index); - readerContext.foliateScrollAnchors.invalidate(); - readerContext.viewport.scrollTop = Math.max( - 0, - readerContext.viewport.scrollTop + article.getBoundingClientRect().top - marker + offset - ); - await readerContext.waitForReader(0, true); - if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return; - readerContext.viewport.scrollTop += article.getBoundingClientRect().top - marker + offset + 4; - readerContext.syncFoliateScrollLocation(); - readerContext.updateTocCurrentMark(); - readerContext.updateProgressTools(); - readerContext.scheduleSave(); - readerContext.foliateScrollAnchors.remember(); - } catch (error) { - readerContext.reportNavigationError(error, generation); - } - } - async function renderBookmarks() { const list = /** @type {HTMLElement} */ (document.querySelector("#bookmarks-list")), generation = readerContext.nextReaderGeneration("bookmarks"); @@ -339,7 +229,7 @@ export function createReaderBookmarks(readerContext) { }; } readerContext.syncCurrentPageFromMarker(); - const foliatePosition = readerContext.captureFoliateBookmarkPosition() || readerContext.captureChapterPosition(); + const chapterPosition = readerContext.captureChapterPosition(); const shell = readerContext.documentState.pageCount ? readerContext.pageAtMarker() : null; const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0; const progress = readerContext.readerProgressPercent(); @@ -347,11 +237,9 @@ export function createReaderBookmarks(readerContext) { const scrollTop = readerContext.viewport.scrollTop; const mode = readerContext.capability.mode; const pagedDocument = readerContext.documentState.pageCount && mode !== "text" && mode !== "markdown"; - const locator = Number.isInteger(foliatePosition?.chapterIndex) - ? `chapter:${/** @type {import('../../../typings/reader-progress-strict').ChapterPosition} */ (foliatePosition).chapterIndex}:${Math.round(/** @type {import('../../../typings/reader-progress-strict').ChapterPosition} */ (foliatePosition).chapterOffset)}` - : foliatePosition - ? `foliate:${foliatePosition.foliateSection}:${Math.round(/** @type {number} */ (foliatePosition.foliateOffset))}` - : pagedDocument + const locator = chapterPosition + ? `chapter:${chapterPosition.chapterIndex}:${Math.round(chapterPosition.chapterOffset)}` + : pagedDocument ? `page:${readerContext.documentState.page}:${Math.round(pageOffset)}` : `progress:${progress}:${Math.round(readerContext.htmlFrame ? htmlScrollTop : scrollTop)}`; return { @@ -365,7 +253,7 @@ export function createReaderBookmarks(readerContext) { pageOffset, scrollTop, htmlScrollTop, - ...(foliatePosition || {}) + ...(chapterPosition || {}) }; } @@ -421,9 +309,6 @@ export function createReaderBookmarks(readerContext) { consumeBookmarkHandoff, excerptFromCaret, bookmarkExcerpt, - captureFoliateBookmarkPosition, - restoreFoliateBookmarkPosition, - seekFoliateProgress, renderBookmarks, captureBookmarkSnapshot, setBookmarkDialogModal, diff --git a/static/reader/ui/reader-navigation.mjs b/static/reader/ui/reader-navigation.mjs index 6b02865e30bc83d4ae68fd6e7cdb6485cc0fe90c..2a9e8d7860da1116196c3ca3197ecd160eda0ed1 100644 --- a/static/reader/ui/reader-navigation.mjs +++ b/static/reader/ui/reader-navigation.mjs @@ -4,7 +4,7 @@ export function createReaderNavigation(readerContext) { readerContext.cancelReaderDestinationHold?.(); if (readerContext.epubSeekFrame) cancelAnimationFrame(readerContext.epubSeekFrame); readerContext.epubSeekFrame = 0; - readerContext.foliateScrollAnchors.invalidate(); + readerContext.chapterScrollAnchors.invalidate(); return readerContext.nextReaderGeneration("navigation"); } @@ -167,8 +167,7 @@ export function createReaderNavigation(readerContext) { readerContext.pdfShellWindow?.schedule(); readerContext.scheduleVisiblePdfRenderReconciliation?.(true); readerContext.scheduleMarkerSync(); - readerContext.scheduleFoliateScrollSync(); - readerContext.foliateScrollAnchors.remember(); + readerContext.chapterScrollAnchors.remember(); } /** @param {string} rawUrl @param {{id: string, url: string} | null} [bookmark] @param {boolean} [resumeHistory] */ diff --git a/static/reader/ui/reader-progress.mjs b/static/reader/ui/reader-progress.mjs index 567ef1ec97c717c091022e60399aad8402832850..c5bab648db923cea4e3657fc4e6e6bee16b5d741 100644 --- a/static/reader/ui/reader-progress.mjs +++ b/static/reader/ui/reader-progress.mjs @@ -36,7 +36,7 @@ export function createReaderProgress(readerContext) { const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0; const htmlScrollTop = readerContext.htmlFrame && readerContext.htmlFrame.contentWindow ? readerContext.htmlFrame.contentWindow.scrollY : 0; const readerUrl = readerContext.currentReaderUrl(); - const foliatePosition = readerContext.captureFoliateBookmarkPosition() || readerContext.captureChapterPosition(); + const chapterPosition = readerContext.captureChapterPosition(); return { url: readerContext.sourceUrl, title: readerContext.documentState.title, @@ -50,7 +50,7 @@ export function createReaderProgress(readerContext) { scrollTop: readerContext.viewport.scrollTop, htmlScrollTop, zoom: Math.round(readerContext.documentState.zoom * 100), - ...(foliatePosition || {}) + ...(chapterPosition || {}) }; } @@ -157,33 +157,6 @@ export function createReaderProgress(readerContext) { return readerContext.mediaElement.duration ? Math.round((readerContext.mediaElement.currentTime / readerContext.mediaElement.duration) * 1000) / 10 : 0; - if (readerContext.foliateContinuous) { - const position = readerContext.captureFoliateBookmarkPosition(), - count = readerContext.epubBook?.sections?.filter((section) => section.linear !== "no").length || 0, - article = - position && - document.querySelector( - `.foliate-continuous article[data-section="${position.foliateSection}"]` - ), - fraction = article - ? Math.max( - 0, - Math.min( - 1, - position.foliateOffset / Math.max(1, article.getBoundingClientRect().height) - ) - ) - : 0; - if (position && position.foliateSection < 0) { - const index = -position.foliateSection - 1, spine = readerContext.epubBook?.sections || []; - if (!spine[index]) return 0; - const preceding = spine.slice(0, index).filter(item => item.linear !== "no").length; - return count ? Math.round((preceding / count) * 1000) / 10 : 0; - } - return count && position - ? Math.round(((position.foliateSection + fraction) / count) * 1000) / 10 - : 0; - } if (readerContext.capability.mode === "epub-chapters") return Math.round((readerContext.chapterManifestLoader?.progressFraction() ?? 0) * 1000) / 10; if (readerContext.htmlFrame && readerContext.htmlFrame.contentDocument) { @@ -270,8 +243,6 @@ export function createReaderProgress(readerContext) { if (Number.isInteger(entry.chapterIndex)) { if (!(await readerContext.restoreChapterPosition(entry, generation))) return false; } else if (!(await readerContext.restoreProgressState(entry, generation))) return false; - } else if (mode === "foliate" && Number.isInteger(entry.foliateSection)) { - if (!(await readerContext.restoreFoliateBookmarkPosition(entry, generation))) return false; } else if (readerContext.documentState.pageCount && entry.page) { if ( !(await readerContext.goToPage(entry.page, generation)) || @@ -351,9 +322,7 @@ export function createReaderProgress(readerContext) { } function captureProgressState() { - return readerContext.foliateContinuous - ? readerContext.captureFoliateBookmarkPosition() - : readerContext.capability.mode === "epub-chapters" + return readerContext.capability.mode === "epub-chapters" ? readerContext.captureChapterPosition() : readerContext.mediaElement ? { mediaTime: readerContext.mediaElement.currentTime } @@ -366,8 +335,6 @@ export function createReaderProgress(readerContext) { * @param {number} [generation] */ async function restoreProgressState(state, generation = readerContext.beginReaderNavigation()) { if (!state || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false; - if (readerContext.foliateContinuous && Number.isInteger(state.foliateSection)) - return readerContext.restoreFoliateBookmarkPosition(state, generation); if (readerContext.capability.mode === "epub-chapters" && Number.isInteger(state.chapterIndex)) return readerContext.restoreChapterPosition(state, generation); try { @@ -426,11 +393,6 @@ export function createReaderProgress(readerContext) { } function flushEpubSeek() { - if (readerContext.epubSeekFrame) { - cancelAnimationFrame(readerContext.epubSeekFrame); - readerContext.epubSeekFrame = 0; - readerContext.epubSeekPromise = readerContext.seekFoliateProgress((/** @type {{percent: number, generation: number}} */ (readerContext.epubSeekTarget)).percent, (/** @type {{percent: number, generation: number}} */ (readerContext.epubSeekTarget)).generation); - } return readerContext.epubSeekPromise; } @@ -443,13 +405,7 @@ export function createReaderProgress(readerContext) { if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return; if (readerContext.mediaElement && readerContext.mediaElement.duration) readerContext.mediaElement.currentTime = (readerContext.mediaElement.duration * percent) / 100; - else if (readerContext.foliateContinuous) { - readerContext.epubSeekTarget = { percent, generation }; - readerContext.epubSeekFrame = requestAnimationFrame(() => { - readerContext.epubSeekFrame = 0; - readerContext.epubSeekPromise = readerContext.seekFoliateProgress(percent, generation); - }); - } else if (readerContext.capability.mode === "epub-chapters") { + else if (readerContext.capability.mode === "epub-chapters") { const target = Number.isFinite(percent) ? readerContext.chapterManifestLoader?.progressTarget(percent / 100) : null; if (target) { readerContext.epubSeekPromise = readerContext.restoreChapterPosition({ diff --git a/static/reader/ui/reader-speech.mjs b/static/reader/ui/reader-speech.mjs index 8c80c16f38e9f2b8c02898c7e70349c15eb8eec1..fbb9c4d1e72ff3fd76233a913368b7c6fe57ba6d 100644 --- a/static/reader/ui/reader-speech.mjs +++ b/static/reader/ui/reader-speech.mjs @@ -84,15 +84,12 @@ export function createReaderSpeech(readerContext, loadPlayer) { const readerSpeechTitle = () => document.querySelector("#title")?.textContent?.trim() || document.title || "朗读"; // ---- Per-format unit sources ------------------------------------------- - function foliateSections() { - return (readerContext.epubBook?.sections || []).filter((section) => section.linear !== "no"); - } function chapterCount() { return readerContext.chapterManifestLoader?.count || 0; } function pageCount() { return Number(readerContext.documentState?.pageCount) || 0; } function hasText() { const current = mode(); - if (["text", "markdown", "html", "foliate", "epub-chapters", "pdf"].includes(current)) return true; + if (["text", "markdown", "html", "epub-chapters", "pdf"].includes(current)) return true; if (current === "pdf-pages") return !!(readerContext.ocrManifestUrl || readerContext.pdfOcrManifest || readerContext.pdfDocument); return false; } @@ -109,25 +106,6 @@ export function createReaderSpeech(readerContext, loadPlayer) { const root = () => frame?.contentDocument?.body || null; return { units: 1, first: 0, root, load: async () => rootText(root()), dom: true, frame }; } - if (current === "foliate") { - const sections = foliateSections(); - /** @param {number} index */ - const article = (index) => readerContext.content.querySelector(`.foliate-continuous article[data-section="${index}"]:not(.foliate-section-placeholder)`); - /** @param {number} index */ - const body = (index) => { const node = article(index); const root = node && readerContext.foliateSectionRoot(node); return root?.querySelector(".reader-section-body") || root || null; }; - return { - units: sections.length, first: 0, root: body, - load: async (index) => { - const loaded = body(index); - if (loaded) return rootText(loaded); - const section = sections[index]; - if (!section) return ""; - const doc = await section.createDocument(); - return rootText(doc.body || doc.documentElement); - }, - locate: (index) => readerContext.foliateSectionLoader?.(index) - }; - } if (current === "epub-chapters") { // Valid chapter manifests have consecutive 1-based indices. Reading // their text doesn't require the optional full-text search index. @@ -385,11 +363,7 @@ export function createReaderSpeech(readerContext, loadPlayer) { const box = readerContext.viewport.getBoundingClientRect(); const current = mode(); let unit = info.first; - if (current === "foliate") { - const article = [...readerContext.content.querySelectorAll(/** @type {string} */ (".foliate-continuous article[data-section]"))] - .find((node) => node.getBoundingClientRect().bottom > box.top + 8); - unit = article ? Number(/** @type {HTMLElement} */ (article).dataset.section) : 0; - } else if (current === "epub-chapters") { + if (current === "epub-chapters") { const article = [...readerContext.content.querySelectorAll(".reader-epub-chapter[data-chapter]")] .find((node) => node.getBoundingClientRect().bottom > box.top + 8); const chapter = Number(/** @type {HTMLElement | undefined} */ (article)?.dataset.chapter); diff --git a/static/reader/ui/reader-toc.mjs b/static/reader/ui/reader-toc.mjs index 255fe7d30f20d003c25ec8485421c38bfd7c890e..aa0a8c5b3b78a33ece493d340a7f75ba5817c74d 100644 --- a/static/reader/ui/reader-toc.mjs +++ b/static/reader/ui/reader-toc.mjs @@ -103,7 +103,7 @@ export function createReaderToc(readerContext) { } const marker = readerContext.htmlFrame ? 8 : readerContext.viewport.getBoundingClientRect().top + 8; const root = readerContext.htmlFrame?.contentDocument?.body || readerContext.content; - if (!["foliate", "epub-chapters"].some(mode => mode === readerContext.capability.mode)) { + if (readerContext.capability.mode !== "epub-chapters") { if (readerContext.headingLocationCache?.root !== root || readerContext.headingLocationCache?.entries !== readerContext.navigationState.tocEntries) { readerContext.headingLocationCache?.dispose(); readerContext.headingLocationCache = readerContext.createHeadingLocationCache(root, readerContext.navigationState.tocEntries); @@ -145,9 +145,7 @@ export function createReaderToc(readerContext) { if (!entry || entry.group) return; const generation = readerContext.beginReaderNavigation(); try { - const activated = readerContext.foliateContinuous - ? await readerContext.activateFoliateTocEntry(entry, generation, { closePanel: false }) - : await entry.activate(generation); + const activated = await entry.activate(generation); if (activated === false || !readerContext.isReaderGenerationCurrent("navigation", generation)) return; readerContext.updateNavigationState({ currentChapterIndex: index }); readerContext.updateTocCurrentMark(); diff --git a/static/reader/ui/reader-ui.mjs b/static/reader/ui/reader-ui.mjs index 45c281c3734fcc3d5ddf4238a4b5b7e89c806a3d..5e9d4a9b9a5f4e2f40b4534ca3bdc21e869f2167 100644 --- a/static/reader/ui/reader-ui.mjs +++ b/static/reader/ui/reader-ui.mjs @@ -31,7 +31,7 @@ export function createReaderUi(readerContext) { /** @param {string} theme @param {boolean} [persist] @param {boolean} [animate] */ function applyReaderTheme(theme, persist = true, animate = true) { - const anchor = readerContext.foliateScrollAnchors.capture(); + const anchor = readerContext.chapterScrollAnchors.capture(); if (animate) { clearTimeout(readerContext.themeAnimationTimer); document.documentElement.classList.add("theme-transition"); @@ -52,17 +52,15 @@ export function createReaderUi(readerContext) { readerContext.readerThemeToggle.title = readerContext.readerTheme === "dark" ? "切换到白天模式" : "切换到夜间模式"; readerContext.readerThemeToggle.setAttribute("aria-label", readerContext.readerThemeToggle.title); readerContext.readerThemeToggle.setAttribute("aria-pressed", String(readerContext.readerTheme === "light")); - for (const article of readerContext.content.querySelectorAll(".foliate-continuous > article")) - article.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark"); if (persist) { try { localStorage.setItem("theme", readerContext.readerTheme); } catch (_) {} } - readerContext.foliateScrollAnchors.restore(anchor); + readerContext.chapterScrollAnchors.restore(anchor); } /** @param {number} percent @param {boolean} [persist] */ function setZoom(percent, persist = true) { - const anchor = readerContext.foliateScrollAnchors.capture(); + const anchor = readerContext.chapterScrollAnchors.capture(); const pdfAnchor = ["pdf", "pdf-pages", "image-pages"].includes(readerContext.capability.mode || "unsupported") ? readerContext.pageAtMarker() : null; const pdfBounds = pdfAnchor?.getBoundingClientRect(); @@ -87,14 +85,12 @@ export function createReaderUi(readerContext) { if (readerContext.htmlFrame && readerContext.htmlFrame.contentDocument) readerContext.htmlFrame.contentDocument.documentElement.style.zoom = String(readerContext.documentState.zoom); if (readerContext.pdfDocument) readerContext.rerenderVisiblePdfPages(); - if (readerContext.capability.mode === "foliate") - readerContext.content.style.setProperty("--reader-zoom", String(readerContext.documentState.zoom)); readerContext.viewport.scrollLeft = horizontalCenter * readerContext.viewport.scrollWidth - readerContext.viewport.clientWidth / 2; if (persist) { readerContext.zoomChangedByUser = true; try { localStorage.setItem("reader-zoom", String(normalized)); } catch (_) {} } - readerContext.foliateScrollAnchors.restore(anchor); + readerContext.chapterScrollAnchors.restore(anchor); if (persist) readerContext.scheduleSave(); } diff --git a/static/search/catalog/application/client.js b/static/search/catalog/application/client.js index ecbfd0a35e5c909280217285b4dde0cfd8fcfc30..a6f3b589784482cb1e595d985368a822551e38e4 100644 --- a/static/search/catalog/application/client.js +++ b/static/search/catalog/application/client.js @@ -4,6 +4,8 @@ function create(deps) { const sidebarInitialCache = new Map(); const sidebarInitialPending = new Map(); + /** @type {WeakMap>}>} */ + const extensionGenerations = new WeakMap(); const methods = { /** @this {SpaceCatalogOwner} */ async getRepos() { @@ -22,18 +24,36 @@ /** @this {SpaceCatalogOwner} @param {string | null} repo */ async getExtensions(repo) { const cacheKey = repo || "__global__"; - if (this._extCache && this._extCache.key === cacheKey) return this._extCache.data; - if (!repo) { - const bootstrap = await this.getBootstrap(); - if (bootstrap && Array.isArray(bootstrap.extensions)) { - this._extCache = { key: cacheKey, data: bootstrap.extensions }; - return bootstrap.extensions; - } + let generation = extensionGenerations.get(this); + if (!generation || this._extCache !== generation.marker) { + // The host invalidates by assigning null, even when a request is pending. + const marker = this._extCache || { key: "", data: [] }; + this._extCache = marker; + generation = { marker, pending: new Map() }; + extensionGenerations.set(this, generation); } - const url = repo ? `/api/extensions?repo=${repo}` : "/api/extensions"; - const data = await fetchMetadataList(url); - this._extCache = { key: cacheKey, data }; - return data; + if (generation.marker.key === cacheKey) return generation.marker.data; + const current = generation; + const existing = current.pending.get(cacheKey); + if (existing) return existing; + const pending = Promise.resolve().then(async () => { + if (!repo) { + const bootstrap = await this.getBootstrap(); + if (bootstrap && Array.isArray(bootstrap.extensions)) return bootstrap.extensions; + } + const url = repo ? `/api/extensions?repo=${repo}` : "/api/extensions"; + return fetchMetadataList(url); + }).then(data => { + if (extensionGenerations.get(this) === current && this._extCache === current.marker) { + current.marker = { key: cacheKey, data }; + this._extCache = current.marker; + } + return data; + }).finally(() => { + if (current.pending.get(cacheKey) === pending) current.pending.delete(cacheKey); + }); + current.pending.set(cacheKey, pending); + return pending; }, /** @param {string} repo */ getFolders(repo) { return fetchMetadataList(`/api/folders/${repo}`); }, diff --git a/static/search/sidebar/presentation/folder-tree.js b/static/search/sidebar/presentation/folder-tree.js index 88273e17f1cc8fb2e1da24bd4241b2252a69eb19..88f2500b6bdcfa60c6ab96bc74f18dbadbf0fcc0 100644 --- a/static/search/sidebar/presentation/folder-tree.js +++ b/static/search/sidebar/presentation/folder-tree.js @@ -240,13 +240,12 @@ function persistFolderSelection(subtreeSet, selfSet) { deps.commitSelection(Array.from(subtreeSet), Array.from(selfSet)); } -/** @param {VoiceOfMLFilterFolder[]} nodes @param {string[]} subtreePaths @param {string[]} selfPaths */ -function collectFolderNodePaths(nodes, subtreePaths, selfPaths) { +/** @param {VoiceOfMLFilterFolder[]} nodes @param {string[]} selfPaths */ +function collectFolderNodePaths(nodes, selfPaths) { for (const node of nodes) { - if (!node.isRoot && node.path) subtreePaths.push(node.path); if (node.hasDirectFiles) selfPaths.push(node.path); if (node.children && node.children.length > 0) { - collectFolderNodePaths(node.children, subtreePaths, selfPaths); + collectFolderNodePaths(node.children, selfPaths); } } } @@ -361,7 +360,7 @@ function appendFilterTreeNode(container, node, depth, subtreeSet, selfSet, looku function handleFolderCheckboxChange(node) { const subtreeSet = getFolderSubtreeSet(); const selfSet = getFolderSelfSet(); - const { full } = deps.selection.folderSelectionState(node, subtreeSet, selfSet); + const { full } = deps.selection.folderSelectionState(node, subtreeSet, selfSet, getFolderSelectionLookup(subtreeSet, selfSet)); setNodeSubtreeSelection(node, !full, subtreeSet, selfSet); persistFolderSelection(subtreeSet, selfSet); refreshFilterFolderSelectionState(); @@ -400,9 +399,8 @@ function invertSelection() { if (!deps.readView().tree || deps.readView().tree.length === 0) return; var subtreeSet = getFolderSubtreeSet(); var selfSet = getFolderSelfSet(); - var allSubtreePaths = /** @type {string[]} */ ([]); var allSelfPaths = /** @type {string[]} */ ([]); - collectFolderNodePaths(deps.readView().tree, allSubtreePaths, allSelfPaths); + collectFolderNodePaths(deps.readView().tree, allSelfPaths); var nextSubtreeSet = new Set(/** @type {string[]} */ ([])); var nextSelfSet = new Set(); for (const path of allSelfPaths) { diff --git a/tests/fixtures/reader/issues/manifest.json b/tests/fixtures/reader/issues/manifest.json index b2b58babfe5ed0defd059d83e27d387357cd3b30..e8897841b15be0caa775fd8118e7b8a1fabbc03e 100644 --- a/tests/fixtures/reader/issues/manifest.json +++ b/tests/fixtures/reader/issues/manifest.json @@ -2,7 +2,7 @@ "schema": 1, "fixtures": [ { "id": "pdf-pages-wide-image", "format": "pdf-pages", "source": "production-id:0ii7sf11ig9ls", "expected": "images fit page shells without overlap", "test": "test_converted_pdf_pages_fit_wide_images_without_overlap" }, - { "id": "epub-nested-resources", "format": "epub", "source": "minimized from nested package resource failures", "expected": "chapter images resolve without escaping the source boundary", "test": "test_foliate_navigation_path_dark_links_and_unique_sections" }, + { "id": "epub-nested-resources", "format": "epub", "source": "minimized from nested package resource failures", "expected": "chapter images resolve without escaping the source boundary", "test": "test_epub_chapters_serve_nested_bundle_with_resources" }, { "id": "text-multibyte-boundary", "format": "txt", "source": "minimized from split UTF-8 and legacy encoding failures", "expected": "stream decoding preserves split multibyte characters", "test": "test_txt_displays_before_stream_finishes" } ,{ "id": "reader-security-boundaries", "format": "html/epub-chapters/epub", "source": "inline deterministic browser routes", "expected": "active resources, oversized chapter resources, and ZIP bomb metadata are rejected while safe text remains", "test": "test_malicious_html_css_and_svg_are_inert_and_keep_safe_text" } ,{ "id": "reader-navigation-matrix", "format": "html/md/pdf/epub-chapters", "source": "inline deterministic browser routes", "expected": "TOC, outline, first/lazy chapter, and cross-panel store updates navigate through visible Reader UI", "test": "test_epub_chapters_load_first_lazy_next_and_toc_destination" } diff --git a/tests/gates/ci-test-inventory.json b/tests/gates/ci-test-inventory.json index 2aaf1afe4951fe8e42814d77d831958aba9be74f..dccd4687562933bf2dc3f247898640ab71d75e31 100644 --- a/tests/gates/ci-test-inventory.json +++ b/tests/gates/ci-test-inventory.json @@ -490,10 +490,6 @@ "kind": "script", "source": "scripts/reader/check_reader_media_coverage.mjs" }, - "tests/reader/test_foliate_proxy.mjs": { - "kind": "script", - "source": "scripts/reader/check_reader_media_coverage.mjs" - }, "tests/reader/media/test_reader_media_baseline.mjs": { "kind": "script", "source": "scripts/reader/check_reader_media_coverage.mjs" diff --git a/tests/gates/test_static_checks.py b/tests/gates/test_static_checks.py index 0162c2a3d7c976fa9dfd51102e8009fb28456f18..887d0260cc62f31bde832d0ca740aca58af5ec71 100644 --- a/tests/gates/test_static_checks.py +++ b/tests/gates/test_static_checks.py @@ -2887,9 +2887,9 @@ const options = {signal: undefined}; 'scripts/reader/check_reader_media_coverage.mjs', 'scripts/check_tap_contracts.mjs', 'tests/reader/media/test_reader_media_baseline.mjs', 'tests/reader/media/test_reader_media_metadata.mjs', - 'tests/reader/copy_reader_vendor.test.mjs', 'tests/reader/test_foliate_proxy.mjs', + 'tests/reader/copy_reader_vendor.test.mjs', 'tests/reader/media/test_ruffle_closure.mjs', 'tests/service_worker/test_ruffle_retention.js', - 'scripts/build/copy_reader_vendor.mjs', 'scripts/build/fetch_foliate_reader.mjs', + 'scripts/build/copy_reader_vendor.mjs', 'scripts/build/check_reader_release.mjs', 'static/reader-resources.js', 'static/sw.js', 'static/reader/core/reader-source.mjs', 'static/reader/core/reader-document-loader.mjs'] for path in paths: diff --git a/tests/gates/test_static_contract.py b/tests/gates/test_static_contract.py index d8737f1de3d7bd779681817f1c5c621187e2750f..b530d21ccd92a3811adb6189bdd2243eee8db67e 100644 --- a/tests/gates/test_static_contract.py +++ b/tests/gates/test_static_contract.py @@ -355,8 +355,8 @@ console.log('OCR module contract passed; 6 negative controls rejected'); self.assertIn("async function activateChapter", reader) assert_source_contains(self, "progressUndo.hidden = !previousProgressState", reader) assert_source_contains(self, "result.activate(generation)", reader) - modes = {'pdf': 'pdf', 'pdf-pages': 'pdf-pages', 'epub': 'foliate', 'mobi': 'foliate', - 'fb2': 'foliate', 'txt': 'text', 'md': 'markdown', 'jpg': 'image', + modes = {'pdf': 'pdf', 'pdf-pages': 'pdf-pages', 'epub': None, 'mobi': None, + 'fb2': None, 'txt': 'text', 'md': 'markdown', 'jpg': 'image', 'mp3': 'audio', 'wav': 'audio', 'flac': 'audio', 'mp4': 'video', 'mov': 'video', 'docx': None, 'epub-chapters': 'epub-chapters', 'html': 'html', 'htm': 'html'} evaluated = subprocess.run( @@ -375,7 +375,8 @@ console.log('OCR module contract passed; 6 negative controls rejected'); self.assertIn('VoiceOfMLReaderResources.vendorUrl("pdf", "/static/")', reader) assert_source_contains(self, 'const PDFJS_WASM_URL = "/static/vendor/wasm/"', reader) assert_source_contains(self, 'wasmUrl: PDFJS_WASM_URL', reader) - self.assertIn('/static/foliate-reader/view.js', reader) + self.assertNotIn('/static/foliate-reader/', reader) + self.assertNotIn('renderFoliate', reader) self.assertIn('VoiceOfMLReaderResources.vendorUrl("purify", "/static/")', reader) self.assertNotIn('cdn.jsdelivr.net', reader) self.assertIn("IntersectionObserver", reader) @@ -606,13 +607,11 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected'); self.assertIn('VoiceOfMLReaderStore.put', reader) self.assertIn('VoiceOfMLReaderStore.get', reader) self.assertIn('function goToPage', reader) - self.assertIn('foliateContinuous', reader) self.assertIn('viewport.scrollTop', reader) self.assertIn("base-uri 'self' blob:", reader_html) self.assertIn("style-src 'self' 'unsafe-inline' blob:", reader_html) for value in ('epubSearchIndex', 'epubSearchIndexReady', 'epubZipPath', 'buildEpubSearchIndex', 'activateIndexedEpubResult', 'runIndexedEpubSearch'): self.assertNotIn(value, reader) - self.assertRegex(reader, r'await view\.open\(\s*new File\(\s*\[bytes\]') self.assertNotIn('epubRendition.setReaderTheme(readerTheme)', reader) self.assertNotIn('epubRendition.themes', reader) self.assertIn('function applyReaderTheme', reader) @@ -627,18 +626,7 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected'); (ROOT / "static/search/reader-host/application/host.js").read_text()) self.assertIn('readerHost.handleReaderMessage(event)', self.js) self.assertNotIn('loadFoliateDocument', reader) - self.assertIn('async function renderFoliate', reader) - foliate = (ROOT / "static/reader/formats/reader-foliate-format.mjs").read_text(encoding="utf-8") - foliate_import = ('const foliateModuleUrl = "/static/foliate-reader/view.js"; ' - 'const prepared = readerContext.prepareReaderDocument([import(foliateModuleUrl)]);') - assert_source_contains(self, foliate_import, foliate) - for before, after in (('import(foliateModuleUrl)', 'Promise.resolve(null)'), - ('/static/foliate-reader/view.js', '/static/wrong-view.js')): - with self.subTest(foliate_import=before): - self.assertEqual(foliate.count(before), 1) - with self.assertRaises(AssertionError): - assert_source_contains(self, foliate_import, foliate.replace(before, after)) - self.assertIn('async function renderFoliate', reader) + assert_source_contains(self, '"epub-chapters": pair(loadChapterManifestDocument, renderChapterManifest)', reader) assert_source_contains(self, 'const READER_PROXY_TIMEOUT_MS = 120000', reader) self.assertIn('function fetchWithReaderTimeout', reader) self.assertIn('function renderPdfShell', reader) @@ -673,16 +661,12 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected'); for path in ('/static/vendor/pdf.min.mjs', '/static/vendor/pdf.worker.min.mjs', '/static/vendor/epub.min.js', '/static/vendor/marked.min.js', '/static/vendor/purify.min.js'): self.assertNotIn(path, self.sw) - def test_foliate_continuous_reader_preserves_embedded_resources(self): - epub = (ROOT / "static/foliate-reader/epub.js").read_text(encoding="utf-8") - mobi = (ROOT / "static/foliate-reader/mobi.js").read_text(encoding="utf-8") + def test_chapter_reader_bounds_embedded_resources(self): + chapter = (ROOT / "static/reader/formats/reader-chapter-format.mjs").read_text(encoding="utf-8") reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8") - self.assertIn("const url = await this.#loader.loadItem(item)", epub) - self.assertIn("const text = await response.text()", epub) - self.assertIn("parseFromString(text, MIME.HTML)", epub) - self.assertIn("await this.replaceResources(doc)", mobi) - self.assertIn("const replaced = await this.replaceResources(str)", mobi) - self.assertIn("for (const [url, node] of this.#inlineMap)", mobi) + assert_source_contains(self, 'readerContext.trustedChapterReferenceUrl(value, url, manifestBase)', chapter) + assert_source_contains(self, 'const resolved = resourceUrl(value, url, name === "href" ? "href" : "resource")', chapter) + assert_source_contains(self, 'element.removeAttribute(name)', chapter) self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:") def test_mobile_shell_hides_sidebars_before_application_startup(self): @@ -747,7 +731,6 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected'); def test_image_pages_prioritize_visible_pages_without_document_image_race(self): reader = read_reader_source(ROOT) - assert_source_contains(self, 'root: viewport, rootMargin: `${FOLIATE_PREFETCH_MARGIN}px`', reader) assert_source_contains(self, 'root: viewport, rootMargin: `${PDF_PREFETCH_MARGIN}px 0px`', reader) assert_source_contains(self, 'const visibleObserver = new IntersectionObserver', reader) assert_source_contains(self, 'renderPdfInBackground(entry.target)', reader) diff --git a/tests/live/test_reader_live_smoke.py b/tests/live/test_reader_live_smoke.py index 105788d8bf50c432525a87bce53012bd7ec16953..1c7bcdeb98cb308dcd58eebee6129316a2f994ca 100644 --- a/tests/live/test_reader_live_smoke.py +++ b/tests/live/test_reader_live_smoke.py @@ -31,6 +31,7 @@ class ReaderLiveSmokeTests(unittest.TestCase): inventory = json.loads(subprocess.check_output([ "node", "-e", 'console.log(JSON.stringify(require("./static/reader-resources.js").readerFiles))' ], cwd=Path(__file__).resolve().parents[2])) + self.assertFalse([name for name in inventory if 'foliate' in name.lower()]) sw = self.fetch('/sw.js') pinned = set(re.findall(r'/static/[^"\s]+\.[0-9a-f]{12}\.(?:js|mjs|css)', sw)) def current(name): @@ -38,7 +39,7 @@ class ReaderLiveSmokeTests(unittest.TestCase): matches = [url for url in pinned if re.fullmatch('/static/' + re.escape(stem) + r'\.[0-9a-f]{12}\.' + extension, url)] self.assertEqual(len(matches), 1, name) return matches[0] - files = ["/static/reader.html", *map(current, inventory), "/static/foliate-reader/view.js"] + files = ["/static/reader.html", *map(current, inventory)] bodies = {path: self.fetch(path) for path in files} self.assertTrue(all(len(body) > 20 for body in bodies.values())) self.assertRegex(bodies[current('reader.js')], r"createReaderRuntime|VoiceOfMLReaderRuntime") diff --git a/tests/performance/test_reader_performance.py b/tests/performance/test_reader_performance.py index fb50e4470334dd449c7fad70ae742dccf43b707b..a370cf2dee0273d3a49a9946df5e6257e143b374 100644 --- a/tests/performance/test_reader_performance.py +++ b/tests/performance/test_reader_performance.py @@ -1558,465 +1558,22 @@ class ReaderPerformanceTest(unittest.TestCase): self.assertIn("第二章", second.inner_text()) self.assertEqual(unexpected_requests, []) - def test_foliate_normalizes_legacy_chm_markup_and_keeps_resources(self): - # This case verifies preservation of source CSS; night colors have a separate contract. - self.page.add_init_script("localStorage.setItem('theme', 'light')") - with zipfile.ZipFile(io.BytesIO(epub_with_legacy_chm_markup())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - chapter_path = "OEBPS/chapters space%20/chapter.xhtml" - files["OEBPS/content.opf"] = files["OEBPS/content.opf"].replace( - b'href="chapter.xhtml"', - f'href="{urllib.parse.quote(chapter_path.removeprefix("OEBPS/"))}"'.encode(), - ) - resource_files = { - f"OEBPS/images %23/{name}": PNG_BYTES - for name in ("cover#1.png", "cover space.png", "literal%20.png", "literal%23.png") - } - resource_files["OEBPS/chapters space%20/local image.png"] = PNG_BYTES - images = [] - for path in resource_files: - relative = (path.removeprefix("OEBPS/chapters space%20/") - if path.startswith("OEBPS/chapters space%20/") - else "../" + path.removeprefix("OEBPS/")) - images.append(f'') - chapter = files.pop("OEBPS/chapter.xhtml").decode().replace( - 'href="style.css"', 'href="../style.css"', - ).replace('src="picture.svg"', 'src="../picture.svg"') - files[chapter_path] = chapter.replace( - "' - + "".join(images) + '查看原图 getComputedStyle(element).color"), "rgb(1, 2, 3)") - self.assertTrue((image.get_attribute("src") or "").startswith("blob:")) - self.assertGreater(image.bounding_box()["height"], 0) - self.page.wait_for_function("""count => performance.getEntriesByType('resource') - .filter(entry => entry.name.includes('/api/reader-resource?')).length >= count""", - arg=len(resource_files)) - self.assertEqual(set(requested_paths), set(resource_files)) - resource_paths = self.page.locator(".foliate-continuous article[data-section='0'] svg image").evaluate_all("""images => - images.map(image => new URL(image.getAttribute('href'), location.origin).searchParams.get('path'))""") - self.assertCountEqual(resource_paths, resource_files) - with self.page.expect_popup() as opened: - self.page.locator('.foliate-continuous #full-image').click() - popup = opened.value - popup.wait_for_load_state() - self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(popup.url).query)['path'], - ['OEBPS/chapters space%20/local image.png']) - popup.wait_for_function('() => document.querySelector("img")?.naturalWidth === 1') - popup.close() - - def test_foliate_navigation_path_dark_links_and_unique_sections(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - self.addCleanup(context.close) - page = context.new_page() - page.add_init_script("localStorage.setItem('theme', 'dark')") - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_navigation())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/e2e.epub" - url = f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=E2E&path=Test%2Fbooks" - page.goto(url, wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 2") - link = page.locator(".foliate-continuous article[data-section='0'] a").first - link.wait_for(state="attached") - self.assertIsNotNone(page.locator(".foliate-continuous article[data-section='0']").evaluate("article => article.shadowRoot")) - title_display = page.locator("#title").evaluate("element => getComputedStyle(element).display") - page.locator(".foliate-continuous article[data-section='0']").evaluate("article => { const style = document.createElement('style'); style.textContent = '#title{display:none!important} a{color:rgb(1,2,3)!important;border-top-style:dotted}'; article.shadowRoot.appendChild(style); }") - self.assertEqual(page.locator("#title").evaluate("element => getComputedStyle(element).display"), title_display) - self.assertEqual(link.evaluate("element => getComputedStyle(element).borderTopStyle"), "dotted") - self.assertEqual(link.evaluate("element => getComputedStyle(element).color"), "rgb(138, 180, 232)") - open_reader_panel(page) - for theme, color in (("light", "rgb(1, 2, 3)"), ("dark", "rgb(138, 180, 232)")): - page.locator("#theme-toggle").click() - page.wait_for_function("() => !document.documentElement.classList.contains('theme-transition')") - self.assertEqual(page.locator("html").get_attribute("data-theme"), theme) - self.assertEqual(link.evaluate("element => getComputedStyle(element).color"), color) - page.locator("#history").click() - self.assertEqual(page.locator("#reader-path").text_content(), "Test/books") - self.assertIsNone(page.locator("#reader-path").get_attribute("hidden")) - initial_url = page.url - link.click() - page.wait_for_function("() => document.querySelector('#viewport').scrollTop > 0") - self.assertEqual(page.url, initial_url) - self.assertAlmostEqual(page.locator("#one").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2) - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(1).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(2)').classList.contains('is-current')") - page.wait_for_function("() => document.querySelectorAll('.foliate-continuous article[data-section]').length === 3") - sections = page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => item.dataset.section)") - self.assertEqual(sections, ["0", "1", "2"]) - page.locator("#viewport").evaluate("element => { element.scrollTop = element.scrollHeight; element.dispatchEvent(new Event('scroll')); }") - page.wait_for_timeout(250) - self.assertEqual(page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => item.dataset.section)"), ["0", "1", "2"]) - context.close() - def test_foliate_rapid_toc_navigation_keeps_latest_destination(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/race.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Race", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - page.evaluate("""() => { - const sections = document.querySelector('foliate-view').book.sections.filter(section => section.linear !== 'no'); - for (const [index, delay] of [[6, 350], [10, 20]]) { - const original = sections[index].createDocument.bind(sections[index]); - sections[index].createDocument = () => new Promise((resolve, reject) => setTimeout(() => original().then(resolve, reject), delay)); - } - document.querySelectorAll('#toc-list .panel-item-main')[5].click(); - document.querySelectorAll('#toc-list .panel-item-main')[9].click(); - }""") - page.wait_for_timeout(700) - self.assertTrue(page.locator("#toc-list .toc-item").nth(9).evaluate("item => item.classList.contains('is-current')")) - self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2) - sections = page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => Number(item.dataset.section))") - self.assertEqual(sections, sorted(set(sections))) - context.close() - def test_foliate_failed_toc_section_can_retry(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - errors = [] - page.on("pageerror", lambda error: errors.append(str(error))) - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/retry.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Retry", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - page.evaluate("""() => { - const sections = document.querySelector('foliate-view').book.sections.filter(item => item.linear !== 'no'); - const section = sections[10]; - window.__neighborFailures = 0; - sections[9].createDocument = () => { window.__neighborFailures++; return Promise.reject(new Error('neighbor unavailable')); }; - const original = section.createDocument.bind(section); let attempts = 0; - section.createDocument = () => ++attempts === 1 ? Promise.reject(new Error('transient section failure')) : original(); - window.__retrySection = () => document.querySelectorAll('#toc-list .panel-item-main')[9].click(); - }""") - page.evaluate("window.__retrySection()") - page.wait_for_timeout(100) - page.evaluate("window.__retrySection()") - page.locator("#chapter-10").wait_for(timeout=5000) - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2) - self.assertGreater(page.evaluate("window.__neighborFailures"), 0) - self.assertEqual(page.locator(".reader-error").count(), 0) - self.assertEqual(errors, []) - context.close() - def test_foliate_duplicate_toc_navigation_shares_section_load(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/deduplicate.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Deduplicate", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - page.evaluate("""() => { - const section = document.querySelector('foliate-view').book.sections.filter(item => item.linear !== 'no')[10]; - const original = section.createDocument.bind(section); window.__sectionCreates = 0; - section.createDocument = () => { window.__sectionCreates += 1; return new Promise((resolve, reject) => setTimeout(() => original().then(resolve, reject), 200)); }; - document.querySelectorAll('#toc-list .panel-item-main')[9].click(); - document.querySelectorAll('#toc-list .panel-item-main')[9].click(); - }""") - page.locator("#chapter-10").wait_for(timeout=5000) - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - self.assertEqual(page.evaluate("window.__sectionCreates"), 1) - self.assertEqual(page.locator(".foliate-continuous article[data-section='10']").count(), 1) - self.assertTrue(page.locator("#toc-list .toc-item").nth(9).evaluate("item => item.classList.contains('is-current')")) - context.close() - def test_foliate_chapter_buttons_use_continuous_reader_navigation(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/chapter-buttons.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Buttons", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(9).click() - page.locator("#chapter-10").wait_for(timeout=5000) - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - open_reader_panel(page) - page.locator(".reader-chapter-next").click() - page.locator("#chapter-11").wait_for(timeout=5000) - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(11)').classList.contains('is-current')") - self.assertAlmostEqual(page.locator("#chapter-11").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2) - self.assertTrue(page.locator("#toc-list .toc-item").nth(10).evaluate("item => item.classList.contains('is-current')")) - context.close() - def test_foliate_toc_retains_groups_and_chapter_buttons_skip_them(self): - with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace( - b'
  1. 第一卷
  2. 第二卷
    1. ', b'
') - self.page.unroute('**/api/reader-content**') - self.page.route('**/api/reader-content**', lambda route: route.fulfill( - status=200, content_type='application/epub+zip', body=zip_bytes(files))) - source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/groups.epub' - self.page.goto(f'{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe="")}&ext=epub', wait_until='domcontentloaded') - self.page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 4") - open_reader_panel(self.page) - self.assertEqual(self.page.locator('#toc-list [role=heading]').all_text_contents(), ['第一卷', '第二卷']) - self.assertEqual(self.page.locator('#toc-list [role=link]').all_text_contents(), ['第一章', '第二章']) - self.assertEqual(self.page.locator('#toc-list .toc-group [tabindex]').count(), 0) - self.page.locator('#toc-list [role=link]').first.click() - self.page.wait_for_function("() => document.querySelector('[data-toc-index=\"1\"]').classList.contains('is-current')") - self.page.wait_for_function("() => document.querySelector('#history').getAttribute('aria-expanded') === 'false'") - open_reader_panel(self.page) - self.page.locator('.reader-chapter-next').click() - self.page.wait_for_function("() => document.querySelector('[data-toc-index=\"3\"]').classList.contains('is-current')") - self.assertAlmostEqual(self.page.locator('#two').evaluate( - "e => e.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2) - - def test_chm_rebuilt_spine_ignores_previous_asset_positions(self): - with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - files['OEBPS/content.opf'] = files['OEBPS/content.opf'].replace( - b'', b'') - root = 'objects/aa/' + 'a' * 64 + '/' - files['META-INF/reader-chm.json'] = json.dumps({'version': 1, - 'previous_path': root + 'calibre-chm-epub-v2/document.epub', - 'previous_sections': ['OEBPS/nav.xhtml', 'OEBPS/chapter-1.xhtml', 'OEBPS/chapter-2.xhtml']}) - self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill( - status=200, content_type='text/javascript', body=STORE_SCRIPT.replace( - 'get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300))', - "get: url => Promise.resolve(url.includes('calibre-chm-epub-v2') ? {foliateSection:2, foliateOffset:100, foliateTocIndex:1} : null)"))) - self.page.route('**/api/reader-content**', lambda route: route.fulfill( - status=200, content_type='application/epub+zip', body=zip_bytes(files))) - source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/manual-chm-navigation-v2/document.epub' - self.page.goto(f'{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe="")}&ext=epub', wait_until='domcontentloaded') - self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") - self.page.wait_for_function("() => window.__savedReaderProgress?.foliateSection === 0") - previous = source.replace('manual-chm-navigation-v2', 'calibre-chm-epub-v2') - self.page.evaluate("url => VoiceOfMLReaderStore.putBookmark({id:'old-chm-mark',url,foliateSection:1,foliateOffset:150,label:'Old chapter one',createdAt:1})", previous) - open_reader_panel(self.page) - self.page.locator('#bookmarks-tab').click() - self.assertEqual(self.page.locator('#bookmarks-list .panel-item-main', has_text='Old chapter one').count(), 0) - self.assertIn('manual-chm-navigation-v2', urllib.parse.unquote(self.page.url)) - def test_foliate_scroll_updates_toc_on_animation_frame(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/scroll-toc.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=ScrollToc", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(9).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - page.locator('.foliate-continuous article[data-section="11"] #chapter-11').wait_for(state='attached') - page.evaluate("""() => { const viewport = document.querySelector('#viewport'), target = document.querySelector('.foliate-continuous article[data-section="11"]').shadowRoot.querySelector('#chapter-11'); viewport.dispatchEvent(new WheelEvent('wheel', {deltaY:100, bubbles:true})); viewport.scrollTop += target.getBoundingClientRect().top - viewport.getBoundingClientRect().top + 100; viewport.dispatchEvent(new Event('scroll')); }""") - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(11)').classList.contains('is-current')", timeout=1000) - context.close() - def test_foliate_resize_keeps_current_text_anchor(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/scroll-anchor.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Anchor", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(9).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - page.evaluate("""() => { const viewport = document.querySelector('#viewport'); viewport.style.overflowAnchor = 'none'; viewport.dispatchEvent(new Event('scroll')); }""") - page.wait_for_timeout(50) - before = page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top") - page.evaluate("""() => { const spacer = document.createElement('div'); spacer.style.height = '600px'; const articles = [...document.querySelectorAll('.foliate-continuous article[data-section]:not(.foliate-section-placeholder)')].filter(article => Number(article.dataset.section) < 10); articles[articles.length - 1].shadowRoot.querySelector('.reader-section-body').appendChild(spacer); }""") - page.wait_for_function("top => Math.abs(document.querySelector('.foliate-continuous article[data-section=\"10\"]').shadowRoot.querySelector('#chapter-10').getBoundingClientRect().top - top) < 3", arg=before, timeout=2000) - context.close() - def test_foliate_virtualizes_distant_sections_and_reloads_them(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/virtual.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Virtual", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - for index in [1, 3, 5, 7, 9, 11, 13]: - page.evaluate("i => document.querySelectorAll('#toc-list .panel-item-main')[i].click()", index) - page.wait_for_function("i => document.querySelectorAll('#toc-list .toc-item')[i].classList.contains('is-current')", arg=index) - page.wait_for_timeout(100) - self.assertLessEqual(page.locator(".foliate-continuous article[data-section]:not(.foliate-section-placeholder)").count(), 12) - self.assertGreater(page.locator(".foliate-section-placeholder").count(), 0) - sections = page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => Number(item.dataset.section))") - self.assertEqual(sections, sorted(set(sections))) - page.evaluate("() => document.querySelectorAll('#toc-list .panel-item-main')[1].click()") - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(2)').classList.contains('is-current')") - page.locator(".foliate-continuous article[data-section]:not(.foliate-section-placeholder) #chapter-2").wait_for(timeout=5000) - page.wait_for_function("() => document.querySelectorAll('.foliate-continuous article[data-section]:not(.foliate-section-placeholder)').length <= 12") - context.close() - def test_large_foliate_toc_keeps_a_bounded_dom_window(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters(600))) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large-toc.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=LargeToc", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelector('#toc-list')?.classList.contains('toc-list-virtualized')") - open_reader_panel(page) - self.assertLess(page.locator("#toc-list .toc-item").count(), 100) - page.evaluate("""() => { const panel = document.querySelector('#toc-panel'); panel.scrollTop = 20000; panel.dispatchEvent(new Event('scroll')); }""") - page.wait_for_function("() => [...document.querySelectorAll('#toc-list .toc-item')].some(row => row.textContent.includes('章节 501'))") - self.assertLess(page.locator("#toc-list .toc-item").count(), 100) - page.locator('#toc-list [data-toc-index="500"] .panel-item-main').click() - page.wait_for_function("() => document.querySelector('#toc-list [data-toc-index=\"500\"]')?.classList.contains('is-current')") - self.assertEqual(page.locator('#toc-list .is-current').get_attribute('data-toc-index'), '500') - context.close() - def test_foliate_full_search_uses_continuous_reader_navigation(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/search.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Search", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#full-search-toggle").click() - page.locator("#full-search-input").fill("正文 10") - page.locator("#full-search-results .full-search-result").first.wait_for(timeout=10000) - page.locator("#full-search-results .full-search-result").first.click() - page.locator("#chapter-10").wait_for(timeout=5000) - page.locator(".foliate-continuous .full-search-highlight").wait_for(timeout=5000) - page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')") - self.assertTrue(page.locator(".foliate-continuous .full-search-highlight").evaluate("element => { const rect = element.getBoundingClientRect(), viewport = document.querySelector('#viewport').getBoundingClientRect(); return rect.bottom > viewport.top && rect.top < viewport.bottom; }")) - context.close() - def test_foliate_bookmark_restores_continuous_section_position(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/bookmark.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Bookmark", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(9).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - page.locator("#bookmark-ribbon").click() - page.locator("#bookmark-add").click() - page.wait_for_function("() => window.__readerBookmarks.length === 1") - bookmark = page.evaluate("window.__readerBookmarks[0]") - self.assertEqual(bookmark.get("foliateSection"), 10) - page.locator("#viewport").evaluate("element => { element.scrollTop = 0; element.dispatchEvent(new Event('scroll')); }") - open_reader_panel(page) - page.locator("#bookmarks-tab").click() - page.locator("#bookmarks-list .panel-item-main").click() - page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')") - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3) - context.close() - def test_foliate_progress_slider_uses_continuous_viewport(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/progress.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Progress", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(3).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(4)').classList.contains('is-current')") - open_reader_panel(page) - page.locator(".reader-progress-range").dispatch_event("pointerdown") - # Seek inside section 12, away from its fractional-pixel top boundary. - page.locator(".reader-progress-range").fill("81") - page.locator(".reader-progress-range").dispatch_event("pointerup") - page.wait_for_function("() => { const article = document.querySelector('.foliate-continuous article[data-section=\"12\"]'), viewport = document.querySelector('#viewport'); if (!article) return false; const marker = viewport.getBoundingClientRect().top + 8, rect = article.getBoundingClientRect(); return rect.top <= marker && rect.bottom > marker; }") - self.assertAlmostEqual(float(page.locator(".reader-progress-percent").text_content().rstrip("%")), 81, delta=7) - page.locator('.foliate-section-placeholder').first.evaluate("node => node.style.setProperty('--foliate-placeholder-height', `${node.getBoundingClientRect().height + 600}px`)") - page.locator(".reader-progress-undo").click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(4)').classList.contains('is-current')") - self.assertAlmostEqual(page.locator("#chapter-4").evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3) - self.assertTrue(page.locator(".reader-progress-undo").is_hidden()) - page.wait_for_function("() => window.__savedReaderProgress?.foliateSection === 4") - context.close() - def test_foliate_history_saves_structured_section_position(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/history.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=History", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(9).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')") - page.evaluate("window.dispatchEvent(new Event('pagehide'))") - page.wait_for_function("() => window.__savedReaderProgress && window.__savedReaderProgress.foliateSection === 10") - self.assertEqual(page.evaluate("window.__savedReaderProgress.foliateTocIndex"), 9) - context.close() - def test_foliate_history_restores_structured_section_position(self): - context = self.browser.new_context(viewport={"width": 390, "height": 844}) - page = context.new_page() - restored_store = STORE_SCRIPT.replace("get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),", "get: () => Promise.resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9, zoom: 1}),") - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=restored_store)) - page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters())) - source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/restore.epub" - page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Restore", wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)')?.classList.contains('is-current')", timeout=10000) - self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3) - delayed_store = restored_store.replace( - "get: () => Promise.resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9, zoom: 1}),", - "get: () => new Promise(resolve => { window.__releaseHistory = () => resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9, zoom: 1}); }),", - ) - page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=delayed_store)) - page.reload(wait_until="domcontentloaded") - page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14") - open_reader_panel(page) - page.locator("#toc-list .panel-item-main").nth(1).click() - page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(2)').classList.contains('is-current')") - page.evaluate("window.__releaseHistory()") - page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") - page.wait_for_function("() => window.__savedReaderProgress?.foliateSection === 2") - self.assertAlmostEqual(page.locator("#chapter-2").evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3) - context.close() + def test_reader_store_preserves_old_history_and_keeps_current_bookmarks(self): context = self.browser.new_context(viewport={"width": 390, "height": 844}) diff --git a/tests/performance/test_reader_toc_latency.py b/tests/performance/test_reader_toc_latency.py index 2abb041f4cb9f5a70d3ac2abbf3eb010dfe624cc..cbc46073d6ca942c5d59d66a58ab9668f8b5245d 100644 --- a/tests/performance/test_reader_toc_latency.py +++ b/tests/performance/test_reader_toc_latency.py @@ -1,25 +1,54 @@ -"""Focused native EPUB TOC demand acceptance, using the shared two-site server.""" +"""TOC UI and chapter-bundle navigation latency, using the shared two-site server.""" import unittest -from urllib.parse import urlencode +from urllib.parse import parse_qs, urlencode, urlsplit from tests.reader.browser import test_reader_pdf_followup as support -from tests.performance.test_reader_performance import epub_with_many_chapters +from tests.reader.browser.test_reader_toc_navigation import chapter_body, chapter_manifest class ReaderTocLatencyTests(unittest.TestCase): setUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__) setUp = support.PdfFollowupTests.setUp - def open_toc_book(self): - self.page.route('**/api/reader-content**',lambda route:route.fulfill( - content_type='application/epub+zip',body=epub_with_many_chapters(), - headers={'Access-Control-Allow-Origin':'*'})) - self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict( - url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc-hint.epub',ext='epub'))) + def open_toc_book(self, held_chapters=None): + manifest = chapter_manifest(14) + for entry in manifest['toc']: + entry['fragment'] = f"chapter-{entry['chapter']}" + + def resource(route): + path = parse_qs(urlsplit(route.request.url).query)['path'][0] + filename = path.rsplit('/', 1)[-1] + if filename == 'chapter-manifest.json': + route.fulfill(json=manifest) + return + index = int(filename.removeprefix('chapter-').removesuffix('.xhtml')) + body = chapter_body(index) + if index == 10: + body = body.replace('', '

Book contents

', 1) + if held_chapters is not None and index in held_chapters: + held_chapters[index].append((route, body)) + else: + route.fulfill(content_type='text/html', body=body) + + self.page.route('**/api/reader-bucket-resource**', resource) + source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/' + + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json') + self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' + + urlencode(dict(url=source, ext='epub-chapters')), + wait_until='domcontentloaded') self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") self.page.wait_for_function("()=>document.querySelector('#history-panel').classList.contains('is-open')", timeout=2500) + def toc_link(self, chapter): + return self.page.locator(f'#toc-list [data-toc-index="{chapter - 1}"] .panel-item-main') + + def wait_for_chapter_landing(self, chapter): + self.page.wait_for_function('''chapter=>{ + const target=document.querySelector(`.reader-epub-chapter[data-chapter="${chapter}"] #chapter-${chapter}`); + return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top)<3; + }''', arg=chapter, timeout=1500) + def expose_toc(self): def instrument(route): response = route.fetch() @@ -171,51 +200,44 @@ class ReaderTocLatencyTests(unittest.TestCase): self.assertTrue(self.page.locator('#history-panel').evaluate('node=>node.hidden')) def test_unrelated_text_selection_does_not_disable_sidebar_navigation(self): - self.page.route('**/api/reader-content**',lambda route:route.fulfill( - content_type='application/epub+zip',body=epub_with_many_chapters(), - headers={'Access-Control-Allow-Origin':'*'})) - self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict( - url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc-selection.epub',ext='epub'))) - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") - for index,number in [(9,10),(4,5)]: - self.page.evaluate('''index=>{ - const range=document.createRange();range.selectNodeContents(document.querySelector('#title')); - getSelection().removeAllRanges();getSelection().addRange(range); - document.querySelectorAll('#toc-list .panel-item-main')[index].click(); - }''',index) - self.page.wait_for_function('''number=>{ - const a=document.querySelector('article[data-section="'+number+'"]'),target=a?.shadowRoot?.querySelector('#chapter-'+number); - return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3; - }''',arg=number,timeout=1500) + self.open_toc_book() + for current, chapter in ((1, 10), (10, 5)): + if self.page.locator('#history').get_attribute('aria-expanded') != 'true': + self.page.locator('#history').click() + selected = self.toc_link(chapter).evaluate('''(link, current)=>{ + const range=document.createRange(); + range.selectNodeContents(document.querySelector(`#chapter-${current}`)); + const selection=getSelection();selection.removeAllRanges();selection.addRange(range); + const selected=selection.toString(); + link.click(); + return selected; + }''', current) + self.assertTrue(selected) + self.wait_for_chapter_landing(chapter) def test_sidebar_and_book_links_do_not_wait_for_unrelated_prefetch(self): - self.page.route('**/api/reader-content**',lambda route:route.fulfill( - content_type='application/epub+zip',body=epub_with_many_chapters(), - headers={'Access-Control-Allow-Origin':'*'})) - self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict( - url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc-latency.epub',ext='epub'))) - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") - self.page.evaluate('''()=>{ - const sections=document.querySelector('foliate-view').book.sections.filter(s=>s.linear!=='no'); - for(const index of [9,11]){const original=sections[index].createDocument.bind(sections[index]); - sections[index].createDocument=()=>new Promise(resolve=>{ - (window.__heldNeighbors||=[]).push(()=>original().then(resolve));});} - document.querySelectorAll('#toc-list .panel-item-main')[9].click(); - }''') - self.page.wait_for_function('''()=>{ - const a=document.querySelector('article[data-section="10"]'),target=a?.shadowRoot?.querySelector('#chapter-10'); - return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3; - }''',timeout=1500) - self.page.evaluate('''()=>{ - const root=document.querySelector('article[data-section="10"]').shadowRoot; - const link=document.createElement('a');link.href='chapter-8.xhtml#chapter-8';link.textContent='Book contents'; - root.querySelector('#chapter-10').append(link);link.click(); - }''') - self.page.wait_for_function('''()=>{ - const a=document.querySelector('article[data-section="8"]'),target=a?.shadowRoot?.querySelector('#chapter-8'); - return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3; - }''',timeout=1500) - self.page.evaluate('()=>{for(const release of window.__heldNeighbors||[])release();}') + # Stall the opening prefetch, then the neighbors of the sidebar destination. + held = {chapter: [] for chapter in (2, 3, 9, 11)} + with ( + self.page.expect_request(lambda request: request.url.endswith('chapter-0002.xhtml'), timeout=1500), + self.page.expect_request(lambda request: request.url.endswith('chapter-0003.xhtml'), timeout=1500), + ): + self.open_toc_book(held) + with ( + self.page.expect_request(lambda request: request.url.endswith('chapter-0009.xhtml'), timeout=1500), + self.page.expect_request(lambda request: request.url.endswith('chapter-0011.xhtml'), timeout=1500), + ): + self.toc_link(10).click() + self.wait_for_chapter_landing(10) + self.page.get_by_role('link', name='Book contents', exact=True).click() + self.wait_for_chapter_landing(8) + + self.assertTrue(all(held.values()), 'both jumps must run with chapter responses withheld') + responses = [response for chapter in held.values() for response in chapter] + held.clear() + for route, body in responses: + route.fulfill(content_type='text/html', body=body) + self.page.locator('.reader-epub-chapter[data-chapter="9"]').wait_for(state='attached', timeout=1500) self.page.wait_for_timeout(250) self.assertLess(abs(self.page.locator('#chapter-8').evaluate( - "e=>e.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8")),3) + "e=>e.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top")), 3) diff --git a/tests/reader/browser/test_reader_ebook_flow.py b/tests/reader/browser/test_reader_ebook_flow.py index 5593971d0aff467af194aa2372411728cc56bcd4..d03cdb7ae8670cf78de29edc9e987a0e8ef5e133 100644 --- a/tests/reader/browser/test_reader_ebook_flow.py +++ b/tests/reader/browser/test_reader_ebook_flow.py @@ -1,11 +1,7 @@ -"""Shared ebook loading/navigation regressions; actual EPUB engine, bounded fixtures.""" -import io -import json +"""Shared chapter ebook loading and navigation regressions.""" import unittest -import zipfile from urllib.parse import urlencode, unquote from tests.reader.browser import test_reader_pdf_followup as support -from tests.performance.test_reader_performance import epub_with_many_chapters class EbookFlowTests(unittest.TestCase): @@ -53,105 +49,16 @@ class EbookFlowTests(unittest.TestCase): self.assertEqual(self.page.locator('.reader-error').count(), 0) def expose(self): - def instrument_foliate(route): - response = route.fetch() - needle = 'readerContext.foliateSectionLoader.refresh = refresh;' - script = response.text() - self.assertIn(needle, script) - route.fulfill(response=response, body=script.replace(needle, - needle + ' window.__nativeStats=()=>({active:scheduler.activeCount,pending:scheduler.pendingCount});')) - self.page.route('**/static/reader/formats/reader-foliate-format.mjs*', instrument_foliate) def instrument(route): response = route.fetch() - script=response.text() - route.fulfill(response=response, body=script+''' - window.__ebook={restore:restoreFoliateBookmarkPosition,capture:captureFoliateBookmarkPosition, - captureChapter:captureChapterPosition,seek:seekFoliateProgress, - begin:beginReaderNavigation,anchor:foliateScrollAnchors, - load:i=>foliateSectionLoader(i),jump:i=>navigateTocEntry(i-1), + route.fulfill(response=response, body=response.text() + ''' + window.__ebook={captureChapter:captureChapterPosition, chapter:i=>navigationState.tocEntries[i-1].activate(beginReaderNavigation()), progress:seekProgress,seekTask:()=>epubSeekPromise, - percent:readerProgressPercent,restoreProgress:restoreProgressState,save:saveProgress, - search:fullSearchFoliateMatches,searchGo:navigateFoliateSearchResult, - searchGeneration:()=>readerRuntime.currentGeneration('search'), - toc:activateFoliateTocEntry}; + percent:readerProgressPercent,restoreProgress:restoreProgressState,save:saveProgress}; ''') self.page.route('**/static/reader.js*', instrument) - def native(self, short=False, image=False): - with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters())) as archive: - files={name:archive.read(name) for name in archive.namelist()} - for name in files: - if name.endswith('.xhtml'): - text=files[name].decode() - if short:text=text.replace('height:1200px','height:20px') - if image:text=text.replace('','') - files[name]=text.encode() - stream=io.BytesIO() - with zipfile.ZipFile(stream,'w',zipfile.ZIP_DEFLATED) as archive: - for name,body in files.items():archive.writestr(name,body) - self.page.route('**/api/reader-content**',lambda route:route.fulfill(content_type='application/epub+zip',body=stream.getvalue(),headers={'Access-Control-Allow-Origin':'*'})) - self.expose() - self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/flow.epub',ext='epub')),wait_until='domcontentloaded') - - def test_native_supplement_navigation_bookmark_and_resources(self): - with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters(count=2))) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - files['OEBPS/content.opf'] = files['OEBPS/content.opf'].replace( - b'', b'' - ).replace(b'', b'') - files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace( - b'', b'
  • Supplement
  • ') - files['OEBPS/chapter-1.xhtml'] = files['OEBPS/chapter-1.xhtml'].replace( - b'', b'Note link') - files['OEBPS/extra.xhtml'] = b''' -

    Supplement target

    uniqueSupplementNeedle

    - Back - - - - ''' - packed = io.BytesIO() - with zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED) as archive: - for name, body in files.items(): archive.writestr(name, body) - self.page.route('**/api/reader-content**', lambda route: route.fulfill( - content_type='application/epub+zip', body=packed.getvalue(), headers={'Access-Control-Allow-Origin':'*'})) - self.expose() - self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict( - url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/supplement.epub', ext='epub'))) - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - self.page.get_by_role('link', name='Supplement', exact=True).wait_for() - self.assertEqual(self.page.locator('article[data-supplement]').count(), 0) - self.page.get_by_role('link', name='Supplement', exact=True).click() - extra = self.page.locator('article[data-supplement]') - extra.wait_for() - self.assertEqual(extra.locator('#note').text_content(), 'Supplement target') - self.assertIn('path=OEBPS%2Fimages%2Fpicture.png#view%20one', extra.locator('#safe').get_attribute('src')) - self.assertIsNone(extra.locator('#unsafe').get_attribute('src')) - self.assertIsNone(extra.locator('#badfragment').get_attribute('src')) - saved = self.page.evaluate('__ebook.capture()') - self.assertLess(saved['foliateSection'], 0) - extra.locator('#back').click() - self.page.wait_for_function("()=>!document.querySelector('article[data-supplement]')") - self.assertTrue(self.page.evaluate('p=>__ebook.restore(p,__ebook.begin())', saved)) - self.assertEqual(self.page.evaluate('__ebook.capture().foliateSection'), saved['foliateSection']) - self.assertEqual(self.page.locator('article[data-supplement]').count(), 1) - extra.locator('#back').click() - self.page.wait_for_function("()=>!document.querySelector('article[data-supplement]')") - result = self.page.evaluate("async()=> (await __ebook.search('uniqueSupplementNeedle',__ebook.searchGeneration()))[0]") - self.assertIsNotNone(result) - self.assertTrue(self.page.evaluate('r=>__ebook.searchGo(r,__ebook.begin())', result)) - self.assertEqual(self.page.locator('article[data-supplement] mark.full-search-highlight').count(), 1) - self.assertTrue(self.page.evaluate("async()=>{const book=document.querySelector('foliate-view').book;" - "const resolve=book.resolveHref.bind(book);book.resolveHref=async href=>{const t=await resolve('OEBPS/extra.xhtml#note');" - "return t&&{...t,anchor:()=>{throw Error('bad anchor')}}};" - "try{return await __ebook.toc({href:'extra.xhtml#%XX'},__ebook.begin());}" - "finally{book.resolveHref=resolve}}")) - self.page.locator('article[data-supplement] #back').click() - self.page.wait_for_function("()=>!document.querySelector('article[data-supplement]')") - self.page.locator('#note-link').click() - self.page.locator('article[data-supplement] #note').wait_for() - def test_ebook_prose_stays_in_paper_and_wide_blocks_scroll(self): body = '''

    Ebook layout

    @@ -162,20 +69,12 @@ class EbookFlowTests(unittest.TestCase):

    正文仍可阅读

    ''' % ('unbroken' * 55, '0123456789 ' * 50) - with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters(count=1))) as archive: - files = {name:archive.read(name) for name in archive.namelist()} - files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace(b'', body.encode() + b'') - packed = io.BytesIO() - with zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED) as archive: - for name, data in files.items(): archive.writestr(name, data) source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/' + 'a'*64 + '/1234567890abcdef/chapter-manifest.json' manifest = {'version':1,'kind':'epub-chapters','chapters':[{'index':1,'path':'chapters/chapter-0001.xhtml','bytes':len(body.encode())}]} - self.page.route('**/api/reader-content**', lambda route:route.fulfill(content_type='application/epub+zip', - body=packed.getvalue(),headers={'Access-Control-Allow-Origin':'*'})) self.page.route('**/api/reader-bucket-resource**', lambda route:route.fulfill(json=manifest) if 'chapter-manifest' in route.request.url else route.fulfill(content_type='text/html', body=body,headers={'Access-Control-Allow-Origin':'*'})) self.page.set_viewport_size({'width':320,'height':750}) - for mode, url in [('epub','https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/mobile.epub'), ('epub-chapters',source)]: + for mode, url in [('epub-chapters',source)]: with self.subTest(mode=mode): self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url=url, ext=mode))) self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") @@ -206,6 +105,40 @@ class EbookFlowTests(unittest.TestCase): self.assertEqual(self.page.locator('#wide-table caption').text_content(),'Table caption') self.assertEqual(self.page.locator('#wide-pre').text_content(),'0123456789 ' * 50) + def test_chapter_xhtml_packaged_css_cascade(self): + source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/' + + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json') + # The chapter renderer mounts the sanitized body, not the document head. + chapter = ''' + CSS chapter +

    CSS chapter

    + + +

    Base

    +

    Specific

    +

    Inline

    + ''' + manifest = {'version': 1, 'kind': 'epub-chapters', 'chapters': [ + {'index': 1, 'path': 'chapters/chapter-0001.xhtml', 'bytes': len(chapter.encode())}]} + self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(json=manifest) + if 'chapter-manifest.json' in route.request.url else route.fulfill( + content_type='application/xhtml+xml', body=chapter, headers={'Access-Control-Allow-Origin': '*'})) + # Dark mode deliberately overrides book colors; test their cascade in light mode. + self.page.add_init_script("localStorage.setItem('theme', 'light')") + self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' + urlencode( + dict(url=source, ext='epub-chapters'))) + self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready' && " + "document.documentElement.dataset.theme==='light'") + for element, color in [('css-base', 'rgb(70, 80, 90)'), + ('css-specific', 'rgb(40, 50, 60)'), + ('css-inline', 'rgb(100, 110, 120)')]: + with self.subTest(element=element): + node = self.page.locator('.reader-epub-chapter #' + element) + self.assertTrue(node.is_visible()) + style = node.evaluate('n => {const s = getComputedStyle(n); return [s.color, s.letterSpacing, s.wordSpacing]}') + self.assertEqual(style, [color, '2px', '4px']) + def test_ebook_first_content_does_not_import_pdf_hit_projection(self): requested = [] @@ -229,154 +162,9 @@ class EbookFlowTests(unittest.TestCase): heading = self.page.locator('.reader-epub-chapter h1') self.assertTrue(heading.is_visible()) self.assertEqual(heading.text_content(), 'Visible converted chapter') - self.page.route('**/api/reader-content**', lambda route: route.fulfill( - content_type='application/epub+zip', body=epub_with_many_chapters(count=2), - headers={'Access-Control-Allow-Origin': '*'})) - self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' + urlencode(dict( - url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/flow.epub', ext='epub'))) - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - self.assertTrue(self.page.locator('.reader-section-body').first.is_visible()) self.assertEqual(requested, []) - def test_native_first_text_does_not_wait_for_image_body(self): - held=[] - self.page.route('**/api/reader-resource?**',lambda route:held.append(route)) - self.native(image=True) - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'",timeout=1200) - self.assertTrue(self.page.locator('.reader-section-body').first.text_content()) - for route in held:route.abort() - - def test_native_first_chapter_reads_packaged_styles_in_parallel_and_keeps_cascade(self): - with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters(count=1))) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - links = ''.join(f'' for i in range(1, 5)) - sheets = ''.join(f'' for i in range(1, 5)) - files['OEBPS/content.opf'] = files['OEBPS/content.opf'].replace(b'', sheets.encode() + b'') - files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace(b'', f'{links}

    styles

    '.encode()) - for i in range(1, 5): - files[f'OEBPS/style-{i}.css'] = f'#cascade-probe {{letter-spacing:{i}px}}'.encode() - body = io.BytesIO() - with zipfile.ZipFile(body, 'w', zipfile.ZIP_DEFLATED) as archive: - for name, data in files.items(): archive.writestr(name, data) - - self.page.add_init_script('''(() => { - const fetchNative = window.fetch; - const blobNative = Response.prototype.blob; - window.__heldStyles = {}; - window.fetch = async (url, ...rest) => { - const response = await fetchNative(url, ...rest); - if (!String(url).startsWith('blob:') || !response.headers.get('content-type')?.includes('text/css')) return response; - const blob = await blobNative.call(response); - const marker = /letter-spacing:(\\d)px/.exec(await blob.text()); - if (!marker) return new Response(blob, {headers: response.headers}); - await new Promise(resolve => { window.__heldStyles[marker[1]] = resolve; }); - return new Response(blob, {headers: response.headers}); - }; - })()''') - self.page.route('**/api/reader-content**', lambda route: route.fulfill( - content_type='application/epub+zip', body=body.getvalue(), headers={'Access-Control-Allow-Origin':'*'})) - self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict( - url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/style-order.epub',ext='epub')), - wait_until='domcontentloaded') - self.page.wait_for_function("()=>['1','2','3'].every(key=>!!window.__heldStyles[key])") - self.assertFalse(self.page.evaluate("()=>!!window.__heldStyles['4']")) - # Finish out of order. The last sheet in document order must still win. - self.page.evaluate("()=>window.__heldStyles['3']()") - self.page.wait_for_function("()=>!!window.__heldStyles['4']") - self.page.evaluate("()=>{for(const key of ['4','2','1']) window.__heldStyles[key]();}") - self.page.wait_for_function('''()=>{ - const probe = document.querySelector('article[data-section="0"]')?.shadowRoot?.querySelector('#cascade-probe'); - return probe && getComputedStyle(probe).letterSpacing === '4px'; - }''') - - def test_native_restore_and_progress_do_not_wait_for_unrelated_neighbors(self): - self.native() - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") - self.page.evaluate('''()=>{ - const sections=document.querySelector('foliate-view').book.sections.filter(s=>s.linear!=='no'); - for(const index of [9,11])sections[index].createDocument=()=>new Promise(()=>{}); - window.__result=null; - __ebook.restore({foliateSection:10,foliateOffset:350}).then(value=>__result=value); - }''') - self.page.wait_for_function('()=>window.__result===true',timeout=1500) - self.page.evaluate('''()=>{window.__seekDone=false;__ebook.seek(100*8.2/15,__ebook.begin()).then(()=>__seekDone=true);}''') - self.page.wait_for_function('()=>window.__seekDone',timeout=1500) - - def test_native_position_reads_each_section_once_and_keeps_gap_fallback(self): - self.native() - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - result=self.page.evaluate('''()=>{ - const host=document.querySelector('.foliate-continuous'), orig=host.className; - host.classList.remove('foliate-continuous'); - const stream=document.createElement('div');stream.className='foliate-continuous';document.body.append(stream); - const top=document.querySelector('#viewport').getBoundingClientRect().top+8; - const rows=[0,1,2].map(i=>{ - const row=document.createElement('article');row.dataset.section=i;stream.append(row);return row; - }); - try { - return [[[-50,-10],[20,30],[45,70]], [[-30,8],[15,25],[35,80]], [[-90,-70],[-65,-35],[-30,-5]]].map(rects=>{ - const reads=[0,0,0]; - rows.forEach((row,i)=>{row.getBoundingClientRect=()=>{reads[i]++;return {top:top+rects[i][0],bottom:top+rects[i][1]}}}); - return [__ebook.capture(),reads]; - }); - } finally {stream.remove();host.className=orig;} - }''') - self.assertEqual([(v['foliateSection'],v['foliateOffset'],reads) for v,reads in result], - [(1,-20,[1,1,1]),(0,30,[1,0,0]),(2,30,[1,1,1])]) - - def test_native_jump_keeps_previous_chapter_reachable_and_position_stable(self): - self.native() - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") - self.page.evaluate('__ebook.jump(13)') - self.page.wait_for_function("()=>!!document.querySelector('article[data-section=\"12\"]:not(.foliate-section-placeholder)')",timeout=1500) - self.page.wait_for_timeout(200) - self.assertLess(abs(self.page.locator('#chapter-13').evaluate('n=>n.getBoundingClientRect().top-document.querySelector("#viewport").getBoundingClientRect().top-8')),3) - self.page.locator('#chapter-12').evaluate('n=>n.scrollIntoView()') - self.page.wait_for_timeout(250) - self.assertTrue(self.page.locator('#chapter-12').is_visible()) - - def test_superseded_native_jump_releases_slots_and_ignores_late_section(self): - self.native() - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") - self.page.evaluate('''()=>{ - const sections=document.querySelector('foliate-view').book.sections.filter(s=>s.linear!=='no'); - const original=sections[10].createDocument.bind(sections[10]); - sections[10].createDocument=()=>new Promise(resolve=>{window.__releaseOld=()=>original().then(resolve);}); - __ebook.jump(10); - }''') - self.page.wait_for_function('()=>!!window.__releaseOld') - self.page.evaluate('__ebook.jump(13)') - self.page.wait_for_function('''()=>{const n=document.querySelector('article[data-section="13"]')?.shadowRoot?.querySelector('#chapter-13'); - return n&&Math.abs(n.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3;}''',timeout=1500) - self.assertLessEqual(self.page.evaluate('__nativeStats().active'),3) - self.page.evaluate('__releaseOld()') - self.page.wait_for_timeout(250) - self.assertEqual(self.page.locator('article[data-section="10"]:not(.foliate-section-placeholder)').count(),0) - def test_native_short_chapters_do_not_recursively_decode_whole_book(self): - self.native(short=True) - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - self.page.wait_for_timeout(400) - self.assertLessEqual(self.page.locator('article[data-section]:not(.foliate-section-placeholder)').count(),9) - self.assertLessEqual(self.page.evaluate('__nativeStats().active'),3) - self.assertTrue(self.page.evaluate("!!document.querySelector('foliate-view').renderer")) - - def test_anchor_preserves_reading_line_when_previous_chapter_arrives_mid_scroll(self): - self.native() - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - result=self.page.evaluate('''()=>{ - const article=document.querySelector('article[data-section]'); - const root=article.shadowRoot.querySelector('.reader-section-body'); - root.innerHTML='

    Before

    Reading line

    After

    '; - const viewport=document.querySelector('#viewport'),line=root.querySelector('#line'); - viewport.scrollTop+=line.getBoundingClientRect().top-viewport.getBoundingClientRect().top-80; - viewport.dispatchEvent(new WheelEvent('wheel',{deltaY:-1})); - const before=line.getBoundingClientRect().top; - __ebook.anchor.preserve(()=>{const previous=document.createElement('div');previous.style.height='700px';article.before(previous);}); - return {before,after:line.getBoundingClientRect().top}; - }''') - self.assertAlmostEqual(result['before'],result['after'],delta=2) def test_converted_position_reads_each_chapter_once_and_preserves_identity(self): self.expose() diff --git a/tests/reader/browser/test_reader_format_pipeline.py b/tests/reader/browser/test_reader_format_pipeline.py index ac504f5f90c9613abc16f1689d383bbfcdecaa5d..985017bdb5d865e171e43f0fd50502b2d77a81e2 100644 --- a/tests/reader/browser/test_reader_format_pipeline.py +++ b/tests/reader/browser/test_reader_format_pipeline.py @@ -3,7 +3,6 @@ import unittest from urllib.parse import urlencode from tests.reader.browser import test_reader_pdf_followup as support -from tests.performance.test_reader_performance import epub_with_navigation class ReaderFormatPipelineTests(unittest.TestCase): @@ -26,13 +25,12 @@ class ReaderFormatPipelineTests(unittest.TestCase): 'marked':'window.marked={parse:t=>"

    Heading

    "+t+"

    "};', 'purify':'window.DOMPurify={addHook(){},removeHook(){},sanitize:(t,o)=>{if(!o?.RETURN_DOM_FRAGMENT)return t;const n=document.createElement("template");n.innerHTML=t;return n.content;}};', } - documents=[('md',b'Markdown body','text/plain'),('html',b'

    Heading

    HTML body

    ','text/html'), - ('epub',epub_with_navigation(),'application/epub+zip')] + documents=[('md',b'Markdown body','text/plain'),('html',b'

    Heading

    HTML body

    ','text/html')] for ext,body,mime in documents: with self.subTest(format=ext): held=[] def engine(route):held.append(route) - pattern='**/static/foliate-reader/view.js*' if ext=='epub' else '**/static/vendor/*.js' + pattern='**/static/vendor/*.js' self.page.route(pattern,engine) self.page.route('**/api/reader-content**',lambda route,_request,body=body,mime=mime:route.fulfill( content_type=mime,body=body,headers={'Access-Control-Allow-Origin':'*'})) @@ -43,13 +41,11 @@ class ReaderFormatPipelineTests(unittest.TestCase): self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'),'ready') self.page.unroute(pattern,engine) for route in held: - if ext=='epub':route.continue_() - else: - name=next(key for key in engines if '/'+key+'.' in route.request.url) - route.fulfill(content_type='text/javascript',body=engines[name]) + name=next(key for key in engines if '/'+key+'.' in route.request.url) + route.fulfill(content_type='text/javascript',body=engines[name]) self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") text=(self.page.frame_locator('.html-frame').locator('body').inner_text() if ext=='html' else - self.page.locator('.reader-section-body').first.inner_text() if ext=='epub' else self.page.locator('#content').inner_text()) + self.page.locator('#content').inner_text()) self.assertTrue(text.strip()) def test_swf_body_finishes_while_ruffle_is_held(self): diff --git a/tests/reader/browser/test_reader_refactor.py b/tests/reader/browser/test_reader_refactor.py index d940229d6b547a38d9b8ce456a34e44f2b570ec3..37bd38e2598ba741d1e92141682e724fc030eb5d 100644 --- a/tests/reader/browser/test_reader_refactor.py +++ b/tests/reader/browser/test_reader_refactor.py @@ -9,7 +9,6 @@ import os import time import unittest import urllib.parse -import zipfile import wave from tests.performance import test_reader_performance as support @@ -144,8 +143,6 @@ class ReaderRefactorTest(unittest.TestCase): [chapter](chapter%20one.md) -[book](book.epub) - [fragment](chapter%20one.md#section) [self](index.md#local) @@ -181,8 +178,6 @@ class ReaderRefactorTest(unittest.TestCase): route.fulfill(content_type='text/markdown', body=index) elif path.endswith('/books/chapter one.md'): route.fulfill(content_type='text/markdown', body=chapter) - elif path.endswith('/books/book.epub'): - route.fulfill(content_type='application/epub+zip', body=support.minimal_epub()) else: route.fulfill(status=404, body='missing') self.page.route('**/api/reader-content**', serve) @@ -194,13 +189,12 @@ class ReaderRefactorTest(unittest.TestCase): base = self.markdown_link_fixture() self.open(self.reader_url('md', name='books/index')) article = self.page.locator('.reader-markdown') - for label, filename, ext in [('chapter', 'chapter one.md', 'md'), ('book', 'book.epub', 'epub')]: - href = article.get_by_role('link', name=label, exact=True).get_attribute('href') - target = urllib.parse.urlsplit(href) - args = urllib.parse.parse_qs(target.query) - self.assertTrue(target.path.endswith('/static/reader.html')) - self.assertEqual(urllib.parse.unquote(args['url'][0]), base + filename) - self.assertEqual(args['ext'][0], ext) + href = article.get_by_role('link', name='chapter', exact=True).get_attribute('href') + target = urllib.parse.urlsplit(href) + args = urllib.parse.parse_qs(target.query) + self.assertTrue(target.path.endswith('/static/reader.html')) + self.assertEqual(urllib.parse.unquote(args['url'][0]), base + 'chapter one.md') + self.assertEqual(args['ext'][0], 'md') self.assertEqual(article.get_by_role('link', name='local', exact=True).get_attribute('href'), '#local') self.assertEqual(article.get_by_role('link', name='self', exact=True).get_attribute('href'), '#local') self.assertEqual(article.get_by_role('link', name='outside').get_attribute('href'), 'https://example.org/article.md') @@ -254,17 +248,6 @@ class ReaderRefactorTest(unittest.TestCase): href = self.page.locator('.reader-markdown').get_by_role('link', name='chapter', exact=True).get_attribute('href') self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(href).query)['url'][0]), base + 'chapter one.md') - def test_markdown_epub_link_opens_book_without_downloading(self): - base = self.markdown_link_fixture() - self.open(self.reader_url('md', name='books/index')) - downloads = [] - self.page.on('download', lambda download: downloads.append(download)) - self.page.locator('.reader-markdown').get_by_role('link', name='book', exact=True).click() - self.page.wait_for_url('**/reader.html?*ext=epub*') - self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") - self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)['url'][0]), base + 'book.epub') - self.assertEqual(downloads, []) - def test_markdown_dataset_link_in_search_overlay_uses_parent_navigation(self): self.markdown_link_fixture() reader = self.reader_url('md', name='books/index') @@ -738,22 +721,6 @@ class ReaderRefactorTest(unittest.TestCase): self.assertEqual(self.page.evaluate('window.__imageWaitProbe()'), [[0, 1, 'eager'], [0, 0, 'eager'], [0, 0, 'eager'], 'AbortError', 0]) - def test_epub_lazy_image_loads_while_section_is_prepared_off_dom(self): - with zipfile.ZipFile(io.BytesIO(support.minimal_epub())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - files['OEBPS/chapter.xhtml'] = files['OEBPS/chapter.xhtml'].replace( - b'', b'Chapter image') - files['OEBPS/picture.webp'] = support.IMAGE_FIXTURES['webp'][1] - images = [] - self.page.route('**/api/reader-resource?**', lambda route: ( - images.append(route.request.url), route.fulfill(content_type='image/webp', body=files['OEBPS/picture.webp']))) - self.serve(support.zip_bytes(files), 'application/epub+zip') - self.open(self.reader_url('epub')) - image = self.page.locator('article[data-section] img').first - self.assertEqual(image.evaluate('node => node.loading'), 'eager') - self.assertGreater(image.evaluate('node => node.naturalWidth'), 0) - self.assertEqual(len(images), 1) - def test_spreadsheet_cells_take_first_viewport_while_images_are_pending(self): # Delay only the post-frame image settlement. The sanitized HTML has # already loaded, so this distinguishes first paint from restore-ready. @@ -901,25 +868,6 @@ class ReaderRefactorTest(unittest.TestCase): self.page.locator('.reader-epub-chapter[data-chapter="6"]').wait_for(state="attached") self.assertNotIn(1, requested) - def test_saved_foliate_builds_target_section_first(self): - store = support.STORE_SCRIPT.replace( - "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),", - "get: () => Promise.resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9}),", - ) - self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(content_type="text/javascript", body=store)) - def instrument(route): - response = route.fetch() - script = response.text() - marker = "async function createFoliateSection(section, index, signal, priority) {" - self.assertEqual(script.count(marker), 1, "Foliate section instrumentation boundary changed") - body = script.replace(marker, marker + " (window.__openedSections ||= []).push(index);") - route.fulfill(response=response, body=body) - self.page.route("**/static/reader/formats/reader-foliate-format.mjs*", instrument) - self.serve(support.epub_with_many_chapters(), "application/epub+zip") - self.open(self.reader_url("epub")) - self.assertEqual(self.page.evaluate("window.__openedSections[0]"), 10) - self.assertTrue(self.page.locator('.foliate-continuous article[data-section="10"]').is_visible()) - def test_djvu_recovers_ocr_text_and_searches_valid_index(self): state = install_native_djvu(self.page, self.origin, ocr=True, fail_page_once=True) self.open(state["url"]) @@ -1395,271 +1343,6 @@ class ReaderRefactorTest(unittest.TestCase): self.assertEqual(self.page.locator("#full-search-page").input_value(), "3") self.assertEqual(self.page.locator("#full-search-status").text_content(), "180 个结果") - def test_pending_foliate_result_does_not_close_reopened_search(self): - self.serve(support.epub_with_many_chapters(3), "application/epub+zip") - self.open(self.reader_url("epub")) - self.search("正文") - self.page.evaluate("""() => { - const view = document.querySelector('foliate-view'); - const original = view.resolveNavigation.bind(view); - view.resolveNavigation = cfi => new Promise(resolve => { - window.__releaseSearchNavigation = () => resolve(original(cfi)); - }); - }""") - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => !!window.__releaseSearchNavigation") - self.page.locator("#history").click() - self.page.locator("#history").click() - self.page.locator("#full-search-input").focus() - self.page.evaluate("window.__releaseSearchNavigation()") - self.page.locator(".foliate-continuous mark.full-search-highlight").first.wait_for() - self.assertTrue(self.page.locator("#full-search-input").is_visible()) - self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.classList.contains('is-open')")) - - def test_unresolvable_foliate_result_keeps_search_open_for_retry(self): - self.serve(support.epub_with_many_chapters(3), "application/epub+zip") - self.open(self.reader_url("epub")) - self.search("正文") - self.page.evaluate("""() => { - const view = document.querySelector('foliate-view'); - window.__resolveSearchResult = view.resolveNavigation.bind(view); - view.resolveNavigation = async () => null; - }""") - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '搜索结果定位失败,请重试'") - self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.classList.contains('is-open')")) - self.assertEqual(self.page.locator(".foliate-continuous mark.full-search-highlight").count(), 0) - self.page.evaluate("document.querySelector('foliate-view').resolveNavigation = window.__resolveSearchResult") - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')") - self.assertEqual(self.page.locator("#full-search-status").text_content(), "3 个结果") - self.assertEqual(self.page.locator(".foliate-continuous mark.full-search-highlight").count(), 1) - - def test_foliate_navigation_exception_reports_failure_and_retries(self): - self.serve(support.epub_with_many_chapters(3), "application/epub+zip") - self.open(self.reader_url("epub")) - self.search("正文") - self.page.evaluate("""() => { - const view = document.querySelector('foliate-view'); - const original = view.resolveNavigation.bind(view); - view.resolveNavigation = async cfi => { - view.resolveNavigation = original; - throw new Error('temporary navigation failure'); - }; - }""") - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '搜索结果定位失败,请重试'") - self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.classList.contains('is-open')")) - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')") - self.assertEqual(self.page.locator("#full-search-status").text_content(), "3 个结果") - - def test_stale_foliate_fallback_cannot_highlight_after_navigation(self): - def hold_fallback(route): - response = route.fetch() - needle = ("const nodes = cached ? [] : await fullSearchTextNodes(" - "root, generation, Infinity, null, collect, respectBlocks);") - script = response.text() - self.assertIn(needle, script) - script = script.replace(needle, """if (occurrence !== null && !window.__fallbackHeld) { - window.__fallbackHeld = true; - await new Promise(resolve => { window.__releaseFallback = resolve; }); - } """ + needle) - route.fulfill(response=response, body=script) - def finish_fallback(route): - response = route.fetch() - route.fulfill(response=response, body=response.text().replace( - "target = matches[0]?.target;", "target = matches[0]?.target; window.__fallbackDone = true;")) - self.page.route("**/static/reader/search/reader-dom-search.mjs*", hold_fallback) - self.page.route("**/static/reader/search/reader-search-backends.mjs*", finish_fallback) - self.serve(support.epub_with_many_chapters(3), "application/epub+zip") - self.open(self.reader_url("epub")) - self.search("正文") - self.page.evaluate("""() => { - const view = document.querySelector('foliate-view'); - const original = view.resolveNavigation.bind(view); - view.resolveNavigation = async cfi => ({ ...(await original(cfi)), anchor: null }); - }""") - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => !!window.__releaseFallback") - self.page.evaluate("document.querySelector('#viewport').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))") - self.page.evaluate("window.__releaseFallback()") - self.page.wait_for_function("() => !!window.__fallbackDone") - self.assertEqual(self.page.locator(".foliate-continuous mark.full-search-highlight").count(), 0) - - def test_foliate_search_reuses_rows_and_bounds_visited_pages(self): - with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters(6))) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - for number in range(1, 7): - files[f'OEBPS/chapter-{number}.xhtml'] = ( - '' + - ''.join(f'

    needle {number}-{hit}

    ' for hit in range(100)) + - '').encode() - self.serve(support.zip_bytes(files), "application/epub+zip") - self.open(self.reader_url("epub")) - self.page.evaluate("""() => { - window.__searchProbe = {rows: 0, calls: 0}; - const view = document.querySelector('foliate-view'), search = view.search.bind(view); - view.search = (...args) => { __searchProbe.calls++; return search(...args); }; - new MutationObserver(records => { - for (const record of records) __searchProbe.rows += record.addedNodes.length; - }).observe(document.querySelector('#full-search-results'), {childList: true}); - }""") - self.search("needle") - self.assertEqual(self.page.locator("#full-search-status").text_content(), "600 个结果") - self.assertEqual(self.page.evaluate("__searchProbe.rows"), 50) - - def jump(number): - self.page.locator("#full-search-page").fill(str(number)) - self.page.locator("#full-search-page").dispatch_event("change") - self.page.wait_for_function("rank => document.querySelector('.full-search-rank')?.textContent === rank", - arg=f"{(number - 1) * 50 + 1}.") - return self.page.locator(".full-search-result").all_text_contents() - - original = jump(2) - jump(3) - before = self.page.evaluate("__searchProbe.calls") - self.assertEqual(jump(2), original) - self.assertEqual(self.page.evaluate("__searchProbe.calls"), before) - for number in (4, 5, 6, 7): - jump(number) - before = self.page.evaluate("__searchProbe.calls") - self.assertEqual(jump(2), original) - self.assertGreater(self.page.evaluate("__searchProbe.calls"), before) - self.page.locator("#full-search-input").fill("absent") - self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '未找到正文匹配'") - self.page.locator("#full-search-input").fill("needle") - self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '600 个结果'") - before = self.page.evaluate("__searchProbe.calls") - self.assertEqual(jump(2), original) - self.assertGreater(self.page.evaluate("__searchProbe.calls"), before) - - def test_foliate_counting_materializes_only_requested_results(self): - for name, needle, probe in ( - ("search.js", "const makeExcerpt = (strs, { startIndex, startOffset, endIndex, endOffset }) => {", "__excerptCalls"), - ("text-walker.js", "const range = document.createRange()", "__rangeCalls"), - ): - def instrument(route, _request, needle=needle, probe=probe): - response = route.fetch() - self.assertIn(needle, response.text()) - route.fulfill(response=response, body=response.text().replace(needle, - needle + f"; window.{probe} = (window.{probe} || 0) + 1;")) - self.page.route(f"**/foliate-reader/{name}", instrument) - with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters(1))) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - files['OEBPS/chapter-1.xhtml'] = ( - '' + - ''.join(f'

    needle {hit}

    ' for hit in range(1000)) + '' - ).encode() - self.serve(support.zip_bytes(files), "application/epub+zip") - self.open(self.reader_url("epub")) - self.page.evaluate("window.__excerptCalls = window.__rangeCalls = 0") - self.search("needle") - self.assertEqual(self.page.locator("#full-search-status").text_content(), "1000 个结果") - self.assertEqual(self.page.evaluate("[window.__excerptCalls, window.__rangeCalls]"), [50, 50]) - self.page.locator("#full-search-page").fill("20") - self.page.locator("#full-search-page").dispatch_event("change") - self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '951.'") - self.assertEqual(self.page.evaluate("[window.__excerptCalls, window.__rangeCalls]"), [100, 100]) - self.assertIn("999", self.page.locator(".full-search-result").last.text_content()) - self.page.locator(".full-search-result").last.click() - self.page.wait_for_function("() => [...document.querySelectorAll('article[data-section]')].some(node => node.shadowRoot?.querySelector('mark')?.parentElement.textContent === 'needle 999')") - - def test_foliate_excerpt_preserves_all_inline_match_nodes(self): - self.serve("Text") - self.open(self.reader_url()) - base = urllib.parse.urlsplit(self.reader_url()).path.rsplit('/', 1)[0] - result = self.page.evaluate("""async base => { - const {search} = await import(base + '/foliate-reader/search.js'); - return ['variant', 'base'].map(sensitivity => { - const result = [...search(['before ne', 'e', 'dle after'], 'needle', - {sensitivity, granularity: 'grapheme'})][0]; - return result.excerpt; - }).concat([...search(['ne', 'ed', 'ne'], 'needne', - {sensitivity: 'base', granularity: 'grapheme'})][0].excerpt); - }""", base) - self.assertEqual(result, [{"pre": "before ", "match": "needle", "post": " after"}] * 2 + - [{"pre": "", "match": "needne", "post": ""}]) - - def test_foliate_many_hits_paginate_and_cancel(self): - with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters(3))) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - for number in (1, 2, 3): - files[f'OEBPS/chapter-{number}.xhtml'] = ( - '' + - ''.join(f'

    needle {number}-{hit}

    ' for hit in range(70)) + - '' - ).encode() - self.serve(support.zip_bytes(files), "application/epub+zip") - self.open(self.reader_url("epub")) - self.search("needle") - self.assertEqual(self.page.locator("#full-search-status").text_content(), "210 个结果") - self.assertEqual(self.page.locator(".full-search-result").count(), 50) - self.assertTrue(self.page.locator("#full-search-cancel").is_hidden()) - self.page.evaluate("""() => { - window.__cancelPagingChanges = []; - const cancel = document.querySelector('#full-search-cancel'); - new MutationObserver(() => { - __cancelPagingChanges.push(cancel.hidden); - }).observe(document.querySelector('#full-search-cancel'), { - attributes: true, attributeFilter: ['hidden'] - }); - }""") - self.page.evaluate("""() => { - const status = document.querySelector('#full-search-status'); - window.__pagingStatuses = [status.textContent]; - window.__pagingObserver = new MutationObserver(records => { - for (const record of records) { - for (const node of record.removedNodes) window.__pagingStatuses.push(node.textContent); - } - window.__pagingStatuses.push(status.textContent); - }); - window.__pagingObserver.observe(status, {childList: true}); - const view = document.querySelector('foliate-view'); - const original = view.search.bind(view); - view.search = async function* (options) { - if (options.index != null && !window.__heldResultPage) { - window.__heldResultPage = true; - await new Promise(resolve => { window.__releaseResultPage = resolve; }); - } - yield* original(options); - }; - }""") - self.page.locator("#full-search-page-next").click() - self.page.wait_for_function("() => !!window.__releaseResultPage") - self.assertTrue(self.page.locator("#full-search-cancel").is_hidden()) - self.page.evaluate("window.__releaseResultPage()") - self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '51.'") - self.page.locator("#full-search-page").fill("3") - self.page.locator("#full-search-page").dispatch_event("change") - self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '3' && document.querySelector('.full-search-result .full-search-rank')?.textContent === '101.'") - self.assertIn("needle 2-30", self.page.locator(".full-search-result").first.text_content()) - self.assertTrue(self.page.locator("#full-search-cancel").is_hidden()) - self.assertNotIn(False, self.page.evaluate("__cancelPagingChanges")) - statuses = self.page.evaluate("() => { window.__pagingObserver.disconnect(); return window.__pagingStatuses; }") - self.assertEqual(set(statuses), {"210 个结果"}) - self.page.locator(".full-search-result").first.click() - self.page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')") - self.page.locator("#history").click() - self.page.wait_for_function("() => document.querySelector('#history-panel').classList.contains('is-open') && !document.querySelector('#full-search-view').hidden") - self.assertEqual(self.page.locator("#full-search-page").input_value(), "3") - self.page.locator("#full-search-input").fill("missing") - self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '未找到正文匹配'") - self.page.evaluate("""() => { - const sections = document.querySelector('foliate-view').book.sections; - for (const section of sections) if (section.createDocument) { - const original = section.createDocument.bind(section); - section.createDocument = async () => { await new Promise(resolve => setTimeout(resolve, 200)); return original(); }; - } - }""") - self.page.locator("#full-search-input").fill("needle") - self.page.locator("#full-search-cancel").click() - self.page.wait_for_timeout(700) - self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消") - self.assertEqual(self.page.locator(".full-search-result").count(), 0) - self.page.locator("#full-search-retry").click() - self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '210 个结果'") - def test_pdf_with_unavailable_ocr_index_does_not_fall_back(self): self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill( content_type="text/javascript", body=support.PDF_MODULE)) @@ -2820,75 +2503,6 @@ class ReaderRefactorTest(unittest.TestCase): self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") self.assertEqual(self.page.locator('.reader-text').text_content(), text) - def expose_toc_probe(self): - def instrument(route): - response = route.fetch() - route.fulfill(response=response, body=response.text() + ''' - window.__startTocProbe = () => { - const sourceSections = [{linear:'yes'}, {linear:'no'}, {linear:'yes'}]; - const visibleSections = [sourceSections[0], sourceSections[2], sourceSections[0]]; - const probe = window.__tocProbe = {calls:0, active:0, peak:0, scans:0, held:[]}; - visibleSections.indexOf = section => {probe.scans++; return Array.prototype.indexOf.call(visibleSections, section);}; - let hold = true; - const children = Array.from({length:85}, (_, n) => ({label:'Chapter ' + n, href:'chapter-' + n + '#anchor%20' + n})); - children.push({label:'Invalid', href:'invalid'}); - const view = {book:{sections:sourceSections, toc:[{label:'Volume', subitems:children}], - async resolveHref(href) { - probe.calls++; probe.active++; probe.peak = Math.max(probe.peak, probe.active); - try { - if (hold) await new Promise(resolve => probe.held.push(resolve)); - if (probe.busy) { - const deadline = performance.now() + 1; - while (performance.now() < deadline) {} - } - if (href === 'invalid') throw Error('bad href'); - const number = Number(href.match(/chapter-(\\d+)/)[1]); - return {index:number % 3, anchor:() => number}; - } finally {probe.active--;} - }}, goTo(href) {probe.navigation = href;}}; - probe.release = () => {hold = false; for (const resolve of probe.held.splice(0)) resolve();}; - probe.promise = foliateTocEntries(view, visibleSections).then(entries => { - entries.find(e => e.href === 'chapter-84#anchor%2084').activate(); - probe.entries = entries.map(e => ({label:e.label, section:e.sectionIndex, fragment:e.fragment, - anchor:typeof e.anchor === 'function' ? e.anchor() : null})); - }, error => {probe.error = error.name;}); - }; - ''') - self.page.route('**/static/reader.js*', instrument) - self.serve('TOC probe') - self.open(self.reader_url()) - self.page.evaluate('window.__startTocProbe()') - - def test_foliate_toc_bounds_resolution_and_keeps_every_entry_in_order(self): - self.expose_toc_probe() - self.page.wait_for_function('() => window.__tocProbe.calls >= 8') - self.assertEqual(self.page.evaluate('__tocProbe.calls'), 8) - self.page.evaluate('''__tocProbe.busy = true; __tocProbe.ticks = []; - const timer = setInterval(() => __tocProbe.ticks.push(__tocProbe.calls), 0); - __tocProbe.promise.finally(() => clearInterval(timer)); __tocProbe.release();''') - self.page.evaluate('__tocProbe.promise') - entries = self.page.evaluate('__tocProbe.entries') - self.assertEqual(entries[0], {'label':'Volume', 'section':-1, 'fragment':'', 'anchor':None}) - # The non-linear section at spine index 1 is a real destination: Foliate - # addresses supplements by -spine_index - 1, not by their visible index. - self.assertEqual(entries[1:-1], [dict(label=f'Chapter {n}', section=(0, -2, 1)[n % 3], - fragment=f'anchor {n}', anchor=n) for n in range(85)]) - self.assertEqual(entries[-1], {'label':'Invalid', 'section':-1, 'fragment':'', 'anchor':None}) - self.assertEqual(self.page.evaluate('[__tocProbe.peak, __tocProbe.scans, __tocProbe.calls]'), [8, 0, 86]) - self.assertGreaterEqual(len(self.page.evaluate('__tocProbe.ticks')), 2) - self.assertEqual(self.page.evaluate('__tocProbe.navigation'), 'chapter-84#anchor%2084') - - def test_foliate_toc_disposal_stops_queued_resolution_and_late_publication(self): - self.expose_toc_probe() - self.page.wait_for_function('() => window.__tocProbe.calls >= 8') - self.page.evaluate("window.dispatchEvent(new Event('pagehide'))") - self.page.wait_for_function("() => window.__tocProbe.error === 'AbortError'") - self.assertEqual(self.page.evaluate('__tocProbe.calls'), 8) - self.page.evaluate('__tocProbe.release()') - self.page.wait_for_function('() => __tocProbe.active === 0') - self.assertFalse(self.page.evaluate('!!__tocProbe.entries')) - self.assertEqual(self.page.evaluate('__tocProbe.calls'), 8) - def test_text_search_publishes_partial_results_before_full_scan(self): self.page.add_init_script("""const native = window.setTimeout.bind(window); window.setTimeout = (fn, ms, ...args) => native(fn, ms === 0 ? 20 : ms, ...args);""") @@ -3182,25 +2796,6 @@ class ReaderRefactorTest(unittest.TestCase): }''') self.assertEqual(result, [dict(equal=True, unsafe=False, remote=False, styles=False)] * 9) - def test_epub_svg_xlink_control_whitespace_cannot_execute_in_reader_context(self): - with zipfile.ZipFile(io.BytesIO(support.minimal_epub())) as archive: - files = {item.filename: archive.read(item.filename) for item in archive.infolist()} - files["OEBPS/chapter.xhtml"] = b''' - - - safe label - - - ''' - body = support.zip_bytes({name: value for name, value in files.items() if name != "mimetype"}, - ("mimetype", "application/epub+zip")) - self.serve(body, "application/epub+zip") - self.open(self.reader_url("epub", name="svg-xlink-security")) - probe = self.page.locator("article[data-section] #probe") - self.assertEqual(probe.get_attribute("xlink:href"), None) - probe.click() - self.assertFalse(self.page.evaluate("() => window.__readerSecurityMarker === 17")) - def test_back_tapped_before_reader_module_binds_still_exits(self): held = [] self.page.route("**/static/reader.js*", lambda route: held.append(route)) @@ -3218,32 +2813,6 @@ class ReaderRefactorTest(unittest.TestCase): held.pop(0).continue_() self.page.wait_for_url(landing, timeout=8000) - def test_epub_prefixed_xlink_and_smil_href_cannot_execute_in_reader_context(self): - with zipfile.ZipFile(io.BytesIO(support.minimal_epub())) as archive: - files = {item.filename: archive.read(item.filename) for item in archive.infolist()} - files["OEBPS/chapter.xhtml"] = b''' - - - prefixed label - - - - animated label - - - ''' - body = support.zip_bytes({name: value for name, value in files.items() if name != "mimetype"}, - ("mimetype", "application/epub+zip")) - self.serve(body, "application/epub+zip") - self.open(self.reader_url("epub", name="svg-prefixed-xlink-security")) - probe = self.page.locator("article[data-section] #probe") - self.assertIsNone(probe.evaluate("n => n.getAttributeNS('http://www.w3.org/1999/xlink', 'href')")) - self.assertEqual(self.page.locator("article[data-section] #animated set").count(), 0) - probe.click() - self.page.locator("article[data-section] #animated").click() - self.page.wait_for_timeout(200) - self.assertIsNone(self.page.evaluate("() => window.__readerSecurityMarker ?? null")) - def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self): dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8" "/x8AAwMB/6XWbqkAAAAASUVORK5CYII=") @@ -3279,41 +2848,6 @@ class ReaderRefactorTest(unittest.TestCase): self.assertEqual(result, {"policy": True, "violations": ["img-src"]}) self.assertNotIn("https://img.remote.test/a.png", remote) - def test_epub_css_cannot_load_remote_references_but_keeps_packaged_styles(self): - css = ("@import url(https://css.remote.test/a.css);\n" - "@import '\\68ttps://css.remote.test/b.css';\n" - "p.linked { letter-spacing: 3px; background-image: url(https://img.remote.test/a.png); }\n" - "p.escaped { background-image: \\75rl(//img.remote.test/b.png); }\n" - "p.set { background-image: image-set('https://img.remote.test/c.png' 1x); }\n" - "p.local { background-image: url(dot.png); }\n") - dot = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/6XWbqkAAAAASUVORK5CYII=") - body = support.zip_bytes({ - "META-INF/container.xml": '', - "OEBPS/content.opf": 'css-securityCSSen', - "OEBPS/style.css": css, - "OEBPS/dot.png": dot, - "OEBPS/chapter.xhtml": 'CSS

    linked

    escaped

    set

    local

    inline

    attr

    ', - }, ("mimetype", "application/epub+zip")) - remote = [] - self.page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None) - self.serve(body, "application/epub+zip") - self.open(self.reader_url("epub", name="css-security")) - self.page.wait_for_function("""() => { - const root = document.querySelector('article[data-section]')?.shadowRoot; - const p = root?.querySelector('p.linked'); - return p && getComputedStyle(p).letterSpacing === '3px'; - }""") - styles = self.page.evaluate("""() => { - const root = document.querySelector('article[data-section]').shadowRoot; - return Object.fromEntries([...root.querySelectorAll('p')].map(p => - [p.className, getComputedStyle(p).backgroundImage])); - }""") - for name in ("linked", "escaped", "set", "inline", "attr"): - self.assertEqual(styles[name], "none", name) - self.assertRegex(styles["local"], r"^url\(\"blob:") - self.page.wait_for_timeout(300) - self.assertEqual(remote, []) - def frame_host_reader(self, overlay=False, cross_origin=False): # The Reader must decide by its real host whether parent messages are handled. reader = self.reader_url(name="framed", path="Test/docs") @@ -3394,6 +2928,64 @@ class ReaderRefactorTest(unittest.TestCase): str(theme == "dark").lower()) page.close() + def open_security_chapter(self, chapter): + prefix = "chapters/ebook/epub/" + "e" * 64 + "/" + "f" * 16 + "/" + manifest_path = prefix + "chapter-manifest.json" + chapter_path = "chapters/chapter-0001.xhtml" + manifest = {"version": 1, "kind": "epub-chapters", "chapters": [ + {"index": 1, "path": chapter_path, "bytes": len(chapter), + "sha256": hashlib.sha256(chapter).hexdigest()}]} + + def bucket(route): + path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0] + if path == manifest_path: + route.fulfill(json=manifest) + elif path == prefix + chapter_path: + route.fulfill(content_type="application/xhtml+xml", body=chapter) + else: + route.fulfill(status=404) + + self.page.route("**/api/reader-bucket-resource?**", bucket) + source = ("https://voiceofml-search.hf.space/api/reader-bucket-resource?" + + urllib.parse.urlencode({"path": manifest_path})) + self.open(self.reader_url("epub-chapters", url=source)) + return self.page.locator(".reader-epub-chapter") + + def test_chapter_svg_xlink_control_whitespace_cannot_execute_in_reader_context(self): + chapter = b''' + + + safe label + + + ''' + chapter_root = self.open_security_chapter(chapter) + probe = chapter_root.locator("#probe") + self.assertEqual(probe.get_attribute("xlink:href"), None) + probe.click() + self.assertFalse(self.page.evaluate("() => window.__readerSecurityMarker === 17")) + + def test_chapter_prefixed_xlink_and_smil_href_cannot_execute_in_reader_context(self): + chapter = b''' + + + prefixed label + + + + animated label + + + ''' + chapter_root = self.open_security_chapter(chapter) + probe = chapter_root.locator("#probe") + self.assertIsNone(probe.evaluate("n => n.getAttributeNS('http://www.w3.org/1999/xlink', 'href')")) + self.assertEqual(chapter_root.locator("#animated set").count(), 0) + probe.click() + chapter_root.locator("#animated").click() + self.page.wait_for_timeout(200) + self.assertIsNone(self.page.evaluate("() => window.__readerSecurityMarker ?? null")) + def test_epub_html_and_svg_references_cannot_load_remote_resources(self): vectors = ('

    a

    ' '

    b

    ' @@ -3407,47 +2999,13 @@ class ReaderRefactorTest(unittest.TestCase): '

    kept text

    ') chapter = ('Refs' + vectors + '') - book = support.zip_bytes({ - "META-INF/container.xml": '', - "OEBPS/content.opf": 'refsRefsen', - "OEBPS/c.xhtml": chapter, - }, ("mimetype", "application/epub+zip")) - prefix = "chapters/ebook/epub/" + "e" * 64 + "/" + "f" * 16 + "/" - manifest = {"version": 1, "kind": "epub-chapters", "chapters": [ - {"index": 1, "path": "chapters/chapter-0001.xhtml", "title": "Refs", - "bytes": len(chapter.encode()), "sha256": hashlib.sha256(chapter.encode()).hexdigest()}]} - def bucket(route): - path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0] - if path == prefix + "chapter-manifest.json": - route.fulfill(content_type="application/json", body=json.dumps(manifest)) - elif path == prefix + "chapters/chapter-0001.xhtml": - route.fulfill(content_type="application/xhtml+xml", body=chapter) - else: - route.fulfill(status=404, body="missing") - bucket_url = ("https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" - + urllib.parse.quote(prefix + "chapter-manifest.json", safe="")) - for mode, url, root in ( - ("foliate", self.reader_url("epub", name="remote-refs"), - "document.querySelector('article[data-section]')?.shadowRoot"), - ("chapters", self.reader_url("epub-chapters", url=bucket_url), - "document.querySelector('.reader-epub-chapter')"), - ): - with self.subTest(mode=mode): - page = self.context.new_page() - page.set_default_timeout(int(os.environ.get("READER_TEST_TIMEOUT_MS", "6000"))) - page.on("pageerror", lambda error: self.errors.append(str(error))) - remote = [] - page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None) - page.route("**/api/reader-content**", lambda route: route.fulfill( - content_type="application/epub+zip", body=book)) - page.route("https://voiceofml-search.hf.space/api/reader-bucket-resource**", bucket) - page.goto(url) - page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") - page.wait_for_function(f"() => !!({root})?.querySelector('#kept')") - page.wait_for_timeout(400) - self.assertEqual(remote, []) - self.assertEqual(page.evaluate(f"() => ({root}).querySelector('#local-use').getAttribute('href')"), "#dot") - page.close() + remote = [] + self.page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None) + chapter_root = self.open_security_chapter(chapter.encode()) + chapter_root.locator("#kept").wait_for(state="attached") + self.page.wait_for_timeout(400) + self.assertEqual(remote, []) + self.assertEqual(chapter_root.locator("#local-use").get_attribute("href"), "#dot") def expose_html_contrast(self): def instrument(route): @@ -4000,52 +3558,6 @@ class ReaderRefactorTest(unittest.TestCase): saved = self.page.evaluate("source => VoiceOfMLReaderStore.get(source)", source) self.assertEqual(saved["chapterIndex"], 1) - def test_foliate_cfi_selects_accented_and_inline_ranges_after_repeated_search(self): - with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - chapter = next(name for name in files if name.endswith("chapter-1.xhtml")) - files[chapter] = b''' - Search -

    Search

    Before

    -

    café

    Between

    -

    cafe

    international

    After

    - ''' - self.serve(support.zip_bytes(files), "application/epub+zip") - self.open(self.reader_url("epub")) - self.search("cafe") - self.assertEqual(self.page.locator(".full-search-result").count(), 2) - self.page.locator(".full-search-result").first.click() - self.assertEqual(self.page.locator("#accent .full-search-highlight").text_content(), "caf\u00e9") - self.page.locator("#history").click() - self.assertFalse(self.page.locator("#full-search-view").is_hidden()) - self.page.locator(".full-search-result").nth(1).click() - self.assertEqual(self.page.locator("#plain .full-search-highlight").text_content(), "cafe") - self.page.locator("#history").click() - self.assertFalse(self.page.locator("#full-search-view").is_hidden()) - self.page.locator("#full-search-input").fill("international") - self.page.locator(".full-search-result").click() - self.page.locator("#inline .full-search-highlight").first.wait_for() - self.assertEqual("".join(self.page.locator("#inline .full-search-highlight").all_text_contents()), "international") - - def test_chm_self_closing_anchors_keep_text_order_and_search_after_many_entries(self): - with zipfile.ZipFile(io.BytesIO(support.epub_with_legacy_chm_markup())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - # Hundreds of empty XML anchors become nested containers under HTML - # parsing, which can reorder inline citations near the parser depth cap. - entries = ''.join(f'Entry {i}: ' - f'Citation {i}; End {i}.' for i in range(600)) - files['OEBPS/chapter.xhtml'] = ( - '' - 'Order' + entries + '' - ).encode() - self.serve(support.zip_bytes(files), "application/epub+zip") - self.open(self.reader_url("epub")) - body = self.page.locator('.foliate-continuous .reader-section-body') - self.assertEqual(body.text_content(), ''.join(f'Entry {i}: Citation {i}; End {i}.' for i in range(600))) - self.search('Citation 599') - self.page.locator('.full-search-result').first.click() - self.assertEqual(self.page.locator('.foliate-continuous .full-search-highlight').text_content(), 'Citation 599') - def test_chapter_resources_allow_siblings_within_manifest_family_only(self): for extension in ("epub", "chm"): with self.subTest(extension=extension): diff --git a/tests/reader/browser/test_reader_speech.py b/tests/reader/browser/test_reader_speech.py index f78ab8e2da4f688ee6e21715ce965b79daaedb1d..0655e84d51969f9104be0290f539596e44adaa8c 100644 --- a/tests/reader/browser/test_reader_speech.py +++ b/tests/reader/browser/test_reader_speech.py @@ -599,17 +599,6 @@ class ReaderSpeechTest(unittest.TestCase): finally: context.close() - def test_foliate_epub_reads_sections_in_order(self): - if not (ROOT / "static/foliate-reader/view.js").exists(): - self.skipTest("fetch Foliate first: node scripts/build/fetch_foliate_reader.mjs") - context, page, posts, errors = self.open("epub", epub_with_navigation(), "application/epub+zip") - try: - job = self.play(page, posts) - self.assertTrue(any(word in job["text"] for word in ("目录", "第一章")), job["text"][:60]) - self.stop(page) - self.assertFalse(errors, errors) - finally: - context.close() if __name__ == "__main__": diff --git a/tests/reader/browser/test_reader_style.py b/tests/reader/browser/test_reader_style.py index 33167aea1c241c4f1954519717b10006ac01a39f..ff7fd19a8f45a2f946b2b50151f1c9d060e7cca8 100644 --- a/tests/reader/browser/test_reader_style.py +++ b/tests/reader/browser/test_reader_style.py @@ -87,7 +87,6 @@ class ReaderStyleTests(unittest.TestCase): for mode, markup, surface in ( ('markdown','
    Markdown
    ','#viewport'), ('epub-chapters','
    Chapter
    ','.epub-frame'), - ('foliate','
    Book
    ','.foliate-continuous'), ): with self.subTest(mode=mode): self.page.locator('#content').evaluate('''(e,[mode,markup])=>{ @@ -98,7 +97,6 @@ class ReaderStyleTests(unittest.TestCase): for mode in ('pdf','pdf-pages','image','html','video'): self.page.locator('#content').evaluate('(e,mode)=>e.dataset.mode=mode', mode) self.assertEqual(viewport.evaluate('e=>getComputedStyle(e).backgroundColor'), 'rgb(233, 236, 239)', mode) - self.assertEqual(self.page.locator('.foliate-continuous').evaluate('e=>getComputedStyle(e).backgroundColor'), 'rgb(255, 255, 255)', mode) def test_back_and_download_icons_have_stable_browser_independent_geometry(self): self.page.evaluate("""() => { @@ -432,11 +430,11 @@ class ReaderStyleTests(unittest.TestCase): cancel.click() self.assertTrue(dialog.is_hidden()) - def test_foliate_and_video_follow_toolbar_across_breakpoint_and_resize(self): + def test_video_follows_toolbar_across_breakpoint_and_resize(self): for width, height in ((390, 844), (390, 360), (600, 500), (601, 500), (1440, 900)): with self.subTest(width=width, height=height): self.page.set_viewport_size({"width": width, "height": height}) - for mode in ("foliate", "video"): + for mode in ("video",): metrics = self.page.locator("#content").evaluate("""(content, mode) => { content.dataset.mode = mode; content.innerHTML = mode === 'video' ? '' : ''; @@ -450,10 +448,7 @@ class ReaderStyleTests(unittest.TestCase): self.assertEqual(metrics["toolbar"], expected_toolbar) self.assertAlmostEqual(metrics["height"], height - expected_toolbar, delta=1) self.assertEqual(metrics["padding"], "0px") - if mode == "foliate": - self.assertAlmostEqual(metrics["minHeight"], height - expected_toolbar, delta=1) - else: - self.assertAlmostEqual(metrics["video"], height - expected_toolbar, delta=1) + self.assertAlmostEqual(metrics["video"], height - expected_toolbar, delta=1) def test_mobile_folder_action_and_title_follow_breakpoint(self): self.page.emulate_media(reduced_motion='reduce') @@ -705,10 +700,8 @@ class ReaderStyleTests(unittest.TestCase): self.assertTrue(all(float(value.strip().removesuffix('s')) == 0 for group in values for value in group.split(',')), values) - def test_high_contrast_overrides_light_borders_and_internal_link_reset(self): + def test_high_contrast_overrides_light_borders(self): self.page.emulate_media(contrast="more") - self.page.locator("#content").evaluate("""content => content.insertAdjacentHTML('beforeend', - '')""") for theme in ("dark", "light"): self.page.locator("html").evaluate("(element, theme) => element.dataset.theme = theme", theme) for selector, border in ((".reader-toolbar", "borderBottomColor"), @@ -721,74 +714,3 @@ class ReaderStyleTests(unittest.TestCase): return [style[border], style.color]; }""", border) self.assertEqual(colors[0], colors[1], (selector, theme, colors)) - self.assertIn("underline", self.page.locator(".foliate-continuous a").evaluate( - "element => getComputedStyle(element).textDecorationLine" - )) - - def test_rendered_foliate_shadow_tracks_contrast_without_layout_changes(self): - with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive: - files = {name: archive.read(name) for name in archive.namelist()} - # A book rule makes normal and high-contrast underlining distinguishable. - files["OEBPS/nav.xhtml"] = files["OEBPS/nav.xhtml"].decode().replace( - "a{color:#000}", "a{color:#000;text-decoration:none!important}" - ).replace("", " ContrastTarget", 1) - book = zip_bytes(files) - self.page.route("**/api/reader-content**", lambda route: route.fulfill( - content_type="application/epub+zip", body=book - )) - source = urllib.parse.quote( - "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/contrast.epub", safe="" - ) - self.page.emulate_media(contrast="no-preference") - self.page.goto( - f"{self.origin}/static/reader.html?url={source}&ext=epub&title=Contrast", - wait_until="domcontentloaded", - ) - self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") - support.open_reader_panel(self.page) - self.page.locator("#full-search-toggle").click() - self.page.locator("#full-search-input").fill("ContrastTarget") - self.page.locator("#full-search-results .full-search-result").first.click() - highlight = self.page.locator(".foliate-continuous mark.full-search-highlight").first - highlight.wait_for() - self.settle() - measure = """mark => { - const root = mark.getRootNode(), link = mark.closest('a[href]'); - const style = getComputedStyle(mark); - const rect = element => { - const box = element.getBoundingClientRect(); - return [box.x, box.y, box.width, box.height]; - }; - const viewport = document.querySelector('#viewport'); - return { - shadow: root instanceof ShadowRoot && root.host.matches('article[data-section]'), - text: mark.textContent, - decoration: getComputedStyle(link).textDecorationLine, - outline: style.outlineStyle, - width: parseFloat(style.outlineWidth), - outlineColor: style.outlineColor, - color: style.color, - layout: [rect(document.querySelector('.reader-toolbar')), rect(viewport), - rect(root.host), rect(link), rect(mark), - [viewport.scrollWidth, viewport.scrollHeight, viewport.scrollTop]] - }; - }""" - for theme in ("dark", "light"): - with self.subTest(theme=theme): - self.page.locator("html").evaluate( - "(element, theme) => element.dataset.theme = theme", theme - ) - before = highlight.evaluate(measure) - self.assertTrue(before["shadow"]) - self.assertEqual(before["text"], "ContrastTarget") - self.assertEqual(before["decoration"], "none") - self.assertEqual(before["outline"], "none") - self.page.emulate_media(contrast="more") - high = highlight.evaluate(measure) - self.assertIn("underline", high["decoration"]) - self.assertEqual(high["outline"], "solid") - self.assertEqual(high["width"], 2) - self.assertEqual(high["outlineColor"], high["color"]) - self.assertEqual(high["layout"], before["layout"]) - self.page.emulate_media(contrast="no-preference") - self.assertEqual(highlight.evaluate(measure), before) diff --git a/tests/reader/browser/test_reader_toc_navigation.py b/tests/reader/browser/test_reader_toc_navigation.py index 08fc41ee3b67e7765bcffb8e8aef096a2211e130..870e2bbac6b5ff248b8a008f8e685faacb9e2788 100644 --- a/tests/reader/browser/test_reader_toc_navigation.py +++ b/tests/reader/browser/test_reader_toc_navigation.py @@ -1,18 +1,14 @@ """Shared table-of-contents navigation regressions: sidebar jumps land where the entry says. -Covers chapter bundles (`epub-chapters`) and the Foliate EPUB engine, early and late -entries, fragments inside large chapters, re-jumps after window trimming, rapid -successive clicks, group headings, the virtualized directory and the opening hint. +Covers chapter bundles (`epub-chapters`): early and late entries, fragments inside +large chapters, re-jumps after window trimming, rapid successive clicks, the +virtualized directory and the opening hint. Also covers PDF and HTML navigation. """ -import io -import json import re import unittest -import zipfile from urllib.parse import unquote, urlencode from tests.reader.browser import test_reader_pdf_followup as support -from tests.performance.test_reader_performance import epub_with_many_chapters, zip_bytes BODY = '

    正文

    ' @@ -33,32 +29,6 @@ def chapter_body(index): f'

    第{index}章 第二节

    {BODY}') -def epub_with_group_headings(count, groups=4): - """EPUB whose navigation groups chapters under href-less headings.""" - manifest = '' - spine = '' - files, items = {}, [] - per_group = max(1, count // groups) - for index in range(1, count + 1): - manifest += f'' - spine += f'' - files[f"OEBPS/chapter-{index}.xhtml"] = ( - f'' - f'

    第{index}章

    正文

    ') - if (index - 1) % per_group == 0: - items.append(f'
  • 分组 {(index - 1) // per_group + 1}
      ') - items.append(f'
    1. 第{index}章
    2. ') - if index % per_group == 0 or index == count: - items.append('
  • ') - files.update({ - "META-INF/container.xml": '', - "OEBPS/content.opf": f'reader-toc-groupsReader Toc Groupszh{manifest}{spine}', - "OEBPS/nav.xhtml": ('' - f''), - }) - return zip_bytes(files, ("mimetype", "application/epub+zip")) - - class TocNavigationTests(unittest.TestCase): setUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__) setUp = support.PdfFollowupTests.setUp @@ -72,7 +42,7 @@ class TocNavigationTests(unittest.TestCase): response = route.fetch() route.fulfill(response=response, body=response.text() + ''' window.__replaceTocForSearch=setToc; - window.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i), syncFoliate:syncFoliateScrollLocation, + window.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i), set:setToc, filter:()=>filterPanel(document.querySelector('#toc-panel')), setPageCount:count=>updateDocumentState({pageCount:count}), setPage:page=>{updateDocumentState({page});updateTocCurrentMark()}, @@ -115,17 +85,6 @@ class TocNavigationTests(unittest.TestCase): f"()=>document.querySelectorAll('#toc-list .toc-item').length>={min_rows}") self.assert_instrumented() - def open_epub(self, body): - self.expose() - self.page.route("**/api/reader-content**", lambda route: route.fulfill( - content_type="application/epub+zip", body=body, - headers={"Access-Control-Allow-Origin": "*"})) - self.page.goto(self.origin + support.PREFIX + "/static/reader.html?" + urlencode( - dict(url="https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc.epub", ext="epub")), - wait_until="domcontentloaded") - self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") - self.assert_instrumented() - def test_pdf_outline_uses_destination_page_not_title(self): self.expose() engine = support.ENGINE.replace('getOutline:async()=>null', '''getOutline:async()=>[ @@ -215,12 +174,6 @@ class TocNavigationTests(unittest.TestCase): return null; }""") - def directory_rows(self): - return self.page.evaluate("""() => [...document.querySelectorAll('#toc-list .toc-item')].map(row => ({ - index: Number(row.dataset.tocIndex), text: row.textContent.trim().slice(0, 12), - group: row.classList.contains('toc-group'), - role: row.querySelector('.panel-item-main')?.getAttribute('role') || null}))""") - def panel_open(self): return self.page.evaluate("()=>document.querySelector('#history').getAttribute('aria-expanded') === 'true'") @@ -251,53 +204,6 @@ class TocNavigationTests(unittest.TestCase): self.assertFalse(self.panel_open()) self.assertEqual(self.page.evaluate('document.activeElement.id'),'history') - def test_foliate_scroll_only_checks_the_active_sections_toc_entries(self): - self.open_epub(epub_with_group_headings(6,groups=2)) - self.page.wait_for_function('()=>__toc.nav().tocEntries.length===8') - result = self.page.evaluate('''()=>{ - const viewport=document.querySelector('#viewport'), top=viewport.getBoundingClientRect().top+80; - const article=document.querySelector('.foliate-continuous article[data-section="0"]'); - const position=y=>()=>({top:y}); - article.getBoundingClientRect=position(top-20); - const target={getBoundingClientRect:position(top-5)}; - const after={getBoundingClientRect:position(top+5)}; - const entry=(label,sectionIndex,props={})=>({label,sectionIndex,activate:()=>true,...props}); - const items=[entry('first',0,{anchor:()=>target}),entry('later tie',0,{anchor:()=>target}), - ...Array.from({length:1000},(_,i)=>entry('other '+i,500+i))]; - __toc.set(items); - const nav=()=>__toc.nav().currentChapterIndex; - let offSectionReads=0; - for(const e of __toc.nav().tocEntries.slice(2)) { - const n=e.sectionIndex; - Object.defineProperty(e,'sectionIndex',{get(){offSectionReads++;return n}}); - } - __toc.syncFoliate();const tied=nav();offSectionReads=0; - __toc.syncFoliate();const warm=offSectionReads; - __toc.set([entry('different section',1),entry('fallback',0,{anchor:()=>after,target}), - entry('later fallback',0,{anchor:()=>after,target:after})]); - __toc.syncFoliate(); - return {tied,warm,fallback:nav()}; - }''') - self.assertEqual(result,dict(tied=1,warm=0,fallback=1)) - - def test_foliate_chapter_buttons_skip_group_headings_and_keep_directory_open(self): - self.open_epub(epub_with_group_headings(6,groups=2)) - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===8") - for width in (390, 1280): - with self.subTest(width=width): - self.page.set_viewport_size({'width':width,'height':844}) - self.page.emulate_media(reduced_motion='reduce') - self.click_entry(3) - self.page.wait_for_function("()=>document.querySelector('#history').getAttribute('aria-expanded')==='false'") - self.page.locator('#history').click() - self.page.locator('#toc-tab').click() - for selector,index in [('.reader-chapter-next',5),('.reader-chapter-prev',3)]: - self.page.locator(selector).click() - self.page.wait_for_function('index=>__toc.nav().currentChapterIndex===index',arg=index) - self.assertTrue(self.panel_open(),selector) - self.assertEqual(self.page.locator('#toc-tab').get_attribute('aria-selected'),'true') - self.assertEqual(self.page.locator('#toc-list [aria-current="location"]').count(),1) - def test_chapter_buttons_boundaries_do_not_close_directory(self): self.open_chapters(6) self.click_entry(0) @@ -1063,21 +969,6 @@ class TocNavigationTests(unittest.TestCase): self.assertGreaterEqual(result["after"] - result["before"], 1400, "a reader scroll must not be pulled back by the hold") - def test_new_navigation_supersedes_the_previous_landing_hold(self): - self.open_epub(epub_with_many_chapters()) - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14") - for index, chapter in [(9, 10), (4, 5), (7, 8)]: - self.page.evaluate("index => __toc.jump(index)", index) - self.page.wait_for_function('''chapter=>{ - const node=document.querySelector(`article[data-section="${chapter}"]`)?.shadowRoot?.querySelector(`#chapter-${chapter}`); - return node && Math.abs(node.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3; - }''', arg=chapter, timeout=1500) - self.page.wait_for_timeout(160) - offset = self.page.locator(f'article[data-section="{chapter}"] #chapter-{chapter}').evaluate( - "node=>node.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top") - self.assertLess(abs(offset - 8), 3, - 'the previous hold must not pull a newer jump back') - def test_landing_hold_is_cancelled_on_disposal(self): self.open_chapters(40) self.page.evaluate("index => __toc.jump(index)", 19) @@ -1117,35 +1008,7 @@ class TocNavigationTests(unittest.TestCase): self.assertEqual(result["before"], result["after"], "re-assertion must not pull a reader who scrolled away back") - # ---- group headings and the opening hint ---- - - def test_group_heading_rows_are_not_links(self): - self.open_epub(epub_with_group_headings(40, groups=4)) - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length>4") - rows = self.directory_rows() - headings = [row for row in rows if row["group"]] - self.assertEqual(len(headings), 4, "href-less navigation headings must still be listed") - self.assertTrue(all(row["role"] == "heading" for row in headings)) - navigable = [row for row in rows if not row["group"]] - self.assertTrue(all(row["role"] == "link" for row in navigable)) - before = self.page.evaluate("()=>document.querySelector('#viewport').scrollTop") - self.page.evaluate("""(index) => { - document.querySelector(`#toc-list .toc-item[data-toc-index="${index}"] .panel-item-main`).click(); - }""", headings[0]["index"]) - self.page.wait_for_timeout(800) - self.assertEqual(self.page.evaluate("()=>document.querySelector('#viewport').scrollTop"), before, - "a group heading must not navigate anywhere") - - def test_navigation_ignores_a_group_entry_index(self): - self.open_epub(epub_with_group_headings(20, groups=2)) - self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length>4") - rows = self.directory_rows() - group = next(row for row in rows if row["group"]) - before = self.page.evaluate("()=>__toc.nav().currentChapterIndex") - self.page.evaluate("(index)=>__toc.jump(index)", group["index"]) - self.page.wait_for_timeout(900) - self.assertEqual(self.page.evaluate("()=>__toc.nav().currentChapterIndex"), before, - "a group index must not navigate or change the current entry") + # ---- opening hint ---- def test_directory_hint_opens_for_more_than_three_entries(self): self.open_chapters(6) @@ -1161,12 +1024,6 @@ class TocNavigationTests(unittest.TestCase): self.assertFalse(self.panel_open(), f"a {count}-entry directory must not open the panel on its own") - def test_directory_hint_skips_a_three_entry_grouped_navigation(self): - self.open_epub(epub_with_group_headings(2, groups=1)) - self.page.wait_for_timeout(500) - self.assertFalse(self.panel_open(), - "two chapters under one heading is still a trivial directory") - if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/reader/copy_reader_vendor.test.mjs b/tests/reader/copy_reader_vendor.test.mjs index 6f0ebffe05dd04d4c84d503573788e382329a123..7a2cf80abf760cf188c258fb79f19dd4ca326584 100644 --- a/tests/reader/copy_reader_vendor.test.mjs +++ b/tests/reader/copy_reader_vendor.test.mjs @@ -91,7 +91,7 @@ function tarGzip(files) { async function run(cwd, env, scriptPath = script) { return new Promise((resolve, reject) => { - const child = spawn(process.execPath, [scriptPath, "out", "--foliate-output", "foliate"], { cwd, env }); + const child = spawn(process.execPath, [scriptPath, "out"], { cwd, env }); let stderr = "", timedOut = false; const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, 15000); child.stderr.on("data", (chunk) => { stderr += chunk; }); @@ -118,7 +118,7 @@ test("environment proxy, bounded concurrent downloads, bypass and hash failure", writeFileSync(cert, TEST_CERT); const ruffleFiles = { "ruffle.js": "ruffle loader", "core.js": "ruffle core", "core.wasm": "wasm bytes", "LICENSE": "license" }; const pdfFiles = { "cmaps/existing": "new pdf", "standard_fonts/font": "font", "wasm/decoder": "wasm" }; - const bodies = { "/archive": tarGzip(pdfFiles), "/ruffle": tarGzip({ ...ruffleFiles, "ignored.txt": "ignored" }), "/a": Buffer.from("a"), "/b": Buffer.from("b"), "/c": Buffer.from("c"), "/d": Buffer.from("d"), "/f": Buffer.from("f") }; + const bodies = { "/archive": tarGzip(pdfFiles), "/ruffle": tarGzip({ ...ruffleFiles, "ignored.txt": "ignored" }), "/a": Buffer.from("a"), "/b": Buffer.from("b"), "/c": Buffer.from("c"), "/d": Buffer.from("d") }; let active = 0, maxActive = 0, connects = 0, failureMode = false, limitMode = ""; let limitRequests = 0, limitClosed = 0; const seen = [], blockedClosed = []; @@ -169,7 +169,7 @@ test("environment proxy, bounded concurrent downloads, bypass and hash failure", const resources = (host) => { const url = (name) => `https://${host}:${server.address().port}/${name}`; const entry = (name) => ({ url: url(name), sha256: hash(bodies[`/${name}`]), file: `${name}.js`, path: `vendor/${name}.js` }); - return { pdfArchive: entry("archive"), vendors: { a: entry("a"), b: entry("b"), c: entry("c"), d: entry("d") }, foliateVendors: { f: entry("f") }, ruffleArchive: { ...entry("ruffle"), directory: "vendor/ruffle/release-test", files: Object.keys(ruffleFiles) } }; + return { pdfArchive: entry("archive"), vendors: { a: entry("a"), b: entry("b"), c: entry("c"), d: entry("d") }, ruffleArchive: { ...entry("ruffle"), directory: "vendor/ruffle/release-test", files: Object.keys(ruffleFiles) } }; }; const save = (value) => writeFileSync(join(dir, "static/reader-resources.js"), `module.exports = ${JSON.stringify(value)};`); const env = { ...process.env, NODE_EXTRA_CA_CERTS: cert, HTTPS_PROXY: `http://127.0.0.1:${proxy.address().port}`, https_proxy: "", NO_PROXY: "", no_proxy: "", HTTP_PROXY: "", http_proxy: "" }; @@ -178,10 +178,8 @@ test("environment proxy, bounded concurrent downloads, bypass and hash failure", assert.equal(result.code, 0, result.stderr); assert.ok(connects > 0, "HTTPS traffic passed through the proxy"); assert.ok(maxActive > 1 && maxActive <= 4, `concurrency: ${maxActive}`); - assert.equal(readFileSync(join(dir, "foliate/f.js"), "utf8"), "f"); for (const [file, content] of Object.entries(pdfFiles)) { assert.equal(readFileSync(join(dir, "out", file), "utf8"), content); - assert.equal(readFileSync(join(dir, "foliate/pdfjs", file), "utf8"), content); } for (const [file, content] of Object.entries(ruffleFiles)) { assert.equal(readFileSync(join(dir, "out/ruffle/release-test", file), "utf8"), content); @@ -192,13 +190,11 @@ test("environment proxy, bounded concurrent downloads, bypass and hash failure", bad.vendors.d.sha256 = "0".repeat(64); save(bad); writeFileSync(join(dir, "out/a.js"), "old"); - writeFileSync(join(dir, "foliate/f.js"), "old foliate"); writeFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "old ruffle"); result = await run(dir, env); assert.notEqual(result.code, 0); assert.match(result.stderr, /SHA-256/); assert.equal(readFileSync(join(dir, "out/a.js"), "utf8"), "old"); - assert.equal(readFileSync(join(dir, "foliate/f.js"), "utf8"), "old foliate"); assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle"); // The hash matches, but a later PDF tar entry is malformed after a valid file. @@ -208,17 +204,13 @@ test("environment proxy, bounded concurrent downloads, bypass and hash failure", bodies["/archive"] = gzipSync(malformedTar); save(resources("example.test")); mkdirSync(join(dir, "out/cmaps"), { recursive: true }); - mkdirSync(join(dir, "foliate/pdfjs/cmaps"), { recursive: true }); writeFileSync(join(dir, "out/cmaps/existing"), "old pdf"); - writeFileSync(join(dir, "foliate/pdfjs/cmaps/existing"), "old foliate pdf"); result = await run(dir, env); assert.notEqual(result.code, 0); assert.match(result.stderr, /Invalid PDF archive entry size/); assert.equal(readFileSync(join(dir, "out/cmaps/existing"), "utf8"), "old pdf"); - assert.equal(readFileSync(join(dir, "foliate/pdfjs/cmaps/existing"), "utf8"), "old foliate pdf"); assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle"); assert.equal(readFileSync(join(dir, "out/a.js"), "utf8"), "old"); - assert.equal(readFileSync(join(dir, "foliate/f.js"), "utf8"), "old foliate"); // Each required group must contain a regular file, not just a directory or link. for (const group of ["cmaps", "standard_fonts", "wasm"]) { const files = Object.fromEntries(Object.entries(pdfFiles).filter(([name]) => !name.startsWith(group + "/"))); @@ -231,7 +223,6 @@ test("environment proxy, bounded concurrent downloads, bypass and hash failure", assert.notEqual(result.code, 0, `${group}: ${type}`); assert.match(result.stderr, type === "symlink" ? /Invalid PDF archive entry/ : new RegExp(`PDF archive missing required files: ${group}`)); assert.equal(readFileSync(join(dir, "out/cmaps/existing"), "utf8"), "old pdf"); - assert.equal(readFileSync(join(dir, "foliate/pdfjs/cmaps/existing"), "utf8"), "old foliate pdf"); assert.equal(readFileSync(join(dir, "out/ruffle/release-test/ruffle.js"), "utf8"), "old ruffle"); } } diff --git a/tests/reader/core/test_reader_architecture.js b/tests/reader/core/test_reader_architecture.js index 137b990cf5a5e05f11aa990ceaa92e101bc1adaa..059b960ee8daf97517ce0fb31d69961c3a82de85 100644 --- a/tests/reader/core/test_reader_architecture.js +++ b/tests/reader/core/test_reader_architecture.js @@ -31,32 +31,12 @@ assertCode(reader, 'await imageLoader.load(image, target, renderController.signa assert.doesNotMatch(reader, /function (?:waitReaderImage|loadReaderImage)\(/) assert.doesNotMatch(imageLoader, /readerRuntime|readerContentUrl|pdfPageManifest|documentState|new Image|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) -for (const file of ['epub.js', 'mobi.js', 'fb2.js', 'pdf.js', 'view.js', 'progress.js', 'ui/tree.js']) assert.ok(fs.existsSync(path.join(root, 'static/foliate-reader', file)), file) -assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/mobi.js'), 'utf8'), /createDocument/) -assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/fb2.js'), 'utf8'), /resolveHref/) -assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/epub.js'), 'utf8'), /String\(href \?\? ''\)/) -assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/epub.js'), 'utf8'), /item\.mediaType === MIME\.XHTML/) -const foliateReader = fs.readFileSync(path.join(root, 'static/foliate-reader/reader.js'), 'utf8') -for (const message of ['voice-foliate-goto-cfi', 'voice-foliate-search', 'voice-foliate-seek', 'voice-foliate-prev', 'voice-foliate-next']) assert.ok(foliateReader.includes(message), message) - -assert.strictEqual((reader.match(/async function renderFoliate\(/g) || []).length, 1) -assert.strictEqual(reader.includes('renderFoliateClean'), false) -assert.strictEqual(reader.includes('renderFoliateLegacy'), false) -assert.strictEqual(reader.includes('foliate-continuous'), true) +assert.doesNotMatch(reader, /\b(?:renderFoliate|foliateSectionLoader)\b/) +assert.doesNotMatch(reader, /foliate-reader/) +assertCode(reader, 'for (const frame of [markerFrame, epubSeekFrame])') assert.strictEqual(reader.includes('document.querySelector("#toc-list").addEventListener'), false) -assert.strictEqual(reader.includes('activateFoliateTocEntryLatest'), false) -assert.strictEqual(reader.includes('setupFoliateToc'), false) -assert.strictEqual(reader.includes('foliateVisibleSections'), false) -assert.strictEqual(reader.includes('foliateVisibleNodes'), false) -assert.strictEqual(reader.includes('directFoliateMoving'), false) -assert.strictEqual(reader.includes('directFoliateContainer'), false) -assert.strictEqual(reader.includes('setInterval(() => { loadNextFoliateSection(); }, 100)'), false) assert.strictEqual(reader.includes('setInterval(() => { const tab = document.querySelector("#toc-tab")'), false) assert.strictEqual(reader.includes('setInterval('), false) -assert.match(reader, /function scheduleFoliateScrollSync\(\)/) -assert.match(reader, /foliateSectionObserver\?\.disconnect\(\)/) assert.strictEqual((reader.match(/function disposeReader\(\)/g) || []).length, 1) assert.strictEqual((reader.match(/function setReaderPhase\(/g) || []).length, 1) assert.strictEqual((reader.match(/function classifyReaderError\(/g) || []).length, 1) @@ -66,7 +46,7 @@ assert.match(reader, /readerRuntime\.setStage\(stage\)/) assert.match(reader, /\$\{readerLifecycle\.stage\}/) assertCode(reader, 'function scheduleSave() { if (readerLifecycle.disposed || readerAbortController.signal.aborted) return;') assertCode(reader, 'readerLifecycle.disposed || !documentState.restorationReady') -assert.strictEqual((reader.match(/if \(!setReaderPhase\("ready"\)\) return/g) || []).length, 2) +assert.strictEqual((reader.match(/if \(!setReaderPhase\("ready"\)\) return/g) || []).length, 1) assert.match(reader, /addEventListener\("pagehide"/) assert.match(reader, /event\.persisted/) assert.match(reader, /!event\.persisted/) @@ -105,7 +85,6 @@ assert.match(reader, /readerRuntime\.track\(readerRequestManager\)/) assert.doesNotMatch(reader, /legacyReaderTitle/) for (const generation of ['navigation', 'search', 'bookmarks', 'pdf']) assert.match(reader, new RegExp(`nextReaderGeneration\\("${generation}"\\)`)) for (const timer of ['saveTimer', 'themeAnimationTimer', 'panelAnimationTimer']) assert.match(reader, new RegExp(`clearTimeout\\(${timer}\\)`)) -assertCode(reader, 'for (const frame of [markerFrame, foliateScrollFrame, foliateWindowFrame, epubSeekFrame]) if (frame) cancelAnimationFrame(frame)') assert.match(reader, /trackReaderResource\(destroy\)/) assert.match(reader, /task\.destroy\(\)/) assert.match(reader, /mediaElement\.pause\(\)/) @@ -137,27 +116,17 @@ for (const renderer of ['renderImageDocument', 'renderMedia']) assert.strictEqua for (const renderer of ['renderTextDocument', 'renderMarkdownDocument']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\(`,'g')) || []).length, 1) for (const loader of ['loadTextDocument', 'loadMarkdownDocument', 'loadHtmlDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1) for (const loader of ['loadMediaDocument', 'loadImageDocument', 'loadChapterManifestDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1) -assert.doesNotMatch(reader, /loadFoliateDocument/) assert.match(reader, /reader-chapter-repository\.js/) assert.match(reader, /reader-scroll-anchor\.js/) assert.match(reader, /reader-section-virtualizer\.js/) -assert.match(reader, /VoiceOfMLReaderChapters\.createChapterRepository\(/) +assert.match(reader, /VoiceOfMLReaderChapters\.createChapterScheduler\(/) assert.match(reader, /VoiceOfMLReaderScroll\.createScrollAnchorManager\(/) assert.match(reader, /VoiceOfMLReaderVirtual\.createSectionVirtualizer\(/) -assert.match(reader, /foliateChapterRepository\?\.dispose\(\)/) assertCode(reader, 'readerRuntime.track(VoiceOfMLReaderScroll') -assert.match(reader, /foliateSectionVirtualizer\?\.dispose\(\)/) -assert.match(reader, /function foliateSectionRoot\(article\)/) -assertCode(reader, 'article.attachShadow({ mode: "open" })') assert.match(reader, /event\.composedPath\(\)/) -assert.match(reader, /foliateSectionRoot\(node\)/) -assert.match(reader, /foliateScrollAnchors\.observe\(article\)/) -assert.ok((reader.match(/foliateScrollAnchors\.invalidate\(\)/g) || []).length >= 3) -const renderFoliateSource = reader.match(/async\s+function\s+renderFoliate\s*\([\s\S]*?status\.textContent\s*=\s*"EPUB";/)[0] -assert.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*(?:\/\*[\s\S]*?\*\/\s*\(\s*)?(?:\(index\)|index)\s*=>/) +assertCode(reader, 'chapterScrollAnchors.observe(article)') +assertCode(reader, 'chapterVirtualizer.dispose()') +assertCode(reader, 'frame.insertBefore(article, next || null)') assert.doesNotMatch(reader, /^let navigationGeneration\b/m) assert.doesNotMatch(reader, /syncReaderState/) assert.doesNotMatch(reader, /^(?:let|var|const)\s+title\b/m) @@ -174,27 +143,18 @@ assertCode(searchController, 'const generation = nextGeneration()') assert.match(reader, /isReaderGenerationCurrent\("navigation", generation\)/) assert.match(reader, /registerReaderFormatAdapters\(\)/) assert.match(reader, /function disposeFormatResources\(mode\)/) -assertCode(reader, 'link.target = "_blank"; link.rel = "noopener noreferrer"') +assertCode(reader, 'trustedChapterReferenceUrl(link.getAttribute("href"), chapterUrl') +assertCode(reader, 'element.removeAttribute(name)') assert.doesNotMatch(reader, /function (?:navigateFormat|searchFormat)\(/) assert.match(reader, /async function restoreFormat\(mode, entry, generation/) assert.match(reader, /formatAdapters\.activate\(capability\.mode\)/) assert.match(reader, /readerRuntime\.events\.on\("phase"/) assert.strictEqual((reader.match(/function navigateTocEntry\(/g) || []).length, 1) assert.match(reader, /await navigateTocEntry\(index,\s*\{\s*closePanel:\s*false\s*\}\)/) -assert.strictEqual((reader.match(/function navigateFoliateSearchResult\(/g) || []).length, 1) -assert.strictEqual((reader.match(/function\s+fullSearchFoliateMatches\s*\(/g) || []).length, 1) -assertCode(reader, 'publishSearchResults(generation, await fullSearchFoliateMatches(query, generation))') -assert.match(reader, /function captureFoliateBookmarkPosition\(\)/) -assert.match(reader, /function restoreFoliateBookmarkPosition\(entry, generation/) -assert.match(reader, /foliatePosition = captureFoliateBookmarkPosition\(\)/) assert.match(reader, /new IntersectionObserver/) assert.doesNotMatch(reader, /article\.innerHTML = styles \+/) -assert.match(reader, /target = await epubRendition\?\.book\?\.resolveHref/) assert.match(reader, /applyReaderMetadata\(resolvedReaderData\)/) -assert.match(css, /\.foliate-continuous\s+a\s*\{\s*color:\s*#8ab4e8\s*!important;\s*\}/) -assert.match(css, /min-height:\s*0\s*!important;\s*height:\s*auto\s*!important;/) -assert.strictEqual(view.includes('.find(x => x.index = resolved.index)'), false) -assert.strictEqual(view.includes('.find(x => x.index === resolved.index)'), true) +assert.doesNotMatch(css, /\.foliate-continuous/) const vm = require('vm') const priorityFunctions = reader.match(/function pdfPagePriority\(shell\) \{[\s\S]*?\n\}(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)+function normalizePdfPriority\(priority\) \{[\s\S]*?\n\}/) assert.ok(priorityFunctions, 'PDF page priority functions') @@ -240,12 +200,11 @@ const expected = { image: ['loadImageDocument', 'renderImageDocument'], text: ['loadTextDocument', 'renderTextDocument'], markdown: ['loadMarkdownDocument', 'renderMarkdownDocument'], html: ['loadHtmlDocument', 'renderHtml'], 'epub-chapters': ['loadChapterManifestDocument', 'renderChapterManifest'], - foliate: ['loadMediaDocument', 'renderFoliate'], swf: ['loadSwfDocument', 'renderSwf'], } const registered = new Map(), calls = [] const registryContext = { extension: 'pdf', formatAdapters: { register: (mode, adapter) => registered.set(mode, adapter) } } -for (const name of [...new Set(Object.values(expected).flat()), 'loadPdfDocument', 'renderPdf', 'preloadPdfFirstPage', 'fetchReaderResponse', 'renderPdfPages', 'renderImagePages', 'renderMedia', 'restoreFormat', 'disposeFormatResources']) registryContext[name] = (...args) => calls.push([name, ...args]) +for (const name of [...new Set(Object.values(expected).flat()), 'loadPdfDocument', 'renderPdf', 'preloadPdfFirstPage', 'fetchReaderResponse', 'renderPdfPages', 'renderImagePages', 'loadMediaDocument', 'renderMedia', 'restoreFormat', 'disposeFormatResources']) registryContext[name] = (...args) => calls.push([name, ...args]) vm.runInNewContext(imageOpen[0] + '\n' + registry[0] + '; registerReaderFormatAdapters();', { ...registryContext, readerRestorationPromise: null, readerRuntime: {currentGeneration: () => 1} }) diff --git a/tests/reader/core/test_reader_format_controller_boundary.mjs b/tests/reader/core/test_reader_format_controller_boundary.mjs index 46e13e52eba52845ed5d13c4eb8e19daf89163f3..b9edfd3afc96f603f45aef292e3460958b1d30dd 100644 --- a/tests/reader/core/test_reader_format_controller_boundary.mjs +++ b/tests/reader/core/test_reader_format_controller_boundary.mjs @@ -52,7 +52,7 @@ test("resolution retains string and legacy DJVU semantics", async () => { }); test("classification is narrowed at the fail boundary without coercion", async () => { - for (const mode of ["text", "foliate"]) { + for (const mode of ["text", "epub-chapters"]) { for (const value of ["READER_RESTORE", undefined, 42, Symbol("code"), hostile]) { const f = fixture({}); let calls = 0, failure; @@ -64,11 +64,11 @@ test("classification is narrowed at the fail boundary without coercion", async ( downloadButton: {}, documentState: { title: "book" }, readerDownloadUrl: () => "download", formatAdapters: { activate() {}, active: { open: async () => { throw error; } } }, readerResources: new Set(), loadReaderRestoration: async () => null, awaitReader: promise => promise, - renderFoliate: async () => { throw error; }, readerAbortController: new AbortController(), + readerAbortController: new AbortController(), classifyReaderError: (received, fallback) => { calls++; assert.equal(received, error); - assert.equal(fallback, mode === "foliate" ? "READER_CORRUPT" : "READER_PARSE"); + assert.equal(fallback, "READER_PARSE"); return value; }, fail: (message, code) => { failure = [message, code]; } @@ -77,7 +77,7 @@ test("classification is narrowed at the fail boundary without coercion", async ( const savedError = console.error; try { console.error = () => {}; await f.controller.start(); } finally { console.error = savedError; } assert.equal(calls, 1); - assert.deepEqual(failure, ["failure", typeof value === "string" ? value : mode === "foliate" ? "READER_CORRUPT" : "READER_PARSE"]); + assert.deepEqual(failure, ["failure", typeof value === "string" ? value : "READER_PARSE"]); } } }); diff --git a/tests/reader/core/test_reader_regression.js b/tests/reader/core/test_reader_regression.js index f126dfad0c906e274fc80a9d48ce4724b1294cd9..3fe0cea66e5f50ace80d9da58278d884d69b55fe 100644 --- a/tests/reader/core/test_reader_regression.js +++ b/tests/reader/core/test_reader_regression.js @@ -303,10 +303,10 @@ for (const path of [assetRoot + '../linearized.pdf', assetRoot + 'private.json', assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: path}), null) } -for (const extension of ['pdf', 'pdf-pages', 'txt', 'md', 'markdown', 'html', 'htm', 'epub', 'mobi', 'azw3', 'fb2', 'fbz', 'jpg', 'png', 'mp3', 'm4a', 'flac', 'mpga', 'audio', 'mp4', 'mov', 'video']) { +for (const extension of ['pdf', 'pdf-pages', 'txt', 'md', 'markdown', 'html', 'htm', 'epub-chapters', 'jpg', 'png', 'mp3', 'm4a', 'flac', 'mpga', 'audio', 'mp4', 'mov', 'video']) { assert.ok(sandbox.self.VoiceOfMLReader.capability(extension).mode, extension) } -for (const extension of ['epub', 'mobi', 'azw3', 'fb2', 'fbz']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'foliate') +for (const extension of ['epub', 'mobi', 'azw', 'azw3', 'fb2', 'fbz']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, null) 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']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages') assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true) @@ -318,12 +318,12 @@ assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('docx').mode, null) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').mode, 'epub-chapters') const convertedUrl = sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/books/book.mobi', - File: '原始书名', Extension: 'mobi', ReaderExtension: 'epub', + File: '原始书名', Extension: 'mobi', ReaderExtension: 'epub-chapters', DownloadLink: 'https://download.example.test/books/book.mobi', ReaderChapterManifest: 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + encodeURIComponent('chapters/ebook/mobi/' + 'c'.repeat(64) + '/' + 'b'.repeat(16) + '/chapter-manifest.json'), }, '/reader.html') const convertedParams = new URL(`https://example.test${convertedUrl}`).searchParams -assert.strictEqual(convertedParams.get('ext'), 'epub') +assert.strictEqual(convertedParams.get('ext'), 'epub-chapters') assert.strictEqual(convertedParams.get('title'), '原始书名.mobi') assert.strictEqual(convertedParams.get('download'), 'https://download.example.test/books/book.mobi') assert.strictEqual(convertedParams.get('fallback'), null) @@ -339,7 +339,7 @@ const sharedAsset = 'https://voiceofml-search.hf.space/api/reader-bucket-resourc const sourceIds = ['Teachers', 'MLMRL-Hub'].map(repo => { const record = { Link: `https://huggingface.co/datasets/VoiceOfML/${repo}/resolve/main/book.mobi`, File: 'book', Extension: 'mobi' } const params = value => new URL(`https://example.test${sandbox.self.VoiceOfMLReader.readerUrl(value)}`).searchParams - const original = params(record).get('id') + const original = sandbox.self.VoiceOfMLReader.shortSourceId(record.Link) const converted = params({ ...record, ReaderLink: sharedAsset, ReaderExtension: 'epub-chapters' }) assert.strictEqual(converted.get('id'), original) assert.match(original, /^[a-z0-9]{13}$/) @@ -358,7 +358,7 @@ assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').readerMode, sa assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').article, true) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.UNSUPPORTED) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').article, false) -for (const extension of ['pdf', 'pdf-pages', 'epub', 'epub-chapters', 'mobi', 'azw3', 'fb2', 'fbz', 'txt', 'md', 'html', 'jpg', 'png', 'webp', 'mp3', 'm4a', 'flac', 'mp4', 'mov']) assert.ok(sandbox.self.VoiceOfMLReader.articleExtensions.includes(extension), extension) +for (const extension of ['pdf', 'pdf-pages', 'epub-chapters', 'txt', 'md', 'html', 'jpg', 'png', 'webp', 'mp3', 'm4a', 'flac', 'mp4', 'mov']) assert.ok(sandbox.self.VoiceOfMLReader.articleExtensions.includes(extension), extension) assert.ok(!sandbox.self.VoiceOfMLReader.articleExtensions.includes('docx')) assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.articleExtensions), true) assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.capability('pdf')), true) @@ -371,7 +371,6 @@ assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1) assertCode(reader, 'const previousList = /** @type {HTMLElement} */ (document.querySelector("#toc-list"))') assertCode(reader, 'previousList.cloneNode(false)') assertCode(reader, 'previousList.replaceWith(list)') -assert.strictEqual((reader.match(/function activateFoliateTocEntry\(/g) || []).length, 1) assert.match(reader, /reader-source:/) assert.match(reader, /reader-zoom/) assert.match(reader, /readerRuntime\.track\(readerRequestManager\)/) diff --git a/tests/reader/djvu/test_reader_djvu_png.mjs b/tests/reader/djvu/test_reader_djvu_png.mjs index 2068f0c1b71398ee5692db9949544af4fa9fab31..e5841886b92a0dcb07b186c90d78eb5362a3333e 100644 --- a/tests/reader/djvu/test_reader_djvu_png.mjs +++ b/tests/reader/djvu/test_reader_djvu_png.mjs @@ -70,7 +70,7 @@ console.log('Historical PNG metadata remains verifiable; document image renderin for (const mode of ['pdf', 'pdf-pages', 'image-pages']) { let resized = false; const anchor = {isConnected: true, getBoundingClientRect: () => resized ? {top: -700, height: 1000} : {top: -400, height: 800}}; - const reader = {capability: {mode}, foliateScrollAnchors: {capture: () => null, restore() {}}, + const reader = {capability: {mode}, chapterScrollAnchors: {capture: () => null, restore() {}}, pageAtMarker: () => anchor, documentState: {zoom: 1}, content: {style: {setProperty() {}}}, zoomInput: {}, viewport: {scrollTop: 1000, scrollLeft: 0, scrollWidth: 600, clientWidth: 600, getBoundingClientRect: () => ({top: 0})}, pdfShellWindow: {resize: () => {resized = true;}}, @@ -82,7 +82,7 @@ for (const mode of ['pdf', 'pdf-pages', 'image-pages']) { } for (const mode of ['pdf', 'pdf-pages', 'image-pages']) { const anchor = {isConnected: true, getBoundingClientRect: () => ({top: 238, height: 577})}; - const reader = {capability: {mode}, foliateScrollAnchors: {capture: () => null, restore() {}}, + const reader = {capability: {mode}, chapterScrollAnchors: {capture: () => null, restore() {}}, pageAtMarker: () => anchor, documentState: {zoom: 1}, content: {style: {setProperty() {}}}, zoomInput: {}, viewport: {scrollTop: 385, scrollHeight: 1193, clientHeight: 808, scrollLeft: 0, scrollWidth: 390, clientWidth: 390, getBoundingClientRect: () => ({top: 36})}, diff --git a/tests/reader/lifecycle/test_reader_lifecycle.mjs b/tests/reader/lifecycle/test_reader_lifecycle.mjs index 585d1506ec411ad6b7587281f6170b6ed933460c..da3cf05d4fa36746ff3f3848157a739d3e57dfcf 100644 --- a/tests/reader/lifecycle/test_reader_lifecycle.mjs +++ b/tests/reader/lifecycle/test_reader_lifecycle.mjs @@ -116,12 +116,12 @@ test('waitForReader rejects on cancellation and resolves on its timer', async () } }); -test('reader readiness preserves Foliate anchor only when loading node is connected', () => { +test('reader readiness preserves chapter anchor only when loading node is connected', () => { const {context,events}=fixture(); context.loadingIndicator={isConnected:true,remove(){events.push('remove');}}; context.loadingStatus={hidden:false}; - context.foliateScrollAnchors={preserve(callback){events.push('preserve');return callback();}}; - context.capability={mode:'foliate'};context.markReaderContentReady(); + context.chapterScrollAnchors={preserve(callback){events.push('preserve');return callback();}}; + context.capability={mode:'epub-chapters'};context.markReaderContentReady(); assert.deepEqual(events,['preserve','remove']);assert.equal(context.loadingStatus.hidden,true); events.length=0;context.capability={mode:'pdf'};context.markReaderContentReady(); assert.deepEqual(events,['remove']); @@ -148,15 +148,15 @@ test('dispose is idempotent, releases observer and clears all timer handles', () context.updateDocumentState=value=>events.push(value); context.contentSanitizerObserver={disconnect(){events.push('observer');}}; const handles=['saveTimer','themeAnimationTimer','panelAnimationTimer','markerFrame', - 'foliateScrollFrame','foliateWindowFrame','epubSeekFrame']; + 'epubSeekFrame']; handles.forEach((key,index)=>context[key]=index+1); try { context.disposeReader();context.disposeReader(); assert.deepEqual(events,[{restorationReady:false},'observer',['clear',1],['clear',2],['clear',3], - ['cancel',4],['cancel',5],['cancel',6],['cancel',7],'store']); + ['cancel',4],['cancel',5],'store']); assert.equal(context.readerLifecycle.disposed,true); assert.equal(context.contentSanitizerObserver,null); - assert.deepEqual(handles.map(key=>context[key]),[0,0,0,0,0,0,0]); + assert.deepEqual(handles.map(key=>context[key]),[0,0,0,0,0]); } finally {globalThis.VoiceOfMLReaderStore=store;globalThis.clearTimeout=oldClear;globalThis.cancelAnimationFrame=oldCancel;} }); diff --git a/tests/reader/pdf-network/test_pdf_range_cache_release.mjs b/tests/reader/pdf-network/test_pdf_range_cache_release.mjs index 7db5ffa3f061651024e88753cdf97212d0490db8..8e181c0ca6f5a287328600ea7f0247513d74825d 100644 --- a/tests/reader/pdf-network/test_pdf_range_cache_release.mjs +++ b/tests/reader/pdf-network/test_pdf_range_cache_release.mjs @@ -82,8 +82,7 @@ test('PDF range dependencies are built before the network consumer and pinned fo } else if(extension==='pdf') { assert.ok(hrefs.includes(base+built('reader/pdf/pdf-worker-wrapper.mjs').path),'intent and Reader use hashed worker URL'); assert.ok(hrefs.includes(base+'vendor/wasm/qcms_bg.wasm'),'ICC branch survives build'); - } else if(extension==='epub') assert.ok(hrefs.includes(base+'foliate-reader/view.js'+(project==='github'?'?reader-v1':''))); - else assert.deepEqual(hrefs,[]); + } else assert.deepEqual(hrefs,[]); } } const original=readFileSync(join(root,'static',network),'utf8'); diff --git a/tests/reader/test_foliate_proxy.mjs b/tests/reader/test_foliate_proxy.mjs deleted file mode 100644 index 400fb22d136dd85a659e0422e551eca817d6218b..0000000000000000000000000000000000000000 --- a/tests/reader/test_foliate_proxy.mjs +++ /dev/null @@ -1,179 +0,0 @@ -import { test, after } from "node:test"; -import assert from "node:assert/strict"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { createHash } from "node:crypto"; -import { spawn } from "node:child_process"; -import { gzipSync } from "node:zlib"; -import http from "node:http"; -import https from "node:https"; -import net from "node:net"; - -// Fixed self-signed credentials for local tests only; public and not secret. -// SAN: example.test, localhost, 127.0.0.1; expires 2046-11-09 UTC. -const TEST_KEY = `-----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/73saPTntjwNm -odAEUTt7sytZpJkW6Wc7si8xxVHLzHlD/LTwLl+dDAj6OW6O1Weomp5lTat9Huho -YtDT9CvMDoHJz5Kd6Q6vI6VdKoJOLk2vocK1XYYs0VoQPYe8JIiQZihqEAGMdMHC -UCVGBBVxgNLFTPu1PMkadCS3t4DeMF78Y23g8NgPX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B/zAoBgNVHREEITAfggxleGFtcGxlLnRl -c3SCCWxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOCAQEAHFb0Y3zhzQ3s -VrJGrgX+3jR8hfQNn6cJgXlhEtgZcJvRjSDO3MM1UNVZD5CkXqUZy8OF5/3+eJNj -lYWxmA8PVgeHO/SF4cjPQdvYYTIvD4zqbSVVivgLsieTcSqrFPFyogPrOemW03WW -WBMGCce3D92r+B3KCGdwO70oDofFe7/Bi3soffQ0mVOKFA9otVV3QVxD2NEOo1Ym -vZ/NjRre6WexUaICRXtKNoPnFp4UdlCnZDDqnW7oTvaxKzVDczMYNgtbVtOZ6+EQ -eh06pGOd4MtLpXZSfos+FUnL4y6R1p6gRSacT6Y7ffwU3jqrE8y/4m5g0bjlEDz0 -momx60pAKw== ------END CERTIFICATE----- -`; -const root = mkdtempSync(join(tmpdir(), "foliate-proxy-")); -after(() => rmSync(root, { recursive: true, force: true })); -const script = resolve(dirname(fileURLToPath(import.meta.url)), "../../scripts/build/fetch_foliate_reader.mjs"); -const fixture = join(root, "fixture"); -mkdirSync(join(fixture, "static"), { recursive: true }); -mkdirSync(join(fixture, "scripts/build"), { recursive: true }); -writeFileSync(join(fixture, "scripts/build/fetch.mjs"), readFileSync(script)); -writeFileSync(join(fixture, "scripts/build/foliate-local.patch.b64"), Buffer.from( - "diff --git a/ok.txt b/ok.txt\n@@ -1 +1 @@\n-before\n+after\n" -).toString("base64")); -// Build a one-file ustar archive without requiring an external tar executable. -const header = Buffer.alloc(512); -const contents = Buffer.from("before\n"); -header.write("foliate-js-rev/ok.txt"); -header.write("0000644\0", 100); -header.write("0000000\0", 108); -header.write("0000000\0", 116); -header.write(contents.length.toString(8).padStart(11, "0") + "\0", 124); -header.write("00000000000\0", 136); -header.fill(32, 148, 156); -header[156] = 48; -header.write("ustar\0", 257); -header.write("00", 263); -header.write(header.reduce((sum, byte) => sum + byte, 0).toString(8).padStart(6, "0") + "\0 ", 148); -const archive = gzipSync(Buffer.concat([header, contents, Buffer.alloc(512 - contents.length), Buffer.alloc(1024)])); -writeFileSync(join(root, "key"), TEST_KEY); -writeFileSync(join(root, "cert"), TEST_CERT); -const hits = [], connections = [], sockets = new Set(); -const server = https.createServer({ key: readFileSync(join(root, "key")), cert: readFileSync(join(root, "cert")) }, (req, res) => { - hits.push(req.url); - if (req.url === "/redirect") res.writeHead(302, { location: "/archive" }).end(); - else res.end(archive); -}); -await new Promise(resolvePromise => server.listen(0, "127.0.0.1", resolvePromise)); -const proxy = http.createServer(); -proxy.on("connect", (req, client, head) => { - connections.push({ url: req.url, auth: req.headers["proxy-authorization"] }); - const upstream = net.connect(server.address().port, "127.0.0.1", () => { - client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); - if (head.length) upstream.write(head); - client.pipe(upstream).pipe(client); - }); - for (const socket of [client, upstream]) { - sockets.add(socket); - socket.on("close", () => sockets.delete(socket)); - socket.on("error", () => { client.destroy(); upstream.destroy(); }); - } -}); -await new Promise(resolvePromise => proxy.listen(0, "127.0.0.1", resolvePromise)); -after(() => { for (const socket of sockets) socket.destroy(); server.close(); proxy.close(); }); -const proxyUrl = `http://secretuser:secretpass@127.0.0.1:${proxy.address().port}`; -writeFileSync(join(fixture, "static/reader-resources.js"), `module.exports = ${JSON.stringify({ - foliateRevision: "rev", foliateArchive: { url: `https://localhost:${server.address().port}/redirect`, sha256: createHash("sha256").update(archive).digest("hex") }, foliateFiles: ["ok.txt"] -})};`); - -async function run(env = {}, preload) { - const args = preload ? ["--require", preload] : []; - const child = spawn(process.execPath, [...args, join(fixture, "scripts/build/fetch.mjs"), join(fixture, "out")], { - cwd: fixture, env: { PATH: process.env.PATH, NODE_EXTRA_CA_CERTS: join(root, "cert"), ...env } - }); - let output = ""; - child.stdout.on("data", data => output += data); - child.stderr.on("data", data => output += data); - const timer = setTimeout(() => child.kill("SIGKILL"), 5000); - const result = await new Promise((resolvePromise, reject) => { - child.on("error", reject); - child.on("close", (code, signal) => resolvePromise({ code, signal, output })); - }).finally(() => clearTimeout(timer)); - assert.equal(result.signal, null, `child timed out: ${output}`); - assert.doesNotMatch(output, /secretuser|secretpass|c2VjcmV0dXNlcjpzZWNyZXRwYXNz/); - return result; -} - -test("version boundaries reject before modifying output or contacting the network", async () => { - for (const version of ["18.20.0", "22.20.0", "23.11.0", "24.4.0"]) { - const preload = join(root, "version.cjs"); - writeFileSync(preload, `Object.defineProperty(process.versions, 'node', {value: ${JSON.stringify(version)}});`); - mkdirSync(join(fixture, "out"), { recursive: true }); - writeFileSync(join(fixture, "out/sentinel"), version); - const previousHits = hits.length; - const result = await run({ HTTPS_PROXY: proxyUrl }, preload); - assert.equal(result.code, 1, version); - assert.match(result.output, /Node\.js 22\.21\+, 24\.5\+, or later is required for proxy support/); - assert.equal(readFileSync(join(fixture, "out/sentinel"), "utf8"), version); - assert.equal(hits.length, previousHits); - } -}); - -const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number); -const supportsProxy = !(nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 21) || nodeMajor === 23 || (nodeMajor === 24 && nodeMinor < 5)); - -test("supported version boundaries allow proxy download, redirect and patch", { skip: !supportsProxy }, async () => { - for (const version of ["22.21.0", "24.5.0", "25.0.0", "26.0.0"]) { - const preload = join(root, "version.cjs"); - writeFileSync(preload, `Object.defineProperty(process.versions, 'node', {value: ${JSON.stringify(version)}});`); - hits.length = 0; connections.length = 0; - const result = await run({ HTTPS_PROXY: proxyUrl }, preload); - assert.equal(result.code, 0, result.output); - assert.deepEqual(hits, ["/redirect", "/archive"]); - assert.equal(connections.length, 2); - assert.ok(connections.every(connection => connection.auth === "Basic c2VjcmV0dXNlcjpzZWNyZXRwYXNz")); - assert.equal(readFileSync(join(fixture, "out/ok.txt"), "utf8"), "after\n"); - } -}); - -test("NO_PROXY bypasses the proxy and lowercase https_proxy works", { skip: !supportsProxy }, async () => { - connections.length = 0; - let result = await run({ HTTPS_PROXY: proxyUrl, NO_PROXY: "localhost" }); - assert.equal(result.code, 0, result.output); - assert.equal(connections.length, 0); - result = await run({ https_proxy: proxyUrl }); - assert.equal(result.code, 0, result.output); - assert.equal(connections.length, 2); -}); diff --git a/tests/reader/transport/test_reader_engine_preload.js b/tests/reader/transport/test_reader_engine_preload.js index 2dd86f2a39202cdd1d2c312b7ce7723ef1c65b07..d900754852f5fe5688c42ecc3acfc9bccf6a168f 100644 --- a/tests/reader/transport/test_reader_engine_preload.js +++ b/tests/reader/transport/test_reader_engine_preload.js @@ -42,11 +42,8 @@ function fixture(prefix,query,{saveData=false,held=false,httpFailure=false,readF const f=fixture(prefix,'?ext='+extension),base='https://site.test'+prefix,suffix=prefix==='/search/static/'?'?reader-v1':''; assert.deepStrictEqual(f.links.map(link=>link.href),resources.engineAssets(extension,base,suffix)); assert.equal(f.fetches.length,0); - if(extension==='epub'){ - assert.ok(f.links.some(link=>link.href===base+'foliate-reader/vendor/zip.js')); - assert.ok(f.links.some(link=>link.href===base+'foliate-reader/epub.js')); - assert.ok(f.links.every(link=>link.rel==='modulepreload')); - }else{ + if(extension==='epub') assert.deepStrictEqual(f.links, [], 'removed raw EPUB engine must not be warmed'); + else { assert.ok(f.links.every(link=>link.rel==='preload'&&link.as==='script')); if(extension==='html'||extension==='htm')assert.equal(f.links.length,1); } @@ -82,17 +79,6 @@ function fixture(prefix,query,{saveData=false,held=false,httpFailure=false,readF assert.ok(calls.every(url=>url.includes('/'+(simd?'simd128':'scalar')+'/'))); assert.equal(calls.length,2); } - // Every static view.js import must be warmed with view.js, or it is only - // discovered after view.js arrives (an extra round trip on first open). - const view=path.join(root,'static/foliate-reader/view.js'); - if(fs.existsSync(view)){ - const imports=[...fs.readFileSync(view,'utf8').matchAll(/^import\s[^;]*?from\s+['"]\.\/([^'"]+)['"]/gm)].map(m=>m[1]); - assert.ok(imports.length>=4,'expected view.js static imports'); - for(const extension of ['epub','mobi','azw','azw3','fb2','fbz']){ - const hrefs=resources.engineAssets(extension,'/static/'); - for(const file of imports)assert.ok(hrefs.includes('/static/foliate-reader/'+file),extension+' must warm '+file); - } - }else console.log('foliate-reader not prepared; static import coverage skipped (run copy_reader_vendor.mjs)'); const lean=fixture('/static/','?ext=pdf',{saveData:true});await tick();assert.equal(lean.fetches.length,1); assert.ok(lean.fetches[0].url.endsWith('pdf-worker-wrapper.mjs')); for(const event of ['pagehide','voice-reader-dispose','timeout']){ @@ -106,5 +92,5 @@ function fixture(prefix,query,{saveData=false,held=false,httpFailure=false,readF } assert.ok(resources.readerFiles.indexOf('reader/pdf/pdf-worker-wrapper.mjs'){console.error(error);process.exitCode=1;}); diff --git a/tests/search/backend/test_search_order_cache.py b/tests/search/backend/test_search_order_cache.py index e899af14c5e099f079d16f6b3d05e2ab20940caa..380343cabf3e9ac37402801c1bf8720da89272f4 100644 --- a/tests/search/backend/test_search_order_cache.py +++ b/tests/search/backend/test_search_order_cache.py @@ -116,6 +116,35 @@ class SearchOrderCacheTests(unittest.TestCase): self.assertEqual(len(app._search_order_cache), 1) self.assertLessEqual(sum(len(v[1])*v[1].itemsize for v in app._search_order_cache.values()), 12) + def test_order_eviction_counts_bytes_once_after_expiry(self): + class CountingOrders(OrderedDict): + scans = 0 + + def values(self): + self.scans += 1 + return super().values() + + # Mixed item sizes ensure eviction subtracts bytes, not element counts. + orders = CountingOrders([ + (('expired',), (0, array('B', range(10)))), + (('oldest',), (100, array('B', range(3)))), + (('middle',), (100, array('H', range(2)))), + (('newest',), (100, array('B', range(2)))), + ]) + incoming = array('B', range(5)) + with mock.patch.object(app, '_search_order_cache', orders), \ + mock.patch.object(app.time, 'monotonic', return_value=100), \ + mock.patch.object(app, 'SEARCH_ORDER_CACHE_TTL_SECONDS', 50), \ + mock.patch.object(app, 'SEARCH_ORDER_CACHE_MAX', 3), \ + mock.patch.object(app, 'SEARCH_ORDER_CACHE_BYTES_MAX', 7), \ + mock.patch.object(app, '_search_order_uncached', return_value=incoming): + result = app._get_search_order('new', None, None, None, None, None, + True, 'relevance', False, 'prefix', None, None) + self.assertIs(result, incoming) + self.assertEqual(orders.scans, 1) + self.assertEqual(list(orders)[:-1], [('newest',)]) + self.assertIs(next(reversed(orders.values()))[1], incoming) + def test_anchor_reuse_skips_scans_across_pages_and_preserves_missing_results(self): anchor = 'VoiceOfML/B\0one/alpha.txt' first = app.search(sort='name', page_size=1, anchor_id=anchor) diff --git a/tests/search/ui/catalog_contracts.mjs b/tests/search/ui/catalog_contracts.mjs index f31b72cb692eb356a2a284cd193962dde5850fb4..6433be0fe5b110956dd99bf3808869496d46c3d4 100644 --- a/tests/search/ui/catalog_contracts.mjs +++ b/tests/search/ui/catalog_contracts.mjs @@ -120,9 +120,9 @@ test(label + ' extension empty inventory, copy and concurrent behavior remain si const f = fixture(baseline); f.settleBootstrap({extensions:[]}); if (space) { assert.deepEqual(plain(await f.extensions(null)), []); assert.equal(f.calls.length, 0); } const a = f.extensions('owner/repo'), b = f.extensions('owner/repo'); await turn(); - assert.equal(f.calls.length, space ? 2 : 1); + assert.equal(f.calls.length, space && baseline ? 2 : 1); assert.equal(f.calls[0].url, space ? '/api/extensions?repo=owner/repo' : 'https://metadata.test/api/extensions?repo=owner%2Frepo'); - f.reply(0, []); if (space) f.reply(1, []); + f.reply(0, []); if (space && baseline) f.reply(1, []); assert.deepEqual(plain(await a), []); const value = await b; assert.deepEqual(plain(value), []); value.push({name:'selected-only'}); const cached = await f.extensions('owner/repo'); @@ -130,6 +130,97 @@ test(label + ' extension empty inventory, copy and concurrent behavior remain si cached.push({name:'mutated-cache-read'}); assert.equal((await f.extensions('owner/repo')).length, space ? 2 : 0); }); +if (space && !baseline) test(label + ' extensions coalesce per receiver and key, retry failures and preserve repo switching', async () => { + const f = fixture(); f.settleBootstrap(); + const a = f.extensions('a'), a2 = f.extensions('a'), b = f.extensions('b'); + await turn(); + assert.deepEqual(f.calls.map(call => call.url), ['/api/extensions?repo=a', '/api/extensions?repo=b']); + f.reply(1, ['b']); assert.deepEqual(plain(await b), ['b']); + const a3 = f.extensions('a'); await turn(); assert.equal(f.calls.length, 2); + f.reply(0, ['a']); + assert.deepEqual(plain(await Promise.all([a, a2, a3])), [['a'], ['a'], ['a']]); + assert.deepEqual(plain(await f.extensions('a')), ['a']); + const againB = f.extensions('b'); await turn(); assert.equal(f.calls.length, 3); + f.reply(2, ['b2']); assert.deepEqual(plain(await againB), ['b2']); + + const bad = f.extensions('bad'), bad2 = f.extensions('bad'); await turn(); + f.reply(3, {error:'malformed'}); + const results = await Promise.allSettled([bad, bad2]); + assert.equal(results.every(r => r.status === 'rejected' && /Invalid metadata/.test(r.reason.message)), true); + assert.deepEqual(plain(await f.extensions('b')), ['b2']); + const retry = f.extensions('bad'); await turn(); f.reply(4, []); + assert.deepEqual(plain(await retry), []); + const network = f.extensions('network'), network2 = f.extensions('network'); await turn(); + f.calls[5].reject(new Error('network failure')); + const errors = await Promise.allSettled([network, network2]); + assert.equal(errors.every(r => r.status === 'rejected' && /network failure/.test(r.reason.message)), true); + const networkRetry = f.extensions('network'); await turn(); f.reply(6, ['ok']); + assert.deepEqual(plain(await networkRetry), ['ok']); + + const other = {getBootstrap:async () => null}; + const first = f.extensions('separate'), second = f.c.owner.getExtensions.call(other, 'separate'); + await turn(); assert.equal(f.calls.length, 9); + f.reply(7, ['first']); f.reply(8, ['second']); + assert.deepEqual(plain(await first), ['first']); assert.deepEqual(plain(await second), ['second']); + assert.equal(f.timers.size, 0); +}); +if (space && !baseline) test(label + ' extension invalidation isolates A-B-A visits in completion order and reverse order', async () => { + for (const order of [[0, 1, 2], [2, 1, 0]]) { + const f = fixture(); f.settleBootstrap(); + const oldA = f.extensions('a'); + f.c.owner._extCache = null; + const b = f.extensions('b'); + f.c.owner._extCache = null; + const newA = f.extensions('a'), sameVisit = f.extensions('a'); + await turn(); + assert.deepEqual(f.calls.map(call => call.url), ['/api/extensions?repo=a', '/api/extensions?repo=b', '/api/extensions?repo=a']); + const values = [['old-a'], ['b'], ['new-a']]; + const requests = [oldA, b, newA]; + for (const index of order) { + f.reply(index, values[index]); + assert.deepEqual(plain(await requests[index]), values[index]); + } + assert.deepEqual(plain(await sameVisit), ['new-a']); + assert.deepEqual(plain(await f.extensions('a')), ['new-a']); + assert.equal(f.calls.length, 3); + } +}); +if (space && !baseline) test(label + ' invalidation before completion prevents stale cache writes and stale cleanup', async () => { + const f = fixture(); f.settleBootstrap(); + const old = f.extensions('a'); await turn(); + f.c.owner._extCache = null; + f.reply(0, ['obsolete']); assert.deepEqual(plain(await old), ['obsolete']); + assert.equal(f.c.owner._extCache, null); + const first = f.extensions('a'); await turn(); + f.c.owner._extCache = null; + const fresh = f.extensions('a'); await turn(); + f.reply(1, null, 503); await assert.rejects(first); + const joined = f.extensions('a'); await turn(); assert.equal(f.calls.length, 3); + f.reply(2, ['fresh']); + assert.deepEqual(plain(await fresh), ['fresh']); assert.deepEqual(plain(await joined), ['fresh']); + assert.deepEqual(plain(await f.extensions('a')), ['fresh']); +}); +if (space && !baseline) test(label + ' global extension bootstrap and fallback are coalesced and retryable', async () => { + const f = fixture(); + let resolveBootstrap, bootstrapCalls = 0; + f.c.owner.getBootstrap = () => { bootstrapCalls++; return new Promise(resolve => { resolveBootstrap = resolve; }); }; + const a = f.extensions(null), b = f.extensions(null); await turn(); + assert.equal(bootstrapCalls, 1); assert.equal(f.calls.length, 0); + resolveBootstrap(null); await turn(); assert.equal(f.calls.length, 1); + const c = f.extensions(null); f.reply(0, null, 503); + assert.equal((await Promise.allSettled([a, b, c])).every(r => r.status === 'rejected'), true); + f.settleBootstrap({extensions:[]}); + assert.deepEqual(plain(await f.extensions(null)), []); assert.equal(f.calls.length, 1); + + f.c.owner._extCache = null; + f.c.owner.getBootstrap = () => Promise.reject(new Error('bootstrap failed')); + const failed = await Promise.allSettled([f.extensions(null), f.extensions(null)]); + assert.equal(failed.every(r => r.status === 'rejected' && /bootstrap failed/.test(r.reason.message)), true); + f.settleBootstrap(); + const retry = f.extensions(null); await turn(); f.reply(1, ['global']); + assert.deepEqual(plain(await retry), ['global']); + assert.equal(f.timers.size, 0); +}); test(label + ' sidebar bootstrap/static fallback coalesces and preserves compact values', async () => { const f = fixture(baseline); f.settleBootstrap(); const a = f.invoke('loadSidebarInitial', 'owner/repo'), b = f.invoke('loadSidebarInitial', 'owner/repo'); diff --git a/tests/search/ui/test_folder_tree_memo.mjs b/tests/search/ui/test_folder_tree_memo.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6a83e8b84b630cc02240f5992769b131da09ea46 --- /dev/null +++ b/tests/search/ui/test_folder_tree_memo.mjs @@ -0,0 +1,72 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import test from 'node:test'; + +function fixture() { + const context = vm.createContext({Set, Map, performance: {now: () => 0}, setTimeout, clearTimeout}); + for (const file of ['domain/folder-selection.js', 'presentation/folder-tree.js']) { + vm.runInContext(fs.readFileSync(new URL(`../../../static/search/sidebar/${file}`, import.meta.url), 'utf8'), context); + } + const node = (path, children = [], direct = true) => ({path, name: path, children, isRoot: !path, + hasDirectFiles: direct, hasChildren: !!children.length, showSelfToggle: direct && !!children.length}); + const c = node('a/b/c'), b = node('a/b', [c]), a = node('a', [b]); + const root = node('', [a, node('ab'), node('empty', [node('empty/x')], false)]); + const nodes = [root, a, b, c, root.children[1], root.children[2], root.children[2].children[0]]; + const view = {tree: [root], subtrees: [], selfs: [], collapsed: {'': true}, mode: 'repo', routeId: 1}; + const listeners = {}, rows = []; + const container = {isConnected: true, addEventListener(type, fn) { listeners[type] = fn; }, + replaceChildren() { rows.length = 0; }, appendChild(row) { rows.push(row); }, + querySelectorAll() { return rows.filter(row => row._folderNode); }}; + context.document = {createElement() { return {style: {setProperty() {}}, dataset: {}, + querySelector() { return null; }, setAttribute() {}}; }}; + const original = context.VoiceOfMLSearchFolderSelection; + let builds = 0, stateLookups = []; + const selection = {...original, + createFolderSelectionLookup(...args) { builds++; return original.createFolderSelectionLookup(...args); }, + folderSelectionState(...args) { stateLookups.push(args[3]); return original.folderSelectionState(...args); }}; + const controller = context.VoiceOfMLSidebarFolderTree.create({readView: () => view, container, selection, + escape: x => x, commitSelection(subtrees, selfs) { view.subtrees = subtrees; view.selfs = selfs; }, + notify() { throw Error('unexpected limit'); }}); + const selected = () => nodes.filter(n => n.hasDirectFiles && (view.selfs.includes(n.path) || + original.folderPathCovered(n.path, new Set(view.subtrees)))).map(n => n.path); + return {view, nodes, controller, selected, listeners, get builds() { return builds; }, stateLookups}; +} + +test('inversion preserves file-membership complement for 2048 mixed selections', () => { + const f = fixture(); + const paths = f.nodes.filter(n => n.hasDirectFiles).map(n => n.path); + const subtreePaths = f.nodes.slice(1).map(n => n.path); + for (let mask = 0; mask < 2048; mask++) { + f.view.selfs = paths.filter((_, i) => mask & (1 << i)); + f.view.subtrees = subtreePaths.filter((_, i) => mask & (1 << (i + paths.length))); + const before = f.selected(); + f.controller.invertSelection(); + assert.deepEqual(f.selected(), paths.filter(path => !before.includes(path)), `mask ${mask}`); + f.controller.invertSelection(); + assert.deepEqual(f.selected(), before, `double inversion ${mask}`); + } +}); + +test('checkbox uses current memo, invalidates on mutation and tree replacement', () => { + const f = fixture(); + f.controller.render(); + assert.equal(f.builds, 1); + const change = node => f.listeners.change({target: {closest: () => ({_folderNode: node}), matches: () => true}}); + change(f.nodes[1]); + assert.ok(f.stateLookups.at(-1) instanceof Map); + assert.equal(f.builds, 3); // initial, normalization, refresh; no checkbox-only build + assert.deepEqual(f.selected(), ['a', 'a/b', 'a/b/c']); + change(f.nodes[2]); + assert.equal(f.builds, 5); + assert.deepEqual(f.selected(), ['a']); + f.view.selfs.push('ab'); + change(f.nodes[4]); + assert.equal(f.builds, 8); // changed input invalidates before checkbox evaluation + assert.deepEqual(f.selected(), ['a']); + f.view.tree = [...f.view.tree]; + change(f.nodes[1]); + assert.equal(f.builds, 11); // changed tree invalidates too + assert.deepEqual(f.selected(), ['a', 'a/b', 'a/b/c']); + f.controller.cancel(); +}); diff --git a/tests/support/reader_test_selection.py b/tests/support/reader_test_selection.py index 1b5675e4a9d8c382a7637de3241eabf4e5bbee20..67740728a57f9081cc909f5e979f9d0aa0efc8de 100644 --- a/tests/support/reader_test_selection.py +++ b/tests/support/reader_test_selection.py @@ -22,7 +22,6 @@ CATEGORY_METHODS = { "test_video_failure_shows_recoverable_reader_error", "test_video_extension_aliases_report_media_errors_consistently", "test_unsupported_format_hides_inapplicable_controls", - "test_truncated_epub_reports_source_damage", "test_txt_displays_before_stream_finishes", "test_text_reader_uses_scroll_mode_without_pagination_controls", "test_reader_tab_is_hidden_for_document_without_toc", @@ -46,33 +45,15 @@ CATEGORY_METHODS = { "test_djvu_canvas_fits_page_without_overflow", "test_long_pdf_virtualizes_and_navigates_to_distant_page", "test_oversized_chapter_manifest_and_response_use_resource_limit", - "test_zip_bomb_metadata_is_rejected_before_foliate_parser", "test_image_proxy_failure_recovers_on_manual_retry_without_direct_source", "test_epub_chapters_serve_nested_bundle_with_resources", - "test_foliate_normalizes_legacy_chm_markup_and_keeps_resources", ), "navigation": ( - "test_large_foliate_toc_keeps_a_bounded_dom_window", "test_reader_controls_honor_boundaries_and_keyboard_activation", "test_text_bookmark_uses_progress_excerpt_and_highlights_search", "test_full_text_search_lists_highlighted_snippets_and_jumps", "test_pdf_allows_two_bookmarks_on_one_page_and_restores_offsets", "test_html_bookmark_at_zero_restores_iframe_top", - "test_foliate_navigation_path_dark_links_and_unique_sections", - "test_foliate_rapid_toc_navigation_keeps_latest_destination", - "test_foliate_failed_toc_section_can_retry", - "test_foliate_duplicate_toc_navigation_shares_section_load", - "test_foliate_chapter_buttons_use_continuous_reader_navigation", - "test_foliate_toc_retains_groups_and_chapter_buttons_skip_them", - "test_chm_rebuilt_spine_ignores_previous_asset_positions", - "test_foliate_scroll_updates_toc_on_animation_frame", - "test_foliate_resize_keeps_current_text_anchor", - "test_foliate_virtualizes_distant_sections_and_reloads_them", - "test_foliate_full_search_uses_continuous_reader_navigation", - "test_foliate_bookmark_restores_continuous_section_position", - "test_foliate_progress_slider_uses_continuous_viewport", - "test_foliate_history_saves_structured_section_position", - "test_foliate_history_restores_structured_section_position", "test_actual_store_broadcasts_progress_and_bookmark_updates_between_readers", "test_html_and_markdown_toc_click_navigation", "test_pdf_outline_click_navigates_to_declared_page", @@ -103,11 +84,20 @@ CATEGORY_METHODS = { } +# These cases still exist in the performance module but exercise raw EPUB +# loading through the removed Foliate engine. ZIP limits remain covered by +# tests/reader/security/test_reader_security.js. +RETIRED_FOLIATE_METHODS = { + "test_truncated_epub_reports_source_damage", + "test_zip_bomb_metadata_is_rejected_before_foliate_parser", +} + + def validate_partition(): source = { name for name, value in ReaderPerformanceTest.__dict__.items() if name.startswith("test_") and callable(value) - } + } - RETIRED_FOLIATE_METHODS assigned = [name for methods in CATEGORY_METHODS.values() for name in methods] counts = collections.Counter(assigned) missing = sorted(source - counts.keys()) diff --git a/typings/foliate/view.d.ts b/typings/foliate/view.d.ts deleted file mode 100644 index 192a34ac550fd690787218e29afb8dc849eea294..0000000000000000000000000000000000000000 --- a/typings/foliate/view.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -// The pinned Foliate module registers as a side effect. -// Reader uses the custom-element interface declared in reader-globals.d.ts. -export {}; diff --git a/typings/reader-bindings-strict.d.ts b/typings/reader-bindings-strict.d.ts index caaa48d193ffb10478e6092942e692266fdcce55..fd5fa8a663130d115e4c28426bb1fc263cdd3502 100644 --- a/typings/reader-bindings-strict.d.ts +++ b/typings/reader-bindings-strict.d.ts @@ -40,15 +40,14 @@ export interface ReaderBindingsContext { setZoom(value: string | number, persist?: boolean): void; zoomInput: HTMLInputElement; pageInput: HTMLInputElement; goToPage(value: string | number): unknown; handleReaderKeydown(event: KeyboardEvent): void; turnViewport(direction: number): void; handleReaderOutsideClick(event: MouseEvent): void; headingLocationCache: Disposable | null; - epubRendition: {book?: {isExternal?(url: string): boolean; sections: {linear?: string; resolveHref?(raw: string): string}[]}} | null; - beginReaderNavigation(): number; activateFoliateTocEntry(entry: {href: string}, generation: number): Promise; reportNavigationError(error: unknown, generation: number): void; + beginReaderNavigation(): number; reportNavigationError(error: unknown, generation: number): void; bookmarkRibbon: HTMLElement; closeBookmarkPopover(): void; pendingBookmarkSnapshot: BookmarkSnapshot | null; captureBookmarkSnapshot(): BookmarkSnapshot; currentReaderUrl(): URL; bookmarkInvoker: HTMLElement | null; selectPanel(panel: string | undefined): void; updatePanelState(state: {showingAllBookmarks: boolean}): void; setPanelSearchOpen(button: HTMLButtonElement, open: boolean): void; filterPanel(view: Element): void; progressSaveChain: Promise; progressNotSaved(error: {name: string}): void; disposeReader(): void; handleReaderPositionChange(event: Event): void; notePdfScrollIntent(event: Event): void; installReaderTapSelectionClear(viewport: HTMLElement): void; independentTextCaret(doc: Document, x: number, y: number): Caret | null; pdfSelectionPointer: SelectionPointer | null; correctPdfCrossPageSelection(x: number, y: number, pointer: SelectionPointer): void; pdfSelectionBoundaryUpdate: boolean; - scheduleFoliateScrollSync(): void; updateProgressTools(): void; stopPdfManifestPrefetch(): void; queuePdfManifestPrefetch(): void; + updateProgressTools(): void; stopPdfManifestPrefetch(): void; queuePdfManifestPrefetch(): void; progressTools: HTMLElement; readingProgressSummary: HTMLElement; updateReadingProgressSummary(): void; syncTocTab(): void; progressSeeking: boolean; previousProgressState: ProgressState | null; captureProgressState(): ProgressState | null; isReaderGenerationCurrent(kind: string, generation: number): boolean; flushEpubSeek(): Promise; progressRange: HTMLInputElement; progressPercent: HTMLElement; seekProgress(value: string, user: boolean): void; progressUndo: HTMLElement; restoreProgressState(state: ProgressState | null): unknown; diff --git a/typings/reader-bookmarks-strict.d.ts b/typings/reader-bookmarks-strict.d.ts index 69de5227c8820c09fffebed65a40305813117392..2e3f5fb1f78dcea1d2117710955ac386357a1371 100644 --- a/typings/reader-bookmarks-strict.d.ts +++ b/typings/reader-bookmarks-strict.d.ts @@ -3,7 +3,7 @@ import type { BookmarkEntry, ReaderStoreStrictApi } from './reader-store-strict' declare global { var VoiceOfMLReaderStore: ReaderStoreStrictApi; } -import type { ChapterPosition, FoliatePosition, ProgressState } from './reader-progress-strict'; +import type { ChapterPosition, ProgressState } from './reader-progress-strict'; export interface BookmarkSnapshot extends ProgressState { locator: string; label: string; excerpt: string; progress: number; @@ -15,23 +15,18 @@ export interface BookmarkContext { capability: { mode?: string | null | undefined }; pageAtMarker(): (HTMLElement & { _bookmarkTextItems?: { y: number; text: string }[] }) | null; bookmarkRibbon: HTMLElement; viewport: HTMLElement; content: HTMLElement; excerptFromCaret(doc: Document, root: Node, x: number, y: number): string; - foliateContinuous: boolean; foliateSectionRoot(article: Element): Element | ShadowRoot; readerProgressPercent(): number; navigationState: { currentChapterIndex: number }; beginReaderNavigation(): number; isReaderGenerationCurrent(kind: string, generation: number): boolean; - foliateSectionLoader: ((index: number) => Promise) | null; waitForReader(delay: number, force: boolean): Promise; - foliateScrollAnchors: { invalidate(): void; remember(): void }; - syncFoliateScrollLocation(): void; updateTocCurrentMark(): void; updateProgressTools(): void; scheduleSave(): void; setReaderPanelOpen(open: boolean, focus: boolean): void; reportNavigationError(error: unknown, generation: number): void; - epubBook: { sections?: { linear?: string }[] } | null; panelState: { showingAllBookmarks: boolean }; sourceUrl: string; navigateReader(url: unknown, entry: StoredBookmark): void; restoreFormat(mode: string, entry: StoredBookmark): void; bookmarksAllButton: HTMLButtonElement; emptyPanel(list: Element, message: string): void; filterPanel(panel: Element | null): void; openBookmarkPopover(invoker: HTMLElement, entry: StoredBookmark): void; mediaElement: HTMLMediaElement | null; formatMediaTime(time: number): string; - syncCurrentPageFromMarker(): void; captureFoliateBookmarkPosition(): FoliatePosition | null; + syncCurrentPageFromMarker(): void; captureChapterPosition(): ChapterPosition | null; documentState: { pageCount: number; page: number }; readerPageScrollTop(shell: Element): number; htmlFrame: HTMLIFrameElement | null; bookmarkExcerpt(): string; bookmarkPopover: HTMLElement; bookmarkInertSiblings: Map; diff --git a/typings/reader-chapter-format-strict.d.ts b/typings/reader-chapter-format-strict.d.ts index 19fef336412186cf9a1f668aa9e1a8742cf1f87d..cbd0b7c77a7a24844144b907914c8799d08c0eb1 100644 --- a/typings/reader-chapter-format-strict.d.ts +++ b/typings/reader-chapter-format-strict.d.ts @@ -24,7 +24,7 @@ export interface ChapterFormatContext { chapterSearchConfiguration: import('./reader-chapter-search-strict').Configuration | null; readerRestorationEntry: import('./reader-progress-strict').ProgressState | null; navigationState: { tocEntries: unknown[] }; - foliateScrollAnchors: ReaderScrollAnchorManager; + chapterScrollAnchors: ReaderScrollAnchorManager; assertReaderActive(): void; trustedReaderAssetManifestUrl(url: string): string | null; trustedChapterUrl(path: string, base: string): string | null; diff --git a/typings/reader-controller-strict.d.ts b/typings/reader-controller-strict.d.ts index bf1cc75ee9800ee0e96f8cd3620257a93d86b1f0..3dd8665e847f54bc380503b660d7e749d162cc71 100644 --- a/typings/reader-controller-strict.d.ts +++ b/typings/reader-controller-strict.d.ts @@ -17,9 +17,6 @@ export interface ReaderFormatControllerContext { clearPdfManifestPrefetches(): void; pdfBookSearchClient: Disposable | null; pdfShellWindow: Disposable | null; pdfFirstPagePreload: HTMLElement | null; content: HTMLElement; - foliateSectionObserver: IntersectionObserver | null; foliateSectionVirtualizer: Disposable | null; foliateChapterRepository: Disposable | null; - foliateSectionLoader: unknown; foliateSectionSettler: unknown; - epubRendition: { close?(): Promise | void } | null; epubBook: unknown; htmlFrame: HTMLIFrameElement | null; mediaElement: HTMLMediaElement | null; extension: string; fetchReaderResponse(): Promise; @@ -32,7 +29,7 @@ export interface ReaderFormatControllerContext { loadHtmlDocument(): {response: Promise; engine: Promise}; renderHtml(prepared: {response: Promise; engine: Promise}): unknown; loadChapterManifestDocument(): Promise; renderChapterManifest(prepared: Response): unknown; loadMediaDocument(): Promise; renderMedia(mode: string): unknown; - loadSwfDocument(): Promise; renderSwf(prepared: unknown): unknown; renderFoliate(): Promise; + loadSwfDocument(): Promise; renderSwf(prepared: unknown): unknown; releasePdfWorker?: (() => void) | null; formatAdapters: { register(mode: string, adapter: Adapter): unknown; activate(mode: string | null | undefined): unknown; dispose(): unknown; readonly active: Adapter | null }; restoreFormat(mode: string, entry: unknown, generation: number): unknown; disposeFormatResources(mode: string): void; @@ -48,9 +45,9 @@ export interface ReaderFormatControllerContext { syncCapabilityControls(): void; downloadButton: Element; documentState: { title: string }; readerDownloadUrl(title: string, url: string): string; fail(message: string, code: string): void; params: URLSearchParams; - foliateContinuous: boolean; loadReaderRestoration(): Promise; readerRestorationPromise: Promise | null; + loadReaderRestoration(): Promise; readerRestorationPromise: Promise | null; awaitReader(value: T | PromiseLike): Promise>; - applyInitialRestoration(entry: unknown, generation: number): Promise; initialReaderTargetSection: unknown; + applyInitialRestoration(entry: unknown, generation: number): Promise; setReaderPhase(phase: string): boolean; updateDocumentState(state: { restorationReady?: boolean; page?: number; pageCount?: number }): void; restorationFailed: boolean; scheduleSave(): void; readerResources: Set<() => void>; markReaderContentReady(): void; isReaderGenerationCurrent(kind: string, generation: number): boolean; diff --git a/typings/reader-foliate-format-strict.d.ts b/typings/reader-foliate-format-strict.d.ts deleted file mode 100644 index 06793a7dc93bf2d27429dc0b68d4aa14f7a1974c..0000000000000000000000000000000000000000 --- a/typings/reader-foliate-format-strict.d.ts +++ /dev/null @@ -1,69 +0,0 @@ -export interface FoliateAnchorDocument { - getElementById(id: string): Element | null; - querySelector(selector: string): Element | null; -} -export type FoliateAnchor = (document: FoliateAnchorDocument) => Element | null; -export interface FoliateSection { - linear?: string; - createDocument(): Promise; - resolveResourceHref?(href: string): string; - resolveHref?(href: string): string; -} -export interface FoliateTarget { index: number; anchor?: FoliateAnchor | null } -export interface FoliateTocItem { href?: string; label?: string; subitems?: FoliateTocItem[] } -export interface FoliateBook { - sections: FoliateSection[]; - toc?: FoliateTocItem[]; - resolveHref(href: string): Promise; -} -export interface FoliateView extends HTMLElement, ReaderSearchBackends.Rendition { book: FoliateBook; open(file: File): Promise; goTo(href: string): Promise; close(): void } -export interface FoliateTocEntry { - label: string; href: string; depth: number; group: boolean; activate(): Promise; - sectionIndex?: number; fragment?: string; anchor?: FoliateAnchor | null; target?: Element | null; -} -export type SearchAnchor = (source: Document) => Range | null; -export type SearchSelection = {node: Text; start: number; end: number}; -export type FoliateArticle = HTMLElement & { _resolveSearchAnchor?: ((anchor: SearchAnchor) => SearchSelection[] | null) | null }; -export type FoliateLoader = ((index: number) => Promise) & {refresh(): void}; -export interface FoliateFormatContext { - content: HTMLElement; viewport: HTMLElement; status: HTMLElement; loadingIndicator: Element; - sourceUrl: string; extension: string; readerTheme: string; - readerAbortController: AbortController; foliateContinuous: boolean; - navigationState: {tocEntries: unknown[]; currentChapterIndex: number}; - foliateWindowFrame: number; foliateScrollFrame: number; - foliateScrollAnchors: ReaderScrollAnchorManager; - foliateSectionObserver: IntersectionObserver | null; - foliateSectionVirtualizer: ReturnType | null; - foliateSectionLoader: FoliateLoader | null; - foliateSectionSettler: (() => Promise) | null; - foliateChapterRepository: ReturnType | null; - FOLIATE_PREFETCH_MARGIN: number; FOLIATE_LOADED_SECTION_LIMIT: number; - initialReaderTargetSection: number | null; - readerRestorationEntry: {foliateSection?: number | null} | null; - epubRendition: FoliateView | null; epubBook: FoliateBook | null; - readerRuntime: {track(resource: T): T}; - foliateSectionRoot(article: Element): Element | ShadowRoot; - foliateSectionQuery(article: Element, selector: string): Element | null; - refreshFoliateWindow(): void; syncFoliateScrollLocation(): void; trimFoliateSections(): void; - scheduleFoliateWindowRefresh(): void; scheduleFoliateScrollSync(): void; - updateNavigationState(state: {currentChapterIndex: number}): void; - updateTocCurrentMark(): void; updateProgressTools(): void; scheduleSave(): void; - beginReaderNavigation(): number; isReaderGenerationCurrent(kind: string, generation: number): boolean; - waitForReader(delay?: number, background?: boolean): Promise; - alignReaderDestination(destination: Element, offset: number): unknown; - holdReaderDestination(destination: Element, offset: number): void; setReaderPanelOpen(open: boolean, focus: boolean): void; - sanitizeEpubDocument(doc: Document, options: {keepBlobImports: boolean}): Document; - cloneFoliateDocument(source: Document): {doc: Document; sourceNodes: WeakMap}; - foliateSearchAnchor(source: Document, nodes: WeakMap, body: Element, rendered: Element): (anchor: SearchAnchor) => SearchSelection[] | null; - assertReaderActive(): void; awaitReader(value: T | PromiseLike, signal?: AbortSignal): Promise>; - rewriteFoliateResources(doc: Document, section: FoliateSection): void; - sanitizeFoliateStyles(nodes: Iterable): Promise; - epubContentBody(doc: Document): HTMLElement; - createFoliateSection(section: FoliateSection, index: number, signal?: AbortSignal, priority?: 'high' | 'low'): Promise; - setupFoliateWindow(stream: HTMLElement, sections: FoliateSection[]): void; - foliateTocEntries(view: FoliateView, sections: FoliateSection[]): Promise; - trackReaderResource(cleanup: () => void): unknown; - prepareReaderDocument(tasks: Promise[]): {response: Promise; engines: Promise}; - readPreparedBytes(response: Promise, engines: Promise, limit: number): Promise>; - getInitialReaderRestoration(): Promise; markReaderContentReady(): void; setToc(entries: FoliateTocEntry[]): void; -} diff --git a/typings/reader-globals.d.ts b/typings/reader-globals.d.ts index 99211bd250d9df4ce240afb90458b842fb26df68..121e3d69fd93bf635a8bb01f57685437b6857241 100644 --- a/typings/reader-globals.d.ts +++ b/typings/reader-globals.d.ts @@ -253,7 +253,6 @@ interface ReaderSecurityApi { interface ReaderResourcesApi { readonly vendors: Record; - readonly foliateVendors: Record; readonly readerFiles: readonly string[]; readonly readerComponentFiles: readonly string[]; vendorUrl(name: string, base: string): string; @@ -264,7 +263,7 @@ interface ReaderResourcesApi { djvuSelectedAssets(base: string): string[]; djvuSupportsSIMD(): boolean; ruffleAssets(base: string): string[]; - engineAssets(extension: string, base: string, foliateSuffix?: string, workerWrapper?: string): string[]; + engineAssets(extension: string, base: string, unusedSuffix?: string, workerWrapper?: string): string[]; } interface ReaderContractApi { @@ -313,7 +312,7 @@ interface ReaderRuntimeState { navigation: {tocEntries: import('./reader-toc-strict').TocEntry[]; currentChapterIndex: number}; search: {query: string; results: unknown[]; index: number}; panel: {open: boolean; selected: string; showingAllBookmarks: boolean; editingBookmark: import('./reader-store-strict').BookmarkEntry | null}; - formats: {active: unknown; pdf: Record; foliate: Record; html: Record; media: Record; [key: string]: unknown}; + formats: {active: unknown; pdf: Record; html: Record; media: Record; [key: string]: unknown}; capability: ReaderRuntimeCapability | null; } type ReaderRuntimeDisposable = (() => void) | {dispose?: () => void}; @@ -327,7 +326,6 @@ type ReaderRuntimeFormatSnapshot = Readonly>; interface ReaderRuntimeFormatsSnapshot { readonly active: ReaderRuntimeFormatSnapshot; readonly pdf: ReaderRuntimeFormatSnapshot; - readonly foliate: ReaderRuntimeFormatSnapshot; readonly html: ReaderRuntimeFormatSnapshot; readonly media: ReaderRuntimeFormatSnapshot; readonly [key: string]: ReaderRuntimeFormatSnapshot | undefined; @@ -514,13 +512,6 @@ declare var VoiceOfMLSearchSession: SearchSessionApi; declare var VoiceOfMLDownloadController: DownloadControllerApi; declare var VoiceOfMLReaderNavigation: SearchReaderNavigationApi; -// The imported module registers this custom element; it does not export the -// book to our code. The concrete sections are provided by the chosen engine. -interface FoliateViewElement extends HTMLElement { - open(file: File): Promise; - book: { sections: Array<{linear?: string}> }; -} -interface HTMLElementTagNameMap { "foliate-view": FoliateViewElement } declare var DOMPurify: { sanitize(input: string, options: {RETURN_DOM_FRAGMENT: true; [key: string]: unknown}): DocumentFragment; sanitize(input: string, options?: object): string; diff --git a/typings/reader-progress-strict.d.ts b/typings/reader-progress-strict.d.ts index 8c5bcc36b804109d84392a46eefd79140747f49e..da033a1405b5d99494bcf56bdb426ddfe3d1c37e 100644 --- a/typings/reader-progress-strict.d.ts +++ b/typings/reader-progress-strict.d.ts @@ -14,7 +14,6 @@ export interface ProgressState { chapterManifest?: string; chapterOffset?: number; } -export interface FoliatePosition extends ProgressState { foliateSection: number; foliateOffset: number; foliateTocIndex: number } export interface ChapterPosition extends ProgressState { chapterIndex: number; chapterManifest: string; chapterOffset: number } export interface ProgressContext { readerLifecycle: { disposed: boolean }; @@ -27,7 +26,7 @@ export interface ProgressContext { mediaElement: (HTMLMediaElement & { _readerSourceRetry?: boolean }) | null; syncCurrentPageFromMarker(): void; content: HTMLElement; viewport: HTMLElement; readerPageScrollTop(shell: Element): number; htmlFrame: HTMLIFrameElement | null; - currentReaderUrl(): URL; captureFoliateBookmarkPosition(): FoliatePosition | null; + currentReaderUrl(): URL; captureChapterPosition(): ChapterPosition | null; extension: string; showDownloadFeedback(message: string, duration: number): void; lastSavedProgress: string; progressSaveChain: Promise; @@ -36,8 +35,7 @@ export interface ProgressContext { params: URLSearchParams; restorationFailed: boolean; readerRestorationPromise: Promise | null; readerRestorationLoaded: boolean; readerRestorationEntry: ProgressState | null; awaitReader(promise: Promise): Promise; - waitForReader(delay?: number): Promise; foliateContinuous: boolean; - epubBook: { sections?: { linear?: string }[] } | null; bookmarkRibbon: HTMLElement; + waitForReader(delay?: number): Promise; bookmarkRibbon: HTMLElement; pageNavigationLockUntil: number; pageAtMarker(): HTMLElement | null; updateDocumentState(state: { page?: number; restoredEntry?: ProgressState | null }): void; pageInput: HTMLInputElement; updateTocCurrentMark(): void; updateProgressTools(): void; @@ -45,7 +43,6 @@ export interface ProgressContext { beginReaderNavigation(): number; isReaderGenerationCurrent(kind: string, generation: number): boolean; restoreChapterPosition(entry: ProgressState, generation: number, progressFraction?: number): Promise; restoreProgressState(entry: ProgressState, generation: number): Promise; - restoreFoliateBookmarkPosition(entry: ProgressState, generation: number): Promise; goToPage(page: number, generation: number): Promise; consumeBookmarkHandoff(entry: ProgressState): void; reportNavigationError(error: unknown, generation: number): void; formatAdapters: { active: { restore(entry: ProgressState, generation: number): unknown } | null }; @@ -57,7 +54,7 @@ export interface ProgressContext { previousProgressState: ProgressState | null; updateReadingProgressSummary(): void; placeReadingProgress(): void; trackReaderResource(cleanup: () => void): () => void; readerAbortError(): Error; epubSeekFrame: number; epubSeekTarget: { percent: number; generation: number } | null; - epubSeekPromise: Promise; seekFoliateProgress(percent: number, generation: number): Promise; + epubSeekPromise: Promise; captureProgressState(): ProgressState | null; chapterManifestLoader: import('./reader-chapter-format-strict').ChapterLoader | null; navigateTocEntry(index: number, options: { closePanel: boolean }): Promise; diff --git a/typings/reader-search-backends-strict.d.ts b/typings/reader-search-backends-strict.d.ts index 766dad1fc9ba05c8a8468c07ae7fd6acdf19af39..0700f116499a71b87d497ec11e6c4627ce5c41de 100644 --- a/typings/reader-search-backends-strict.d.ts +++ b/typings/reader-search-backends-strict.d.ts @@ -2,11 +2,10 @@ declare namespace ReaderSearchBackends { type GenerationKind = "search" | "navigation"; interface Snippet { text: string; matchStart: number; matchLength: number; prefix: string; suffix: string } interface ChapterResult { chapterIndex: number; start: number; length: number; location: string; snippet: Snippet } - interface FoliateResult { location: string; cfi: string; occurrence: number; snippet: Snippet } interface DomResult { target?: HTMLElement; location: string; snippet: Snippet; activate(generation?: number): Promise } interface DomTarget { target: HTMLElement | undefined } interface PdfResult { page: number; start: number; length: number; boxes: { box: number[]; block?: unknown; precision?: string }[]; snippet: Snippet; textGeneration?: string } - type Result = FoliateResult | DomResult; + type Result = DomResult; interface Page { total: number; offset: number; pageSize: number; results: T[] } interface ChapterProgress extends Page { scanned: number; chapters: number } interface ChapterConfiguration { chapters: { index: number; path: string }[]; index: { url: string; path: string; bytes: number; sha256: string; text_profile?: string } } @@ -23,14 +22,6 @@ declare namespace ReaderSearchBackends { createChapterSearch(configuration: ChapterConfiguration): ChapterClient; chapterTextMap(roots: (Node | null)[], textProfile?: string): { text: string; parts(start: number, end: number, body: Node): TextPart[] }; } - interface FoliateItem { cfi: string; excerpt?: { pre: string; match: string; post: string } } - interface FoliateGroup { index: number; count: number; label: string; subitems: FoliateItem[] } - type Anchor = (source: Document) => Range; - interface FoliateNode extends HTMLElement { _resolveSearchAnchor?: ((anchor: Anchor) => TextPart[] | null) | null } - interface Rendition { - search(options: { query: string; index?: number; offset?: number; limit: number; lean: boolean; current: () => boolean }): AsyncIterable; - resolveNavigation?(cfi: string): Promise<{ index: number; anchor?: Anchor } | null>; - } interface Context { readerRuntime: { update(kind: "search", patch: SearchPatch): unknown; currentGeneration(kind: GenerationKind): number }; isReaderGenerationCurrent(kind: GenerationKind, generation: number): boolean; @@ -46,16 +37,12 @@ declare namespace ReaderSearchBackends { chapterManifestLoader: ((index: number) => Promise) | null; clearFullSearchMarks(): void; highlightTextParts(parts: TextPart[]): HTMLElement[]; - foliateScrollAnchors: { invalidate(): void; remember(): void }; + chapterScrollAnchors: { invalidate(): void; remember(): void }; navigationState: { tocEntries: { chapterIndex?: number; sectionIndex?: number }[] }; updateNavigationState(patch: { currentChapterIndex: number }): unknown; updateTocCurrentMark(): void; updateProgressTools(): void; scheduleSave(): void; - epubRendition: Rendition | null; - epubBook: { sections?: { linear?: string }[] } | null; - foliateSectionLoader: ((index: number) => Promise) | null; - foliateSectionRoot(node: FoliateNode): Element | ShadowRoot; viewport: HTMLElement; searchState: { query: string }; capability: { mode?: string | null | undefined }; @@ -69,7 +56,6 @@ declare namespace ReaderSearchBackends { fullSearchDomMatches(root: HTMLElement, fallback: string, query: string, generation: number, progressive?: boolean): Promise; fullSearchPdfMatches(query: string, generation: number): Promise; searchConcentratedPdf(query: string, generation: number): Promise; - fullSearchFoliateMatches(query: string, generation: number): Promise; searchChapterBook(query: string, generation: number): Promise; } interface SearchPatch { results?: Result[]; index?: number } diff --git a/typings/reader-search-controller-strict.d.ts b/typings/reader-search-controller-strict.d.ts index d98189424d3bbbdff7a0c7970cd0671dbfabcc92..0240f4b28f227bcf58ee5237ea389487cde2c320 100644 --- a/typings/reader-search-controller-strict.d.ts +++ b/typings/reader-search-controller-strict.d.ts @@ -1,8 +1,7 @@ declare namespace ReaderSearchController { interface Snippet { text: string; matchStart: number; matchLength: number; prefix: string; suffix: string } interface DomResult { location: string; snippet: Snippet; cfi?: undefined; target?: HTMLElement; activate(generation?: number): Promise } - interface FoliateResult { location: string; snippet: Snippet; cfi: string; occurrence: number } - type Result = DomResult | FoliateResult; + type Result = DomResult; interface ChapterResult { location: string; snippet: Snippet; chapterIndex: number; start: number; length: number } interface Page { total: number; offset: number; pageSize: number; results: T[] } interface State { diff --git a/typings/reader-speech-strict.d.ts b/typings/reader-speech-strict.d.ts index 1ebea3108d274d2764e9696ca3a2ba556ecc6df5..ec59057e805fca9652ba15dfe62278809a35e2cd 100644 --- a/typings/reader-speech-strict.d.ts +++ b/typings/reader-speech-strict.d.ts @@ -1,13 +1,9 @@ -import type { FoliateSection } from './reader-foliate-format-strict'; import type { OcrPayload, PdfPage, TextContent, TextItem, TextTask } from './reader-pdf-text-runtime-strict'; export interface SpeechContext { capability: { mode?: string | null } | null; sourceUrl: string; contentUrl: string; content: HTMLElement; viewport: HTMLElement; htmlFrame: HTMLIFrameElement | null; - epubBook: { sections: FoliateSection[] } | null; - foliateSectionRoot(article: Element): Element | ShadowRoot; - foliateSectionLoader: ((index: number) => Promise) | null; chapterManifestLoader: (((index: number) => Promise) & { count: number }) | null; documentState: { pageCount: number; page: number }; ocrManifestUrl: string; pdfOcrManifest: object | null; diff --git a/typings/reader-toc-strict.d.ts b/typings/reader-toc-strict.d.ts index efa868c660fd4d0f32c486ffc7e7a538a1959c7f..c2d894aecde683cae16b0ad625fcc8cbcde05dde 100644 --- a/typings/reader-toc-strict.d.ts +++ b/typings/reader-toc-strict.d.ts @@ -42,8 +42,6 @@ export interface TocContext { updateNavigationState(patch: Partial<{ tocEntries: TocEntry[]; currentChapterIndex: number }>): unknown; updateTocCurrentMark(): void; beginReaderNavigation(): number; - foliateContinuous: boolean; - activateFoliateTocEntry(entry: TocEntry, generation: number, options: { closePanel: boolean }): Promise; isReaderGenerationCurrent(kind: string, generation: number): boolean; updateProgressTools(): void; setReaderPanelOpen(open: boolean, focus?: boolean): void; diff --git a/typings/reader-ui-component-strict.d.ts b/typings/reader-ui-component-strict.d.ts index 334fd34021158b5f1ebfd070006af36291350456..e5b731cef8478b3b8252e01b7f3394abd6c095e7 100644 --- a/typings/reader-ui-component-strict.d.ts +++ b/typings/reader-ui-component-strict.d.ts @@ -27,7 +27,7 @@ export interface ReaderUiContext { }; pageInverted: boolean; pageInvertToggle: HTMLElement; - foliateScrollAnchors: { capture(): ReaderUiScrollAnchor | null; restore(anchor: ReaderUiScrollAnchor | null): boolean }; + chapterScrollAnchors: { capture(): ReaderUiScrollAnchor | null; restore(anchor: ReaderUiScrollAnchor | null): boolean }; themeAnimationTimer: number; readerTheme: string; readerThemeToggle: HTMLElement; diff --git a/typings/reader-ui-strict.d.ts b/typings/reader-ui-strict.d.ts index 606447336e8e0997a27ff542fcab20309a3256b9..5946facdc4542811d9f602e24a91b957a0129bca 100644 --- a/typings/reader-ui-strict.d.ts +++ b/typings/reader-ui-strict.d.ts @@ -1,7 +1,7 @@ export interface NavigationContext { cancelReaderDestinationHold?: () => void; epubSeekFrame: number; - foliateScrollAnchors: { invalidate(): void; remember(): void }; + chapterScrollAnchors: { invalidate(): void; remember(): void }; nextReaderGeneration(kind: string): number; returnHistoryKey: string | null; folderNavigationTarget: URL | null; @@ -43,7 +43,6 @@ export interface NavigationContext { pdfScrollDirection: number; scheduleVisiblePdfRenderReconciliation?: (immediate: boolean) => void; scheduleMarkerSync(): void; - scheduleFoliateScrollSync(): void; saveProgress(): Promise; pdfUserHasScrolled: boolean; trackReaderResource(cleanup: () => unknown): () => boolean;