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 @@
-ZGlmZiAtLWdpdCBhL2VwdWIuanMgYi9lcHViLmpzCmluZGV4IGU4YmQ3MDMuLmFlYWNlNDYgMTAwNjQ0Ci0tLSBhL2VwdWIuanMKKysrIGIvZXB1Yi5qcwpAQCAtMzUwLDcgKzM1MCw3IEBAIGNvbnN0IHBhcnNlTkNYID0gKGRvYywgcmVzb2x2ZSA9IGYgPT4gZikgPT4gewogICAgICAgICBjb25zdCAkbGFiZWwgPSAkKGVsLCAnbmF2TGFiZWwnKQogICAgICAgICBjb25zdCAkY29udGVudCA9ICQoZWwsICdjb250ZW50JykKICAgICAgICAgY29uc3QgbGFiZWwgPSBnZXRFbGVtZW50VGV4dCgkbGFiZWwpCi0gICAgICAgIGNvbnN0IGhyZWYgPSByZXNvbHZlSHJlZigkY29udGVudC5nZXRBdHRyaWJ1dGUoJ3NyYycpKQorICAgICAgICBjb25zdCBocmVmID0gcmVzb2x2ZUhyZWYoJGNvbnRlbnQ/LmdldEF0dHJpYnV0ZSgnc3JjJykpCiAgICAgICAgIGlmIChlbC5sb2NhbE5hbWUgPT09ICduYXZQb2ludCcpIHsKICAgICAgICAgICAgIGNvbnN0IGVscyA9ICQkKGVsLCAnbmF2UG9pbnQnKQogICAgICAgICAgICAgcmV0dXJuIHsgbGFiZWwsIGhyZWYsIHN1Yml0ZW1zOiBlbHMubGVuZ3RoID8gZWxzLm1hcChwYXJzZUl0ZW0pIDogbnVsbCB9CkBAIC02NDIsNiArNjQyLDcgQEAgY2xhc3MgUmVzb3VyY2VzIHsKICAgICAgICAgdGhpcy5tYW5pZmVzdCA9ICQkKCRtYW5pZmVzdCwgJ2l0ZW0nKQogICAgICAgICAgICAgLm1hcChnZXRBdHRyaWJ1dGVzKCdocmVmJywgJ2lkJywgJ21lZGlhLXR5cGUnLCAncHJvcGVydGllcycsICdtZWRpYS1vdmVybGF5JykpCiAgICAgICAgICAgICAubWFwKGl0ZW0gPT4geworICAgICAgICAgICAgICAgIGl0ZW0ucmF3SHJlZiA9IGl0ZW0uaHJlZgogICAgICAgICAgICAgICAgIGl0ZW0uaHJlZiA9IHJlc29sdmVIcmVmKGl0ZW0uaHJlZikKICAgICAgICAgICAgICAgICBpdGVtLnByb3BlcnRpZXMgPSBpdGVtLnByb3BlcnRpZXM/LnNwbGl0KC9ccy8pCiAgICAgICAgICAgICAgICAgcmV0dXJuIGl0ZW0KQEAgLTk5Myw2ICs5OTQsMTQgQEAgJHtkb2MucXVlcnlTZWxlY3RvcigncGFyc2VyZXJyb3InKS5pbm5lclRleHR9YCkKICAgICAgICAgICAgICAgICBsaW5lYXIsCiAgICAgICAgICAgICAgICAgcGFnZVNwcmVhZDogZ2V0UGFnZVNwcmVhZChwcm9wZXJ0aWVzKSwKICAgICAgICAgICAgICAgICByZXNvbHZlSHJlZjogaHJlZiA9PiByZXNvbHZlVVJMKGhyZWYsIGl0ZW0uaHJlZiksCisgICAgICAgICAgICAgICAgcmVzb2x2ZVJlc291cmNlSHJlZjogaHJlZiA9PiB7CisgICAgICAgICAgICAgICAgICAgIC8vIFJlc29sdmUgcmF3IFVSSXMgYmVmb3JlIGRlY29kaW5nIG9uY2UgdG8gYSBsaXRlcmFsIFpJUCBtZW1iZXIgbmFtZS4KKyAgICAgICAgICAgICAgICAgICAgY29uc3Qgcm9vdCA9ICdodHRwczovL2ludmFsaWQuaW52YWxpZC8nCisgICAgICAgICAgICAgICAgICAgIGNvbnN0IGJhc2UgPSBuZXcgVVJMKGl0ZW0ucmF3SHJlZiwgcm9vdCArI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29sZS53YXJuKGUpCisgICAgICAgIH0KKyAgICAgICAgY29uc3Qgb2Zmc2V0cyA9IFtdCisgICAgICAgIGNvbnN0IG1hcE5DWCA9IGl0ZW1zID0+IGl0ZW1zPy5tYXAoKHsgbGFiZWwsIG9mZnNldCwgY2hpbGRyZW4gfSkgPT4geworICAgICAgICAgICAgaWYgKCFOdW1iZXIuaXNTYWZlSW50ZWdlcihvZmZzZXQpIHx8IG9mZnNldCA8IDAgfHwgb2Zmc2V0ID49IHRvdGFsTGVuZ3RoKQorICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcignSW52YWxpZCBNT0JJIG5hdmlnYXRpb24gb2Zmc2V0JykKKyAgICAgICAgICAgIG9mZnNldHMucHVzaChTdHJpbmcob2Zmc2V0KSkKKyAgICAgICAgICAgIHJldHVybiB7IGxhYmVsOiB1bmVzY2FwZUhUTUwobGFiZWwpLCBocmVmOiBgZmlsZXBvczoke29mZnNldH1gLAorICAgICAgICAgICAgICAgIHN1Yml0ZW1zOiBtYXBOQ1goY2hpbGRyZW4pIH0KKyAgICAgICAgfSkKKyAgICAgICAgdHJ5IHsKKyAgICAgICAgICAgIHRoaXMudG9jID0gbWFwTkNYKG5jeCkKKyAgICAgICAgfSBjYXRjaCAoZSkgeworICAgICAgICAgICAgY29uc29sZS53YXJuKGUpCisgICAgICAgIH0KKyAgICAgICAgdGhpcy4jZmlsZXBvc0xpc3QgPSBbLi4ubmV3IFNldChbCisgICAgICAgICAgICAuLi5BcnJheS5mcm9tKHN0ci5tYXRjaEFsbChmaWxlcG9zUmVnZXgpLCBtID0+IG1bMV0pLCAuLi5vZmZzZXRzXSldCiAgICAgICAgICAgICAubWFwKGZpbGVwb3MgPT4gKHsgZmlsZXBvcywgbnVtYmVyOiBOdW1iZXIoZmlsZXBvcykgfSkpCiAgICAgICAgICAgICAuc29ydCgoYSwgYikgPT4gYS5udW1iZXIgLSBiLm51bWJlcikKIApAQCAtNzMzLDcgKzc1Miw3IEBAIGNsYXNz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mxheW91dC5zZWxlY3QoJ3Njcm9sbGVkJykKICAgICB9CiAgICAgYXN5bmMgb3BlbihmaWxlKSB7CiAgICAgICAgIHRoaXMudmlldyA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2ZvbGlhdGUtdmlldycpCiAgICAgICAgIGRvY3VtZW50LmJvZHkuYXBwZW5kKHRoaXMudmlldykKICAgICAgICAgYXdhaXQgdGhpcy52aWV3Lm9wZW4oZmlsZSkKKyAgICAgICAgdGhpcy52aWV3LnJlbmRlcmVyLnNldEF0dHJpYnV0ZSgnZmxvdycsICdzY3JvbGxlZCcpCisgICAgICAgIGxldCBtb3ZpbmcgPSBmYWxzZQorICAgICAgICBsZXQgcHJldmlvdXNTdGFydCA9IG51bGwKKyAgICAgICAgY29uc3QgbW92ZVNlY3Rpb24gPSBhc3luYyBkaXJlY3Rpb24gPT4geworICAgICAgICAgICAgY29uc3QgcmVuZGVyZXIgPSB0aGlzLnZpZXcucmVuZGVyZXIKKyAgICAgICAgICAgIGlmIChtb3ZpbmcgfHwgIXJlbmRlcmVyLnNjcm9sbGVkIHx8ICFkaXJlY3Rpb24pIHJldHVybgorICAgICAgICAgICAgY29uc3Qgc3RhcnQgPSByZW5kZXJlci5zdGFydAorICAgICAgICAgICAgY29uc3QgZW5kID0gcmVuZGVyZXIuZW5kCisgICAgICAgICAgICBjb25zdCB2aWV3U2l6ZSA9IHJlbmRlcmVyLnZpZXdTaXplCisgICAgICAgICAgICBpZiAoZGlyZWN0aW9uID4gMCAmJiBlbmQgPCB2aWV3U2l6ZSAtIDIpIHJldHVybgorICAgICAgICAgICAgaWYgKGRpcmVjdGlvbiA8IDAgJiYgc3RhcnQgPiAyKSByZXR1cm4KKyAgICAgICAgICAgIG1vdmluZyA9IHRydWUKKyAgICAgICAgICAgIHRyeSB7CisgICAgICAgICAgICAgICAgaWYgKGRpcmVjdGlvbiA+IDApIGF3YWl0IHRoaXMudmlldy5uZXh0KCkKKyAgICAgICAgICAgICAgICBlbHNlIGF3YWl0IHRoaXMudmlldy5wcmV2KCkKKyAgICAgICAgICAgIH0gZmluYWxseSB7CisgICAgICAgICAgICAgICAgbW92aW5nID0gZmFsc2UKKyAgICAgICAgICAgICAgICBwcmV2aW91c1N0YXJ0ID0gbnVsbAorICAgICAgICAgICAgfQorICAgICAgICB9CisgICAgICAgIGNvbnN0IG1vdmVBY3Jvc3NTZWN0aW9ucyA9ICgpID0+IHsKKyAgICAgICAgICAgIGNvbnN0IHJlbmRlcmVyID0gdGhpcy52aWV3LnJlbmRlcmVyCisgICAgICAgICAgICBjb25zdCBzdGFydCA9IHJlbmRlcmVyLnN0YXJ0CisgICAgICAgICAgICBjb25zdCBkaXJlY3Rpb24gPSBwcmV2aW91c1N0YXJ0ID09IG51bGwgPyAwIDogc3RhcnQgLSBwcmV2aW91c1N0YXJ0CisgICAgICAgICAgICBwcmV2aW91c1N0YXJ0ID0gc3RhcnQKKyAgICAgICAgICAgIG1vdmVTZWN0aW9uKGRpcmVjdGlvbikKKyAgICAgICAgfQorICAgICAgICBsZXQgYm91bmRDb250YWluZXIgPSBudWxsCisgICAgICAgIGNvbnN0IGJpbmRTY3JvbGxDb250YWluZXIgPSAoKSA9PiB7CisgICAgICAgICAgICBjb25zdCBjb250YWluZXIgPSB0aGlzLnZpZXcucmVuZGVyZXIuc2hhZG93Um9vdD8ucXVlcnlTZWxlY3RvcignI2NvbnRhaW5lcicpIHx8IHRoaXMudmlldy5yZW5kZXJlcgorICAgICAgICAgICAgaWYgKGNvbnRhaW5lciA9PT0gYm91bmRDb250YWluZXIpIHJldHVybgorICAgICAgICAgICAgYm91bmRDb250YWluZXIgPSBjb250YWluZXIKKyAgICAgICAgICAgIGNvbnRhaW5lci5hZGRFdmVudExpc3RlbmVyKCdzY3JvbGwnLCBtb3ZlQWNyb3NzU2VjdGlvbnMpCisgICAgICAgICAgICBjb250YWluZXIuYWRkRXZlbnRMaXN0ZW5lcignd2hlZWwnLCBldmVudCA9PiB7CisgICAgICAgICA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WQuYmluZCh0aGlzKSkKICAgICAgICAgdGhpcy52aWV3LmFkZEV2ZW50TGlzdGVuZXIoJ3JlbG9jYXRlJywgdGhpcy4jb25SZWxvY2F0ZS5iaW5kKHRoaXMpKQogCkBAIC0xMTgsNyArMTY4LDEwIEBAIGNsYXNzIFJlYWRlciB7CiAgICAgICAgICAgICB9KQogICAgICAgICB9KQogICAgICAgICB0aGlzLnZpZXcucmVuZGVyZXIuc2V0U3R5bGVzPy4oZ2V0Q1NTKHRoaXMuc3R5bGUpKQotICAgICAgICB0aGlzLnZpZXcucmVuZGVyZXIubmV4dCgpCisgICAgICAgIGF3YWl0IFByb21pc2UucmFjZShbCisgICAgICAgICAgICB0aGlzLnZpZXcuZ29UbygwKSwKKyAgICAgICAgICAgIG5ldyBQcm9taXNlKHJlc29sdmUgPT4gc2V0VGltZW91dChyZXNvbHZlLCAzMDAwKSksCisgICAgICAgIF0pCiAKICAgICAgICAgJCgnI2hlYWRlci1iYXInKS5zdHlsZS52aXNpYmlsaXR5ID0gJ3Zpc2libGUnCiAgICAgICAgICQoJyNuYXYtYmFyJykuc3R5bGUudmlzaWJpbGl0eSA9ICd2aXNpYmxlJwpAQCAtMTUxLDYgKzIwNCwxNSBAQCBjbGFzcyBSZWFkZXIgewogICAgICAgICAgICAgICAgIHRoaXMuY2xvc2VTaWRlQmFyKCkKICAgICAgICAgICAgIH0pCiAgICAgICAgICAgICAkKCcjdG9jLXZpZXcnKS5hcHBlbmQodGhpcy4jdG9jVmlldy5lbGVtZW50KQorICAgICAgICAgICAgY29uc3QgZW50cmllcyA9IFtdCisgICAgICAgICAgICBjb25zdCBhcHBlbmQgPSAoaXRlbXMsIGRlcHRoID0gMCkgPT4geworICAgICAgICAgICAgICAgIGZvciAoY29uc3QgaXRlbSBvZiBpdGVtcyB8fCBbXSkgeworICAgICAgICAgICAgICAgICAgICBlbnRyaWVzLnB1c2goeyBsYWJlbDogaXRlbS5sYWJlbCB8fCAn5pyq5ZG95ZCN56ug6IqC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gICAgICAgICAgICAgIGNvbnN0IHsgZG9jIH0gPSB0aGlzLnJlbmRlcmVyLmdldENvbnRlbnRzKCkKLSAgICAgICAgICAgICAgICAgICAgICAgICAgICAuZmluZCh4ID0+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'- 第一卷
- 第二卷
- ', 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('
- Supplement target
uniqueSupplementNeedle
- Back
-
-
-
-