vomebook commited on
Commit
1dc63a4
·
1 Parent(s): 46e3e7f

Remove Foliate runtime and simplify Reader and search paths

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +0 -1
  2. Dockerfile +1 -4
  3. backend/search/application/cached.py +4 -2
  4. config/types/jsconfig.check.json +0 -6
  5. config/types/jsconfig.strict.json +1 -4
  6. eslint.config.mjs +1 -1
  7. ruff.toml +1 -1
  8. scripts/build/check_reader_release.mjs +4 -21
  9. scripts/build/copy_reader_vendor.mjs +3 -24
  10. scripts/build/fetch_foliate_reader.mjs +0 -157
  11. scripts/build/foliate-local.patch.b64 +0 -1
  12. scripts/check_markup.mjs +1 -1
  13. scripts/reader/check_reader_lifecycle_coverage.mjs +1 -1
  14. scripts/reader/check_reader_media_coverage.mjs +1 -1
  15. static/app.js +1 -2
  16. static/reader-resources.js +14 -60
  17. static/reader.css +3 -86
  18. static/reader.js +10 -76
  19. static/reader/core/reader-bindings.mjs +1 -40
  20. static/reader/core/reader-contract.js +0 -14
  21. static/reader/core/reader-lifecycle.mjs +4 -8
  22. static/reader/core/reader-runtime.js +1 -1
  23. static/reader/core/reader-shared-content.mjs +51 -0
  24. static/reader/formats/reader-chapter-format.mjs +13 -13
  25. static/reader/formats/reader-foliate-format.mjs +0 -773
  26. static/reader/formats/reader-format-controller.mjs +2 -42
  27. static/reader/formats/reader-html-format.mjs +0 -97
  28. static/reader/pdf/reader-engine-preload.js +1 -1
  29. static/reader/reader-components.mjs +0 -1
  30. static/reader/search/reader-dom-search.mjs +0 -2
  31. static/reader/search/reader-search-backends.mjs +2 -147
  32. static/reader/search/reader-search-controller.mjs +2 -2
  33. static/reader/ui/reader-bookmarks.mjs +6 -121
  34. static/reader/ui/reader-navigation.mjs +2 -3
  35. static/reader/ui/reader-progress.mjs +4 -48
  36. static/reader/ui/reader-speech.mjs +2 -28
  37. static/reader/ui/reader-toc.mjs +2 -4
  38. static/reader/ui/reader-ui.mjs +4 -8
  39. static/search/catalog/application/client.js +31 -11
  40. static/search/sidebar/presentation/folder-tree.js +5 -7
  41. tests/fixtures/reader/issues/manifest.json +1 -1
  42. tests/gates/ci-test-inventory.json +0 -4
  43. tests/gates/test_static_checks.py +2 -2
  44. tests/gates/test_static_contract.py +10 -27
  45. tests/live/test_reader_live_smoke.py +2 -1
  46. tests/performance/test_reader_performance.py +1 -444
  47. tests/performance/test_reader_toc_latency.py +75 -53
  48. tests/reader/browser/test_reader_ebook_flow.py +39 -251
  49. tests/reader/browser/test_reader_format_pipeline.py +5 -9
  50. tests/reader/browser/test_reader_refactor.py +71 -559
.gitignore CHANGED
@@ -6,7 +6,6 @@ node_modules/
6
  _search_index_native*.so
7
  static/vendor/*
8
  !static/vendor/djvu-rs-reader/
9
- static/foliate-reader/
10
  tests/__pycache__/
11
  tests/performance/benchmark-results.json
12
  tests/snapshots/
 
6
  _search_index_native*.so
7
  static/vendor/*
8
  !static/vendor/djvu-rs-reader/
 
9
  tests/__pycache__/
10
  tests/performance/benchmark-results.json
11
  tests/snapshots/
Dockerfile CHANGED
@@ -136,15 +136,12 @@ RUN npm install --global "esbuild@${ESBUILD_VERSION}" \
136
  COPY static/ /build/static/
137
  COPY scripts/build/build_static_assets.mjs /build/build_static_assets.mjs
138
  COPY scripts/build/copy_reader_vendor.mjs /build/copy_reader_vendor.mjs
139
- COPY scripts/build/fetch_foliate_reader.mjs /build/fetch_foliate_reader.mjs
140
- COPY scripts/build/foliate-local.patch.b64 /build/foliate-local.patch.b64
141
  COPY scripts/build/check_reader_release.mjs /build/check_reader_release.mjs
142
  COPY scripts/build/compose_app.mjs /build/compose_app.mjs
143
 
144
  RUN mkdir -p /out \
145
  && cp -a static/. /out/ \
146
- && node /build/fetch_foliate_reader.mjs /out/foliate-reader \
147
- && node /build/copy_reader_vendor.mjs /out/vendor --foliate-output /out/foliate-reader/vendor \
148
  && node /build/compose_app.mjs > /build/app-composed.js \
149
  && esbuild /build/app-composed.js --minify --target=es2020 --charset=utf8 --legal-comments=none --outfile=/out/app.js \
150
  && for file in $(node -e 'console.log(require("./static/reader-resources.js").buildFiles("hf").filter(f => f !== "app.js").join(" "))'); do \
 
136
  COPY static/ /build/static/
137
  COPY scripts/build/build_static_assets.mjs /build/build_static_assets.mjs
138
  COPY scripts/build/copy_reader_vendor.mjs /build/copy_reader_vendor.mjs
 
 
139
  COPY scripts/build/check_reader_release.mjs /build/check_reader_release.mjs
140
  COPY scripts/build/compose_app.mjs /build/compose_app.mjs
141
 
142
  RUN mkdir -p /out \
143
  && cp -a static/. /out/ \
144
+ && node /build/copy_reader_vendor.mjs /out/vendor \
 
145
  && node /build/compose_app.mjs > /build/app-composed.js \
146
  && esbuild /build/app-composed.js --minify --target=es2020 --charset=utf8 --legal-comments=none --outfile=/out/app.js \
147
  && for file in $(node -e 'console.log(require("./static/reader-resources.js").buildFiles("hf").filter(f => f !== "app.js").join(" "))'); do \
backend/search/application/cached.py CHANGED
@@ -142,9 +142,11 @@ def get_order(q: str, repos: Sequence[str] | None, extensions: Sequence[str] | N
142
  packed = indices if isinstance(indices, array) else array('I', indices)
143
  size = len(packed) * packed.itemsize
144
  if size <= deps.order_bytes():
 
145
  while deps.orders() and (len(deps.orders()) >= deps.order_max() or
146
- sum(len(v[1]) * v[1].itemsize for v in deps.orders().values()) + size > deps.order_bytes()):
147
- deps.orders().popitem(last=False)
 
148
  deps.orders()[key] = (now, packed)
149
  return packed
150
 
 
142
  packed = indices if isinstance(indices, array) else array('I', indices)
143
  size = len(packed) * packed.itemsize
144
  if size <= deps.order_bytes():
145
+ total_bytes = sum(len(v[1]) * v[1].itemsize for v in deps.orders().values())
146
  while deps.orders() and (len(deps.orders()) >= deps.order_max() or
147
+ total_bytes + size > deps.order_bytes()):
148
+ _, (_, evicted) = deps.orders().popitem(last=False)
149
+ total_bytes -= len(evicted) * evicted.itemsize
150
  deps.orders()[key] = (now, packed)
151
  return packed
152
 
config/types/jsconfig.check.json CHANGED
@@ -15,12 +15,6 @@
15
  ],
16
  "/search/static/*": [
17
  "../../static/*"
18
- ],
19
- "/static/foliate-reader/view.js": [
20
- "../../typings/foliate/view.d.ts"
21
- ],
22
- "/search/static/foliate-reader/view.js?reader-v1": [
23
- "../../typings/foliate/view.d.ts"
24
  ]
25
  }
26
  },
 
15
  ],
16
  "/search/static/*": [
17
  "../../static/*"
 
 
 
 
 
 
18
  ]
19
  }
20
  },
config/types/jsconfig.strict.json CHANGED
@@ -14,9 +14,7 @@
14
  "moduleResolution": "bundler",
15
  "paths": {
16
  "/static/*": ["../../static/*"],
17
- "/search/static/*": ["../../static/*"],
18
- "/static/foliate-reader/view.js": ["../../typings/foliate/view.d.ts"],
19
- "/search/static/foliate-reader/view.js?reader-v1": ["../../typings/foliate/view.d.ts"]
20
  }
21
  },
22
  "files": [
@@ -54,7 +52,6 @@
54
  "../../static/reader/pdf/reader-pdf-text-runtime.mjs",
55
  "../../static/reader/pdf/reader-v3.mjs",
56
  "../../static/reader/core/reader-contract.js",
57
- "../../static/reader/formats/reader-foliate-format.mjs",
58
  "../../static/reader/formats/reader-html-format.mjs",
59
  "../../static/reader/search/reader-book-text.js",
60
  "../../static/reader/search/reader-chapter-search.mjs",
 
14
  "moduleResolution": "bundler",
15
  "paths": {
16
  "/static/*": ["../../static/*"],
17
+ "/search/static/*": ["../../static/*"]
 
 
18
  }
19
  },
20
  "files": [
 
52
  "../../static/reader/pdf/reader-pdf-text-runtime.mjs",
53
  "../../static/reader/pdf/reader-v3.mjs",
54
  "../../static/reader/core/reader-contract.js",
 
55
  "../../static/reader/formats/reader-html-format.mjs",
56
  "../../static/reader/search/reader-book-text.js",
57
  "../../static/reader/search/reader-chapter-search.mjs",
eslint.config.mjs CHANGED
@@ -12,7 +12,7 @@ const rules = Object.fromEntries([
12
 
13
  export default [
14
  // ESLint's global ignore also prevents parsing third-party minified files.
15
- { ignores: ["**/vendor/**", "**/foliate-reader/**", "**/node_modules/**"] },
16
  {
17
  files: ["static/**/*.{js,mjs}"],
18
  languageOptions: {
 
12
 
13
  export default [
14
  // ESLint's global ignore also prevents parsing third-party minified files.
15
+ { ignores: ["**/vendor/**", "**/node_modules/**"] },
16
  {
17
  files: ["static/**/*.{js,mjs}"],
18
  languageOptions: {
ruff.toml CHANGED
@@ -1,5 +1,5 @@
1
  target-version = "py311"
2
- extend-exclude = ["static/vendor", "static/foliate-reader"]
3
 
4
  [lint]
5
  select = ["F", "E9", "S"]
 
1
  target-version = "py311"
2
+ extend-exclude = ["static/vendor"]
3
 
4
  [lint]
5
  select = ["F", "E9", "S"]
scripts/build/check_reader_release.mjs CHANGED
@@ -19,7 +19,7 @@ const args = Object.fromEntries(
19
  )
20
  );
21
  const sourceRequired = ["reader.html", ...resources.readerFiles];
22
- const required = [...sourceRequired, ...resources.foliateFiles.map(file => `foliate-reader/${file}`)];
23
  // Source smoke assertions, not a substitute for runtime behavior tests.
24
  const behavioral = [
25
  /\bVoiceOfMLReaderRuntime\s*\.\s*createReaderRuntime\s*\(/,
@@ -90,15 +90,6 @@ function checkAssets(output, hashed = false) {
90
  for (const [file, digest] of Object.entries(djvuFiles))
91
  assert(hash(path.join(output, "vendor/djvu-rs-reader", file)) === digest, `DjVu decoder integrity mismatch: ${file}`);
92
  assert(fs.statSync(path.join(output, "vendor/djvu-rs-reader/NOTICE.txt")).isFile(), "missing DjVu decoder notice");
93
- for (const vendor of Object.values(resources.foliateVendors)) {
94
- const filename = path.join("foliate-reader/vendor", vendor.file);
95
- assert(hash(path.join(output, filename)) === vendor.sha256,
96
- `Foliate vendor integrity mismatch: ${filename}`);
97
- }
98
- for (const [name, filename] of [["pdf", "pdf.mjs"], ["pdfWorker", "pdf.worker.mjs"]]) {
99
- assert(hash(path.join(output, "foliate-reader/vendor/pdfjs", filename)) === resources.vendors[name].sha256,
100
- `Foliate PDF engine mismatch: ${filename}`);
101
- }
102
  for (const vendor of Object.values(resources.vendors)) {
103
  assert(
104
  hash(path.join(output, vendor.path)) === vendor.sha256,
@@ -151,12 +142,6 @@ function checkAssets(output, hashed = false) {
151
  `missing or empty Reader vendor directory: ${directory}`
152
  );
153
  }
154
- for (const directory of ["foliate-reader/vendor/pdfjs/cmaps", "foliate-reader/vendor/pdfjs/standard_fonts",
155
- "foliate-reader/vendor/pdfjs/wasm"]) {
156
- const target = path.join(output, directory);
157
- assert(fs.existsSync(target) && fs.statSync(target).isDirectory() && fs.readdirSync(target).length > 0,
158
- `missing or empty Foliate PDF.js directory: ${directory}`);
159
- }
160
  }
161
 
162
  function currentAsset(output, filename) {
@@ -192,6 +177,7 @@ function checkProject(root, artifact) {
192
  const output = staticRoot(root, artifact);
193
  checkAssets(output, !!artifact);
194
  if (artifact) {
 
195
  const project = args.project || (fs.existsSync(path.join(root, "Dockerfile")) ? "hf" : "github");
196
  for (const file of resources.buildFiles(project)) currentAsset(output, file);
197
  const shellPath = fs.existsSync(path.join(output, "index.html"))
@@ -215,10 +201,7 @@ function checkProject(root, artifact) {
215
  "unexpanded Reader cache inventory"
216
  );
217
  }
218
- const manifest = [
219
- ...sourceRequired.map(file => `${file}:${hash(path.join(source, file))}`),
220
- ...resources.foliateFiles.map(file => `foliate-reader/${file}:${hash(path.join(output, "foliate-reader", file))}`)
221
- ].join("\n");
222
  return crypto.createHash("sha256").update(manifest).digest("hex");
223
  }
224
 
@@ -331,7 +314,7 @@ function crossCheck(githubRoot, hfRoot) {
331
  `cross-project drift: ${file}`
332
  );
333
  }
334
- for (const file of ["compose_app.mjs", "copy_reader_vendor.mjs", "fetch_foliate_reader.mjs", "foliate-local.patch.b64", "check_reader_release.mjs"]) {
335
  assert(
336
  hash(path.join(githubRoot, "scripts/build", file)) === hash(path.join(hfRoot, "scripts/build", file)),
337
  `cross-project drift: scripts/build/${file}`
 
19
  )
20
  );
21
  const sourceRequired = ["reader.html", ...resources.readerFiles];
22
+ const required = sourceRequired;
23
  // Source smoke assertions, not a substitute for runtime behavior tests.
24
  const behavioral = [
25
  /\bVoiceOfMLReaderRuntime\s*\.\s*createReaderRuntime\s*\(/,
 
90
  for (const [file, digest] of Object.entries(djvuFiles))
91
  assert(hash(path.join(output, "vendor/djvu-rs-reader", file)) === digest, `DjVu decoder integrity mismatch: ${file}`);
92
  assert(fs.statSync(path.join(output, "vendor/djvu-rs-reader/NOTICE.txt")).isFile(), "missing DjVu decoder notice");
 
 
 
 
 
 
 
 
 
93
  for (const vendor of Object.values(resources.vendors)) {
94
  assert(
95
  hash(path.join(output, vendor.path)) === vendor.sha256,
 
142
  `missing or empty Reader vendor directory: ${directory}`
143
  );
144
  }
 
 
 
 
 
 
145
  }
146
 
147
  function currentAsset(output, filename) {
 
177
  const output = staticRoot(root, artifact);
178
  checkAssets(output, !!artifact);
179
  if (artifact) {
180
+ assert(!fs.existsSync(path.join(output, "foliate-reader")), "obsolete Foliate runtime in release");
181
  const project = args.project || (fs.existsSync(path.join(root, "Dockerfile")) ? "hf" : "github");
182
  for (const file of resources.buildFiles(project)) currentAsset(output, file);
183
  const shellPath = fs.existsSync(path.join(output, "index.html"))
 
201
  "unexpanded Reader cache inventory"
202
  );
203
  }
204
+ const manifest = sourceRequired.map(file => `${file}:${hash(path.join(source, file))}`).join("\n");
 
 
 
205
  return crypto.createHash("sha256").update(manifest).digest("hex");
206
  }
207
 
 
314
  `cross-project drift: ${file}`
315
  );
316
  }
317
+ for (const file of ["compose_app.mjs", "copy_reader_vendor.mjs", "check_reader_release.mjs"]) {
318
  assert(
319
  hash(path.join(githubRoot, "scripts/build", file)) === hash(path.join(hfRoot, "scripts/build", file)),
320
  `cross-project drift: scripts/build/${file}`
scripts/build/copy_reader_vendor.mjs CHANGED
@@ -1,5 +1,5 @@
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
  import { Agent, get } from "node:https";
4
  import { dirname, join } from "node:path";
5
  import { gunzipSync } from "node:zlib";
@@ -8,13 +8,6 @@ import { setTimeout as delay } from "node:timers/promises";
8
  const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
9
 
10
  const output = process.argv[2] || "static/vendor";
11
- const foliateOutputArgument = process.argv.indexOf("--foliate-output");
12
- if (foliateOutputArgument >= 0 && !process.argv[foliateOutputArgument + 1])
13
- throw new Error("--foliate-output requires a directory");
14
- const foliateOutput = foliateOutputArgument >= 0
15
- ? process.argv[foliateOutputArgument + 1]
16
- : process.argv.includes("--refresh-foliate")
17
- ? join(process.cwd(), "static/foliate-reader/vendor") : null;
18
  // proxyEnv is supported by Node 22.21+, 24.5+, and later major versions.
19
  const [major, minor] = process.versions.node.split(".").map(Number);
20
  if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5))
@@ -82,8 +75,7 @@ async function downloadWithRetry(url, signal) {
82
 
83
  async function main() {
84
  const vendors = Object.entries(resources.vendors);
85
- const foliateVendors = foliateOutput ? Object.values(resources.foliateVendors) : [];
86
- const items = [resources.pdfArchive, ...vendors.map(([, value]) => value), ...foliateVendors, resources.ruffleArchive];
87
  const downloaded = new Array(items.length);
88
  let next = 0;
89
  const controller = new AbortController();
@@ -134,7 +126,6 @@ async function main() {
134
  // Prepare every operation before touching existing output. Disk errors during the
135
  // commit below can still leave partial updates; this is not an atomic rollback.
136
  const writes = [];
137
- const removals = [];
138
  const ruffleOutput = join(output, resources.ruffleArchive.directory.slice("vendor/".length));
139
  for (const [file, bytes] of extractedRuffle) writes.push([join(ruffleOutput, file), bytes]);
140
  const tar = gunzipSync(downloaded[0], { maxOutputLength: MAX_ARCHIVE_BYTES });
@@ -158,7 +149,6 @@ for (let offset = 0; offset < tar.length;) {
158
  const target = join(output, relative);
159
  const bytes = tar.subarray(offset + 512, offset + 512 + size);
160
  writes.push([target, bytes]);
161
- if (foliateOutput) writes.push([join(foliateOutput, "pdfjs", relative), bytes]);
162
  }
163
  offset += 512 + Math.ceil(size / 512) * 512;
164
  }
@@ -166,26 +156,15 @@ for (const group of pdfGroups) {
166
  if (![...pdfFiles].some(file => file.startsWith(group + "/")))
167
  throw new Error(`PDF archive missing required files: ${group}`);
168
  }
169
- for (const [index, [name, {path}]] of vendors.entries()) {
170
  const bytes = downloaded[index + 1];
171
  const versioned = path.slice("vendor/".length);
172
  writes.push([join(output, versioned), bytes]);
173
- if (foliateOutput && (name === "pdf" || name === "pdfWorker")) {
174
- const filename = name === "pdf" ? "pdf.mjs" : "pdf.worker.mjs";
175
- writes.push([join(foliateOutput, "pdfjs", filename), bytes]);
176
- removals.push(join(foliateOutput, "pdfjs", filename + ".map"));
177
- }
178
- }
179
- if (foliateOutput) for (const [index, {file}] of foliateVendors.entries()) {
180
- const bytes = downloaded[1 + vendors.length + index];
181
- const target = join(foliateOutput, file);
182
- writes.push([target, bytes]);
183
  }
184
  for (const [target, bytes] of writes) {
185
  mkdirSync(dirname(target), { recursive: true });
186
  writeFileSync(target, bytes);
187
  }
188
- for (const target of removals) rmSync(target, { force: true });
189
  }
190
 
191
  main().catch((error) => { console.error(error); process.exitCode = 1; });
 
1
  import { createHash } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
  import { Agent, get } from "node:https";
4
  import { dirname, join } from "node:path";
5
  import { gunzipSync } from "node:zlib";
 
8
  const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
9
 
10
  const output = process.argv[2] || "static/vendor";
 
 
 
 
 
 
 
11
  // proxyEnv is supported by Node 22.21+, 24.5+, and later major versions.
12
  const [major, minor] = process.versions.node.split(".").map(Number);
13
  if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5))
 
75
 
76
  async function main() {
77
  const vendors = Object.entries(resources.vendors);
78
+ const items = [resources.pdfArchive, ...vendors.map(([, value]) => value), resources.ruffleArchive];
 
79
  const downloaded = new Array(items.length);
80
  let next = 0;
81
  const controller = new AbortController();
 
126
  // Prepare every operation before touching existing output. Disk errors during the
127
  // commit below can still leave partial updates; this is not an atomic rollback.
128
  const writes = [];
 
129
  const ruffleOutput = join(output, resources.ruffleArchive.directory.slice("vendor/".length));
130
  for (const [file, bytes] of extractedRuffle) writes.push([join(ruffleOutput, file), bytes]);
131
  const tar = gunzipSync(downloaded[0], { maxOutputLength: MAX_ARCHIVE_BYTES });
 
149
  const target = join(output, relative);
150
  const bytes = tar.subarray(offset + 512, offset + 512 + size);
151
  writes.push([target, bytes]);
 
152
  }
153
  offset += 512 + Math.ceil(size / 512) * 512;
154
  }
 
156
  if (![...pdfFiles].some(file => file.startsWith(group + "/")))
157
  throw new Error(`PDF archive missing required files: ${group}`);
158
  }
159
+ for (const [index, [, {path}]] of vendors.entries()) {
160
  const bytes = downloaded[index + 1];
161
  const versioned = path.slice("vendor/".length);
162
  writes.push([join(output, versioned), bytes]);
 
 
 
 
 
 
 
 
 
 
163
  }
164
  for (const [target, bytes] of writes) {
165
  mkdirSync(dirname(target), { recursive: true });
166
  writeFileSync(target, bytes);
167
  }
 
168
  }
169
 
170
  main().catch((error) => { console.error(error); process.exitCode = 1; });
scripts/build/fetch_foliate_reader.mjs DELETED
@@ -1,157 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { createRequire } from "node:module";
3
- import { dirname, join, relative, resolve, sep } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
- import { Agent, get } from "node:https";
7
- import { gunzipSync } from "node:zlib";
8
-
9
- // proxyEnv is supported by Node 22.21+, 24.5+, and later major versions.
10
- const [major, minor] = process.versions.node.split(".").map(Number);
11
- if (major < 22 || (major === 22 && minor < 21) || major === 23 || (major === 24 && minor < 5))
12
- throw new Error("Node.js 22.21+, 24.5+, or later is required for proxy support");
13
-
14
- const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
15
- const output = resolve(process.argv[2] || "static/foliate-reader");
16
- const scriptDir = dirname(fileURLToPath(import.meta.url));
17
- const encodedPatch = readFileSync(join(scriptDir, "foliate-local.patch.b64"), "ascii").replace(/\s/g, "");
18
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encodedPatch))
19
- throw new Error("Foliate local adaptation patch is not valid base64");
20
- const localPatch = Buffer.from(encodedPatch, "base64").toString("utf8");
21
-
22
- // The proxy-aware agent honors HTTP(S)_PROXY and NO_PROXY, including on redirects.
23
- const agent = new Agent({ proxyEnv: process.env });
24
-
25
- function download(url, redirects = 0) {
26
- return new Promise((resolvePromise, reject) => {
27
- // Never propagate transport errors or URLs: either can contain proxy credentials.
28
- const fail = () => reject(new Error("Foliate archive download failed"));
29
- try {
30
- const request = get(url, { agent }, (response) => {
31
- if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location && redirects < 5) {
32
- response.resume();
33
- try { return download(new URL(response.headers.location, url), redirects + 1).then(resolvePromise, reject); }
34
- catch { return fail(); }
35
- }
36
- if (response.statusCode !== 200) {
37
- response.resume();
38
- return reject(new Error(`Foliate archive download: HTTP ${response.statusCode}`));
39
- }
40
- const chunks = [];
41
- response.on("data", chunk => chunks.push(chunk));
42
- response.on("end", () => resolvePromise(Buffer.concat(chunks)));
43
- response.on("error", fail);
44
- response.on("aborted", fail);
45
- });
46
- request.setTimeout(180000, () => request.destroy());
47
- request.on("error", fail);
48
- } catch { fail(); }
49
- });
50
- }
51
-
52
- async function downloadWithRetry(url) {
53
- let lastError;
54
- for (let attempt = 0; attempt < 4; attempt++) {
55
- try { return await download(url); }
56
- catch (error) {
57
- lastError = error;
58
- if (attempt < 3) await new Promise(resolvePromise => setTimeout(resolvePromise, 1000 * (2 ** attempt)));
59
- }
60
- }
61
- throw lastError;
62
- }
63
-
64
- function extractPinnedFiles(archive) {
65
- const tar = gunzipSync(archive);
66
- const allowed = new Set(resources.foliateFiles);
67
- const extracted = new Set();
68
- const root = `foliate-js-${resources.foliateRevision}`;
69
- for (let offset = 0; offset + 512 <= tar.length;) {
70
- const header = tar.subarray(offset, offset + 512);
71
- const name = header.subarray(0, 100).toString("utf8").replace(/\0.*$/, "");
72
- if (!name) break;
73
- const prefix = header.subarray(345, 500).toString("utf8").replace(/\0.*$/, "");
74
- const path = prefix ? `${prefix}/${name}` : name;
75
- const sizeText = header.subarray(124, 136).toString("ascii").replace(/\0.*$/, "").trim() || "0";
76
- const size = parseInt(sizeText, 8);
77
- const type = String.fromCharCode(header[156] || 48);
78
- const rootPrefix = `${root}/`;
79
- if (!Number.isSafeInteger(size) || size < 0) throw new Error(`invalid Foliate tar entry size: ${path}`);
80
- if (path.startsWith(rootPrefix) && (type === "0" || type === "\0")) {
81
- const file = path.slice(rootPrefix.length);
82
- if (allowed.has(file)) {
83
- const target = resolve(output, file);
84
- const rel = relative(output, target);
85
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`)) throw new Error(`unsafe Foliate path: ${file}`);
86
- mkdirSync(dirname(target), { recursive: true });
87
- writeFileSync(target, tar.subarray(offset + 512, offset + 512 + size));
88
- extracted.add(file);
89
- }
90
- }
91
- offset += 512 + Math.ceil(size / 512) * 512;
92
- }
93
- const missing = [...allowed].filter(file => !extracted.has(file));
94
- if (missing.length) throw new Error(`pinned Foliate archive is missing: ${missing.join(", ")}`);
95
- }
96
-
97
- function applyLocalPatch(patch) {
98
- const lines = patch.split(/\r?\n/);
99
- let index = 0;
100
- let changed = 0;
101
- while (index < lines.length) {
102
- const fileHeader = lines[index++].match(/^diff --git a\/(.+) b\/(.+)$/);
103
- if (!fileHeader) continue;
104
- const file = fileHeader[2];
105
- const target = resolve(output, file);
106
- const rel = relative(output, target);
107
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || !resources.foliateFiles.includes(file))
108
- throw new Error(`Foliate patch targets an unexpected path: ${file}`);
109
- const original = readFileSync(target, "utf8").split("\n");
110
- const result = [];
111
- let sourceIndex = 0;
112
- while (index < lines.length && !lines[index].startsWith("diff --git ")) {
113
- const hunk = lines[index].match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
114
- if (!hunk) { index++; continue; }
115
- const oldStart = Number(hunk[1]);
116
- const oldCount = hunk[2] === undefined ? 1 : Number(hunk[2]);
117
- const targetIndex = oldCount === 0 ? oldStart : oldStart - 1;
118
- while (sourceIndex < targetIndex) result.push(original[sourceIndex++]);
119
- index++;
120
- while (index < lines.length && !lines[index].startsWith("@@ ") && !lines[index].startsWith("diff --git ")) {
121
- const line = lines[index++];
122
- if (line === "") {
123
- if (index === lines.length) break;
124
- throw new Error(`unexpected empty Foliate patch line in ${file}`);
125
- }
126
- const marker = line[0], text = line.slice(1);
127
- if (marker === "\\") continue;
128
- if (marker === " ") {
129
- if (original[sourceIndex] !== text) throw new Error(`Foliate patch context mismatch in ${file}`);
130
- result.push(original[sourceIndex++]);
131
- } else if (marker === "-") {
132
- if (original[sourceIndex] !== text) throw new Error(`Foliate patch removal mismatch in ${file}`);
133
- sourceIndex++;
134
- } else if (marker === "+") result.push(text);
135
- else throw new Error(`invalid Foliate patch line in ${file}: ${line}`);
136
- }
137
- changed++;
138
- }
139
- result.push(...original.slice(sourceIndex));
140
- writeFileSync(target, result.join("\n"));
141
- }
142
- if (!changed) throw new Error("Foliate local adaptation patch was empty or invalid");
143
- }
144
-
145
- async function main() {
146
- rmSync(output, { recursive: true, force: true });
147
- mkdirSync(output, { recursive: true });
148
- const archive = await downloadWithRetry(resources.foliateArchive.url);
149
- const actual = createHash("sha256").update(archive).digest("hex");
150
- if (actual !== resources.foliateArchive.sha256)
151
- throw new Error(`Foliate archive SHA-256 ${actual} does not match ${resources.foliateArchive.sha256}`);
152
- extractPinnedFiles(archive);
153
- applyLocalPatch(localPatch);
154
- console.log(`Foliate ${resources.foliateRevision} fetched, verified, and locally adapted at ${output}`);
155
- }
156
-
157
- main().catch(error => { console.error(error); process.exitCode = 1; });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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gICAgICAgICAgLm1hcChnZXRBdHRyaWJ1dGVzKCdocmVmJywgJ2lkJywgJ21lZGlhLXR5cGUnLCAncHJvcGVydGllcycsICdtZWRpYS1vdmVybGF5JykpCiAgICAgICAgICAgICAubWFwKGl0ZW0gPT4geworICAgICAgICAgICAgICAgIGl0ZW0ucmF3SHJlZiA9IGl0ZW0uaHJlZgogICAgICAgICAgICAgICAgIGl0ZW0uaHJlZiA9IHJlc29sdmVIcmVmKGl0ZW0uaHJlZikKICAgICAgICAgICAgICAgICBpdGVtLnByb3BlcnRpZXMgPSBpdGVtLnByb3BlcnRpZXM/LnNwbGl0KC9ccy8pCiAgICAgICAgICAgICAgICAgcmV0dXJuIGl0ZW0KQEAgLTk5Myw2ICs5OTQsMTQgQEAgJHtkb2MucXVlcnlTZWxlY3RvcigncGFyc2VyZXJyb3InKS5pbm5lclRleHR9YCkKICAgICAgICAgICAgICAgICBsaW5lYXIsCiAgICAgICAgICAgICAgICAgcGFnZVNwcmVhZDogZ2V0UGFnZVNwcmVhZChwcm9wZXJ0aWVzKSwKICAgICAgICAgICAgICAgICByZXNvbHZlSHJlZjogaHJlZiA9PiByZXNvbHZlVVJMKGhyZWYsIGl0ZW0uaHJlZiksCisgICAgICAgICAgICAgICAgcmVzb2x2ZVJlc291cmNlSHJlZjogaHJlZiA9PiB7CisgICAgICAgICAgICAgICAgICAgIC8vIFJlc29sdmUgcmF3IFVSSXMgYmVmb3JlIGRlY29kaW5nIG9uY2UgdG8gYSBsaXRlcmFsIFpJUCBtZW1iZXIgbmFtZS4KKyAgICAgICAgICAgICAgICAgICAgY29uc3Qgcm9vdCA9ICdodHRwczovL2ludmFsaWQuaW52YWxpZC8nCisgICAgICAgICAgICAgICAgICAgIGNvbnN0IGJhc2UgPSBuZXcgVVJMKGl0ZW0ucmF3SHJlZiwgcm9vdCArIG9wZlBhdGguc3BsaXQoJy8nKS5tYXAoZW5jb2RlVVJJQ29tcG9uZW50KS5qb2luKCcvJykpCisgICAgICAgICAg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IHRoaXMudmlldyA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2ZvbGlhdGUtdmlldycpCiAgICAgICAgIGRvY3VtZW50LmJvZHkuYXBwZW5kKHRoaXMudmlldykKICAgICAgICAgYXdhaXQgdGhpcy52aWV3Lm9wZW4oZmlsZSkKKyAgICAgICAgdGhpcy52aWV3LnJlbmRlcmVyLnNldEF0dHJpYnV0ZSgnZmxvdycsICdzY3JvbGxlZCcpCisgICAgICAgIGxldCBtb3ZpbmcgPSBmYWxzZQorICAgICAgICBsZXQgcHJldmlvdXNTdGFydCA9IG51bGwKKyAgICAgICAgY29uc3QgbW92ZVNlY3Rpb24gPSBhc3luYyBkaXJlY3Rpb24gPT4geworICAgICAgICAgICAgY29uc3QgcmVuZGVyZXIgPSB0aGlzLnZpZXcucmVuZGVyZXIKKyAgICAgICAgICAgIGlmIChtb3ZpbmcgfHwgIXJlbmRlcmVyLnNjcm9sbGVkIHx8ICFkaXJlY3Rpb24pIHJldHVybgorICAgICAgICAgICAgY29uc3Qgc3RhcnQgPSByZW5kZXJlci5zdGFydAorICAgICAgICAgICAgY29uc3QgZW5kID0gcmVuZGVyZXIuZW5kCisgICAgICAgICAgICBjb25zdCB2aWV3U2l6ZSA9IHJlbmRlcmVyLnZpZXdTaXplCisgICAgICAgICAgICBpZiAoZGlyZWN0aW9uID4gMCAmJiBlbmQgPCB2aWV3U2l6ZSAtIDIpIHJldHVybgorICAgICAgICAgICAgaWYgKGRpcmVjdGlvbiA8IDAgJiYgc3RhcnQgPiAyKSByZXR1cm4KKyAgICAgICAgICAgIG1vdmluZyA9IHRydWUKKyAgICAgICAgICAgIHRyeSB7CisgICAgICAgICAgICAgICAgaWYgKGRpcmVjdGlvbiA+IDApIGF3YWl0IHRoaXMudmlldy5uZXh0KCkKKyAgICAgICAgICAgICAgICBlbHNlIGF3YWl0IHRoaXMudmlldy5wcmV2KCkKKyAgICAgICAgICAgIH0gZmluYWxseSB7CisgICAgICAgICAgICAgICAgbW92aW5nID0gZmFsc2UKKyAgICAgICAgICAgICAgICBwcmV2aW91c1N0YXJ0ID0gbnVsbAorICAgICAgICAgICAgfQorICAgICAgICB9CisgICAgICAgIGNvbnN0IG1vdmVBY3Jvc3NTZWN0aW9ucyA9ICgpID0+IHsKKyAgICAgICAgICAgIGNvbnN0IHJlbmRlcmVyID0gdGhpcy52aWV3LnJlbmRlcmVyCisgICAgICAgICAgICBjb25zdCBzdGFydCA9IHJlbmRlcmVyLnN0YXJ0CisgICAgICAgICAgICBjb25zdCBkaXJlY3Rpb24gPSBwcmV2aW91c1N0YXJ0ID09IG51bGwgPyAwIDogc3RhcnQgLSBwcmV2aW91c1N0YXJ0CisgICAgICAgICAgICBwcmV2aW91c1N0YXJ0ID0gc3RhcnQKKyAgICAgICAgICAgIG1vdmVTZWN0aW9uKGRpcmVjdGlvbikKKyAgICAgICAgfQorICAgICAgICBsZXQgYm91bmRDb250YWluZXIgPSBudWxsCisgICAgICAgIGNvbnN0IGJpbmRTY3JvbGxDb250YWluZXIgPSAoKSA9PiB7CisgICAgICAgICAgICBjb25zdCBjb250YWluZXIgPSB0aGlzLnZpZXcucmVuZGVyZXIuc2hhZG93Um9vdD8ucXVlcnlTZWxlY3RvcignI2NvbnRhaW5lcicpIHx8IHRoaXMudmlldy5yZW5kZXJlcgorICAgICAgICAgICAgaWYgKGNvbnRhaW5lciA9PT0gYm91bmRDb250YWluZXIpIHJldHVybgorICAgICAgICAgICAgYm91bmRDb250YWluZXIgPSBjb250YWluZXIKKyAgICAgICAgICAgIGNvbnRhaW5lci5hZGRFdmVudExpc3RlbmVyKCdzY3JvbGwnLCBtb3ZlQWNyb3NzU2VjdGlvbnMpCisgICAgICAgICAgICBjb250YWluZXIuYWRkRXZlbnRMaXN0ZW5lcignd2hlZWwnLCBldmVudCA9PiB7CisgICAgICAgICAgICBpZiAoZXZlbnQuZGVsdGFZKSBtb3ZlU2VjdGlvbihldmVudC5kZWx0YVkgPiAwID8gMSA6IC0xKQorICAg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Ghpcy4jb25SZWxvY2F0ZS5iaW5kKHRoaXMpKQogCkBAIC0xMTgsNyArMTY4LDEwIEBAIGNsYXNzIFJlYWRlciB7CiAgICAgICAgICAgICB9KQogICAgICAgICB9KQogICAgICAgICB0aGlzLnZpZXcucmVuZGVyZXIuc2V0U3R5bGVzPy4oZ2V0Q1NTKHRoaXMuc3R5bGUpKQotICAgICAgICB0aGlzLnZpZXcucmVuZGVyZXIubmV4dCgpCisgICAgICAgIGF3YWl0IFByb21pc2UucmFjZShbCisgICAgICAgICAgICB0aGlzLnZpZXcuZ29UbygwKSwKKyAgICAgICAgICAgIG5ldyBQcm9taXNlKHJlc29sdmUgPT4gc2V0VGltZW91dChyZXNvbHZlLCAzMDAwKSksCisgICAgICAgIF0pCiAKICAgICAgICAgJCgnI2hlYWRlci1iYXInKS5zdHlsZS52aXNpYmlsaXR5ID0gJ3Zpc2libGUnCiAgICAgICAgICQoJyNuYXYtYmFyJykuc3R5bGUudmlzaWJpbGl0eSA9ICd2aXNpYmxlJwpAQCAtMTUxLDYgKzIwNCwxNSBAQCBjbGFzcyBSZWFkZXIgewogICAgICAgICAgICAgICAgIHRoaXMuY2xvc2VTaWRlQmFyKCkKICAgICAgICAgICAgIH0pCiAgICAgICAgICAgICAkKCcjdG9jLXZpZXcnKS5hcHBlbmQodGhpcy4jdG9jVmlldy5lbGVtZW50KQorICAgICAgICAgICAgY29uc3QgZW50cmllcyA9IFtdCisgICAgICAgICAgICBjb25zdCBhcHBlbmQgPSAoaXRlbXMsIGRlcHRoID0gMCkgPT4geworICAgICAgICAgICAgICAgIGZvciAoY29uc3QgaXRlbSBvZiBpdGVtcyB8fCBbXSkgeworICAgICAgICAgICAgICAgICAgICBlbnRyaWVzLnB1c2goeyBsYWJlbDogaXRlbS5sYWJlbCB8fCAn5pyq5ZG95ZCN56ug6IqCJywgaHJlZjogaXRlbS5ocmVmLCBkZXB0aCB9KQorICAgICAgICAgICAgICAgICAgICBhcHBlbmQoaXRlbS5zdWJpd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ByYW5nZSA9IHsgc3RhcnRJbmRleCwgc3RhcnRPZmZzZXQsIGVuZEluZGV4LCBlbmRPZmZzZXQgfQotICAgICAgICAgICAgeWllbGQgeyByYW5nZSwgZXhjZXJwdDogbWFrZUV4Y2VycHQoc3RycywgcmFuZ2UpIH0KKyAgICAgICAgICAgIHlpZWxkIHsgcmFuZ2UsIGdldCBleGNlcnB0KCkgeyByZXR1cm4gbWFrZUV4Y2VycHQoc3RycywgcmFuZ2UpIH0gfQogICAgICAgICB9CiAgICAgICAgIHN1YnN0ckFyci5zaGlmdCgpCiAgICAgfQpAQCAtMTIxLDggKzEyMSwxNSBAQCBleHBvcnQgY29uc3Qgc2VhcmNoTWF0Y2hlciA9ICh0ZXh0V2Fsa2VyLCBvcHRzKSA9PiB7CiAgICAgICAgICAgICAgICAgOiAnYmFzZScsCiAgICAgICAgICAgICB9KSkgewogICAgICAgICAgICAgICAgIGNvbnN0IHsgc3RhcnRJbmRleCwgc3RhcnRPZmZzZXQsIGVuZEluZGV4LCBlbmRPZmZzZXQgfSA9IHJlc3VsdC5yYW5nZQotICAgICAgICAgICAgICAgIHJlc3VsdC5yYW5nZSA9IG1ha2VSYW5nZShzdGFydEluZGV4LCBzdGFydE9mZnNldCwgZW5kSW5kZXgsIGVuZE9mZnNldCkKLSAgICAgICAgICAgICAgICB5aWVsZCByZXN1bHQKKyAgICAgICAgICAgICAgICAvLyBDb3VudCBldmVyeSBtYXRjaCB3aXRob3V0IGJ1aWxkaW5nIGV4Y2VycHRzIG9yIERPTSByYW5nZXMKKyAgICAgICAgICAgICAgICAvLyBmb3IgcmVzdWx0cyBvdXRzaWRlIHRoZSByZXF1ZXN0ZWQgcGFnZS4KKyAgICAgICAgICAgICAgICBsZXQgcmFuZ2UKKyAgICAgICAgICAgICAgICB5aWVsZCB7CisgICAgICAgICAgICAgICAgICAgIGdldCByYW5nZSgpIHsKKyAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiByYW5nZSA/Pz0gbWFrZVJhb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AgICAgICAgICAgICAgICAgICAgICAuZmluZCh4ID0+IHguaW5kZXggPSByZXNvbHZlZC5pbmRleCkKKyAgICAgICAgICAgICAgICAgICAgICAgICAgICAuZmluZCh4ID0+IHguaW5kZXggPT09IHJlc29sdmVkLmluZGV4KQogICAgICAgICAgICAgICAgICAgICAgICAgY29uc3QgZWwgPSByZXNvbHZlZC5hbmNob3IoZG9jKQogICAgICAgICAgICAgICAgICAgICAgICAgZWwuY2xhc3NMaXN0LmFkZChhY3RpdmVDbGFzcykKICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChwbGF5YmFja0FjdGl2ZUNsYXNzKSBlbC5vd25lckRvY3VtZW50CkBAIC0zMDcsOSArMzEwLDcgQEAgZXhwb3J0IGNsYXNzIFZpZXcgZXh0ZW5kcyBIVE1MRWxlbWVudCB7CiAgICAgICAgIHRoaXMubWVkaWFPdmVybGF5ID0gbnVsbAogICAgIH0KICAgICBnb1RvVGV4dFN0YXJ0KCkgewotICAgICAgICByZXR1cm4gdGhpcy5nb1RvKHRoaXMuYm9vay5sYW5kbWFya3MKLSAgICAgICAgICAgID8uZmluZChtID0+IG0udHlwZS5pbmNsdWRlcygnYm9keW1hdHRlcicpIHx8IG0udHlwZS5pbmNsdWRlcygndGV4dCcpKQotICAgICAgICAgICAgPy5ocmVmID8/IHRoaXMuYm9vay5zZWN0aW9ucy5maW5kSW5kZXgocyA9PiBzLmxpbmVhciAhPT0gJ25vJykpCisgICAgICAgIHJldHVybiB0aGlzLmdvVG8oMCkKICAgICB9CiAgICAgYXN5bmMgaW5pdCh7IGxhc3RMb2NhdGlvbiwgc2hvd1RleHRTdGFydCB9KSB7CiAgICAgICAgIGNvbnN0IHJlc29sdmVkID0gbGFzdExvY2F0aW9uID8gdGhpcy5yZXNvbHZlTmF2aWdhdGlvbihsYXN0TG9jYXRpb24pIDogbnVsbApAQCAtNTQ3LDYgKzU0OCwzNyBAQCBleHBvcnQgY2xhc3MgVmlldyBleHRlbmRzIEhUTUxFbGVtZW50IHsKICAgICAgICAgY29uc3QgeyBxdWVyeSwgaW5kZXggfSA9IG9wdHMKICAgICAgICAgY29uc3QgbWF0Y2hlciA9IHNlYXJjaE1hdGNoZXIodGV4dFdhbGtlciwKICAgICAgICAgICAgIHsgZGVmYXVsdExvY2FsZTogdGhpcy5sYW5ndWFnZSwgLi4ub3B0cyB9KQorICAgICAgICBpZiAob3B0cy5sZWFuKSB7CisgICAgICAgICAgICBjb25zdCB7IHNlY3Rpb25zIH0gPSB0aGlzLmJvb2sKKyAgICAgICAgICAgIGNvbnN0IGluZGljZXMgPSBpbmRleCAhPSBudWxsID8gW2luZGV4XSA6IHNlY3Rpb25zLm1hcCgoXywgaSkgPT4gaSkKKyAgICAgICAgICAgIGNvbnN0IG9mZnNldCA9IE1hdGgubWF4KDAsIG9wdHMub2Zmc2V0IHx8IDApCisgICAgICAgICAgICBjb25zdCBsaW1pdCA9IE1hdGgubWF4KDAsIE1hdGgubWluKDUwLCBvcHRzLmxpbWl0ID8/IDUwKSkKKyAgICAgICAgICAgIGZvciAoY29uc3Qgc2VjdGlvbkluZGV4IG9mIGluZGljZXMpIHsKKyAgICAgICAgICAgICAgICBpZiAob3B0cy5jdXJyZW50Py4oKSA9PT0gZmFsc2UpIHJldHVybgorICAgICAgICAgICAgICAgIGNvbnN0IHNlY3Rpb24gPSBzZWN0aW9uc1tzZWN0aW9uSW5kZXhdCisgICAgICAgICAgICAgICAgaWYgKCFzZWN0aW9uPy5jcmVhdGVEb2N1bWVudCkgY29udGludWUKKyAgICAgICAgICAgICAgICBjb25zdCBkb2MgPSBhd2FpdCBzZWN0aW9uLmNyZWF0ZURvY3VtZW50KCkKKyAgICAgICAgICAgICAgICBpZiAob3B0cy5jdXJyZW50Py4oKSA9PT0gZmFsc2UpIHJldHVybgorICAgICAgICAgICAgICAgIGxldCBjb3VudCA9IDAKKyAgICAgICAgICAgICAgICBjb25zdCBzdWJpdGVtcyA9IFtdCisgICAgICAgICAgICAgICAgZm9yIChjb25zdCBtYXRjaCBvZiBtYXRjaGVyKGRvYywgcXVlcnkpKSB7CisgICAgICAgICAgICAgICAgICAgIGlmIChjb3VudCA+PSBvZmZzZXQgJiYgc3ViaXRlbXMubGVuZ3RoIDwgbGltaXQpIHsKKyAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHsgcmFuZ2UsIGV4Y2VycHQgfSA9IG1hdGNoCisgICAgICAgICAgICAgICAgICAgICAgICBzdWJpdGVtcy5wdXNoKHsgY2ZpOiB0aGlzLmdldENGSShzZWN0aW9uSW5kZXgsIHJhbmdlKSwgZXhjZXJwdCB9KQorICAgICAgICAgICAgICAgICAgICB9CisgICAgICAgICAgICAgICAgICAgIGNvdW50KysKKyAgICAgICAgICAgICAgICAgICAgaWYgKGNvdW50ICUgMjA0OCA9PT0gMCkgeworICAgICAgICAgICAgICAgICAgICAgICAgYXdhaXQgbmV3IFByb21pc2UocmVzb2x2ZSA9PiBzZXRUaW1lb3V0KHJlc29sdmUsIDApKQorICAgICAgICAgICAgICAgICAgICAgICAgaWYgKG9wdHMuY3VycmVudD8uKCkgPT09IGZhbHNlKSByZXR1cm4KKyAgICAgICAgICAgICAgICAgICAgfQorICAgICAgICAgICAgICAgICAgICBpZiAoaW5kZXggIT0gbnVsbCAmJiBzdWJpdGVtcy5sZW5ndGggPT09IGxpbWl0KSBicmVhaworICAgICAgICAgICAgICAgIH0KKyAgICAgICAgICAgICAgICBpZiAob3B0cy5jdXJyZW50Py4oKSA9PT0gZmFsc2UpIHJldHVybgorICAgICAgICAgICAgICAgIHlpZWxkIHsgaW5kZXg6IHNlY3Rpb25JbmRleCwgY291bnQsIHN1Yml0ZW1zLAorICAgICAgICAgICAgICAgICAgICBsYWJlbDogdGhpcy4jdG9jUHJvZ3Jlc3MuZ2V0UHJvZ3Jlc3Moc2VjdGlvbkluZGV4KT8ubGFiZWwgPz8gJycgfQorICAgICAgICAgICAgfQorICAgICAgICAgICAgcmV0dXJuCisgICAgICAgIH0KICAgICAgICAgY29uc3QgaXRlciA9IGluZGV4ICE9IG51bGwKICAgICAgICAgICAgID8gdGhpcy4jc2VhcmNoU2VjdGlvbihtYXRjaGVyLCBxdWVyeSwgaW5kZXgpCiAgICAgICAgICAgICA6IHRoaXMuI3NlYXJjaEJvb2sobWF0Y2hlciwgcXVlcnkpCg==
 
 
scripts/check_markup.mjs CHANGED
@@ -63,7 +63,7 @@ function html(file) {
63
 
64
  function visitDirectory(directory) {
65
  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
66
- if (entry.name === "vendor" || entry.name === "foliate-reader") continue;
67
  const file = path.join(directory, entry.name);
68
  if (entry.isDirectory()) visitDirectory(file);
69
  else if (entry.isFile() && entry.name.endsWith(".html")) html(file);
 
63
 
64
  function visitDirectory(directory) {
65
  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
66
+ if (entry.name === "vendor") continue;
67
  const file = path.join(directory, entry.name);
68
  if (entry.isDirectory()) visitDirectory(file);
69
  else if (entry.isFile() && entry.name.endsWith(".html")) html(file);
scripts/reader/check_reader_lifecycle_coverage.mjs CHANGED
@@ -24,7 +24,7 @@ const required = [
24
  'error classification preserves dynamic getter access and uncoerced matching codes',
25
  'navigation warnings require a current generation and ignore aborts',
26
  'waitForReader rejects on cancellation and resolves on its timer',
27
- 'reader readiness preserves Foliate anchor only when loading node is connected',
28
  'phase and stage forward return values unchanged',
29
  'dispose is idempotent, releases observer and clears all timer handles',
30
  'failure cleanup preserves message, lifecycle stage and retry control semantics',
 
24
  'error classification preserves dynamic getter access and uncoerced matching codes',
25
  'navigation warnings require a current generation and ignore aborts',
26
  'waitForReader rejects on cancellation and resolves on its timer',
27
+ 'reader readiness preserves chapter anchor only when loading node is connected',
28
  'phase and stage forward return values unchanged',
29
  'dispose is idempotent, releases observer and clears all timer handles',
30
  'failure cleanup preserves message, lifecycle stage and retry control semantics',
scripts/reader/check_reader_media_coverage.mjs CHANGED
@@ -43,7 +43,7 @@ if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => v
43
  } else {
44
  // Keep these independent of the TAP and coverage checks above.
45
  for (const args of [
46
- ['--test', '--test-concurrency=1', '--test-reporter=tap', 'tests/reader/copy_reader_vendor.test.mjs', 'tests/reader/test_foliate_proxy.mjs'],
47
  ['tests/reader/media/test_ruffle_closure.mjs'],
48
  ['tests/service_worker/test_ruffle_retention.js']
49
  ]) {
 
43
  } else {
44
  // Keep these independent of the TAP and coverage checks above.
45
  for (const args of [
46
+ ['--test', '--test-concurrency=1', '--test-reporter=tap', 'tests/reader/copy_reader_vendor.test.mjs'],
47
  ['tests/reader/media/test_ruffle_closure.mjs'],
48
  ['tests/service_worker/test_ruffle_retention.js']
49
  ]) {
static/app.js CHANGED
@@ -1975,8 +1975,7 @@ function warmReaderIntent(rawUrl, urgent = false) {
1975
  /** @param {string} href */
1976
  const preload = (href) => {
1977
  const link = document.createElement("link");
1978
- // Foliate files are all ES modules; a classic preload would not be reused.
1979
- const module = href.endsWith(".mjs") || href.includes("/foliate-reader/") || (href.endsWith(".js") && !engineAssets.includes(href));
1980
  link.rel = module ? "modulepreload" : "preload";
1981
  if (!module) link.as = href.endsWith(".css") ? "style" : "script";
1982
  link.fetchPriority = "low";
 
1975
  /** @param {string} href */
1976
  const preload = (href) => {
1977
  const link = document.createElement("link");
1978
+ const module = href.endsWith(".mjs") || (href.endsWith(".js") && !engineAssets.includes(href));
 
1979
  link.rel = module ? "modulepreload" : "preload";
1980
  if (!module) link.as = href.endsWith(".css") ? "style" : "script";
1981
  link.fetchPriority = "low";
static/reader-resources.js CHANGED
@@ -28,6 +28,16 @@
28
  file: "purify.min.js",
29
  sha256: "8053ee2a6a09f9d50f7fcd6fb7f07072f52c7f3fa9aa12147cab4feaf65ee970"
30
  },
 
 
 
 
 
 
 
 
 
 
31
  ruffle: {
32
  url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js",
33
  file: "ruffle.js",
@@ -62,54 +72,11 @@
62
  url: "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
63
  sha256: "7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa"
64
  });
65
- const foliateRevision = "78914aef4466eb960965702401634c2cb348e9b1";
66
- const foliateArchive = Object.freeze({
67
- url: `https://codeload.github.com/johnfactotum/foliate-js/tar.gz/${foliateRevision}`,
68
- sha256: "4878cd5f04073af5046ea543da73a963a7f9e1a4b30ddc63ac86cea5adf02f38"
69
- });
70
- const foliateFiles = Object.freeze([
71
- "LICENSE", "comic-book.js", "epub.js", "epubcfi.js", "fb2.js", "fixed-layout.js",
72
- "mobi.js", "overlayer.js", "paginator.js", "pdf.js", "progress.js", "reader.html",
73
- "reader.js", "search.js", "text-walker.js", "tts.js", "ui/menu.js", "ui/tree.js", "view.js"
74
- ]);
75
- const foliateVendors = {
76
- fflateLicense: {
77
- url: "https://cdn.jsdelivr.net/npm/fflate@0.8.3/LICENSE",
78
- file: "LICENSE_fflate",
79
- sha256: "0a1df3a083d0c010560aa342e87959c8c1070e6fd54545741f083f22d0c8b551"
80
- },
81
- zipLicense: {
82
- url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/LICENSE",
83
- file: "LICENSE_zipjs",
84
- sha256: "1b7ebc8d7889ed25491484ab2b102370742ca6c0b26650a0c62cc2269b579b84"
85
- },
86
- fflate: {
87
- url: "https://cdn.jsdelivr.net/npm/fflate@0.8.3/esm/browser.js",
88
- file: "fflate.js",
89
- sha256: "b7ca4450b19559a1d50eb381adcee94b82449674be4cd17789d9beba7e6122a1"
90
- },
91
- zip: {
92
- url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/index.min.js",
93
- file: "zip.js",
94
- sha256: "715a4067bb71d750d4af8e60390e48894072f65501e0442e53f252cbfc45cfbc"
95
- },
96
- textLayer: {
97
- url: "https://cdn.jsdelivr.net/gh/mozilla/pdf.js@v6.5.438/web/text_layer_builder.css",
98
- file: "pdfjs/text_layer_builder.css",
99
- sha256: "5b21bcb7d703cae5b8eebf9c8579435409aaf351b62e7518327ada60bdd0946f"
100
- },
101
- annotationLayer: {
102
- url: "https://cdn.jsdelivr.net/gh/mozilla/pdf.js@v6.5.438/web/annotation_layer_builder.css",
103
- file: "pdfjs/annotation_layer_builder.css",
104
- sha256: "eb7905a0db3e35b4a069c7ba47048fc131ccc2eccc8c4205e4e20dac58c80176"
105
- }
106
- };
107
- for (const vendor of Object.values(foliateVendors)) Object.freeze(vendor);
108
  const readerComponentFiles = Object.freeze([
109
  "reader/ui/reader-document-styles.mjs",
110
- "reader/core/reader-diagnostics.mjs", "reader/core/reader-lifecycle.mjs", "reader/core/reader-source.mjs", "reader/ui/reader-ui.mjs",
111
  "reader/ui/reader-toc.mjs", "reader/search/reader-search-backends.mjs", "reader/pdf/reader-pdf-scheduler.mjs", "reader/ui/reader-navigation.mjs",
112
- "reader/formats/reader-foliate-format.mjs", "reader/ui/reader-progress.mjs", "reader/ui/reader-bookmarks.mjs", "reader/formats/reader-media-format.mjs",
113
  "reader/core/reader-document-loader.mjs", "reader/pdf/reader-pdf-page-window.mjs", "reader/pdf/reader-pdf-text-runtime.mjs",
114
  "reader/formats/reader-html-format.mjs", "reader/pdf/reader-pdf-renderer.mjs", "reader/formats/reader-text-format.mjs",
115
  "reader/formats/reader-chapter-format.mjs", "reader/formats/reader-format-controller.mjs",
@@ -235,8 +202,8 @@
235
  const djvuDecoderAssets = (base) => ["scalar/djvu_rs.js", "scalar/djvu_rs_bg.wasm",
236
  "simd128/djvu_rs.js", "simd128/djvu_rs_bg.wasm"].map(file =>
237
  base + "vendor/djvu-rs-reader/release-06c82c74447d-03087b1edf0c/" + file);
238
- /** @param {string} extension @param {string} base @param {string} [foliateSuffix] @param {string} [workerWrapper] @returns {string[]} */
239
- function engineAssets(extension, base, foliateSuffix = "", workerWrapper = base + "reader/pdf/pdf-worker-wrapper.mjs") {
240
  if (extension === "pdf")
241
  return [
242
  vendorUrl("pdf", base),
@@ -245,15 +212,6 @@
245
  ...pdfSupportAssets(base)
246
  ];
247
  if (["djvu", "djv"].includes(extension)) return djvuSelectedAssets(base);
248
- // view.js statically imports these leaf modules; warm them with it so they
249
- // are not discovered one round trip later. Format modules follow makeBook.
250
- /** @param {...string} files */
251
- const foliate = (...files) => [base + "foliate-reader/view.js" + foliateSuffix,
252
- ...["epubcfi.js", "progress.js", "overlayer.js", "text-walker.js", ...files].map(file => base + "foliate-reader/" + file)];
253
- if (extension === "epub") return foliate("vendor/zip.js", "epub.js", "paginator.js");
254
- if (["mobi", "azw", "azw3"].includes(extension)) return foliate("mobi.js", "vendor/fflate.js", "paginator.js");
255
- if (extension === "fb2") return foliate("fb2.js", "paginator.js");
256
- if (extension === "fbz") return foliate("vendor/zip.js", "fb2.js", "paginator.js");
257
  if (["md", "markdown"].includes(extension))
258
  return [vendorUrl("marked", base), vendorUrl("purify", base)];
259
  if (["html", "htm"].includes(extension)) return [vendorUrl("purify", base)];
@@ -331,10 +289,6 @@
331
  }
332
  const resources = Object.freeze({
333
  vendors: Object.freeze(vendors),
334
- foliateVendors: Object.freeze(foliateVendors),
335
- foliateRevision,
336
- foliateArchive,
337
- foliateFiles,
338
  pdfArchive,
339
  ruffleArchive,
340
  ruffleAssets,
 
28
  file: "purify.min.js",
29
  sha256: "8053ee2a6a09f9d50f7fcd6fb7f07072f52c7f3fa9aa12147cab4feaf65ee970"
30
  },
31
+ zip: {
32
+ url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/index.min.js",
33
+ file: "zip.js",
34
+ sha256: "715a4067bb71d750d4af8e60390e48894072f65501e0442e53f252cbfc45cfbc"
35
+ },
36
+ zipLicense: {
37
+ url: "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.25.0/LICENSE",
38
+ file: "LICENSE_zipjs.txt",
39
+ sha256: "1b7ebc8d7889ed25491484ab2b102370742ca6c0b26650a0c62cc2269b579b84"
40
+ },
41
  ruffle: {
42
  url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js",
43
  file: "ruffle.js",
 
72
  url: "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
73
  sha256: "7461aefcd27c4ef0dd76f9ca5760f09466eb6b3f934432670c12132e7b3d6faa"
74
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  const readerComponentFiles = Object.freeze([
76
  "reader/ui/reader-document-styles.mjs",
77
+ "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",
78
  "reader/ui/reader-toc.mjs", "reader/search/reader-search-backends.mjs", "reader/pdf/reader-pdf-scheduler.mjs", "reader/ui/reader-navigation.mjs",
79
+ "reader/ui/reader-progress.mjs", "reader/ui/reader-bookmarks.mjs", "reader/formats/reader-media-format.mjs",
80
  "reader/core/reader-document-loader.mjs", "reader/pdf/reader-pdf-page-window.mjs", "reader/pdf/reader-pdf-text-runtime.mjs",
81
  "reader/formats/reader-html-format.mjs", "reader/pdf/reader-pdf-renderer.mjs", "reader/formats/reader-text-format.mjs",
82
  "reader/formats/reader-chapter-format.mjs", "reader/formats/reader-format-controller.mjs",
 
202
  const djvuDecoderAssets = (base) => ["scalar/djvu_rs.js", "scalar/djvu_rs_bg.wasm",
203
  "simd128/djvu_rs.js", "simd128/djvu_rs_bg.wasm"].map(file =>
204
  base + "vendor/djvu-rs-reader/release-06c82c74447d-03087b1edf0c/" + file);
205
+ /** @param {string} extension @param {string} base @param {string} [_unusedSuffix] @param {string} [workerWrapper] @returns {string[]} */
206
+ function engineAssets(extension, base, _unusedSuffix = "", workerWrapper = base + "reader/pdf/pdf-worker-wrapper.mjs") {
207
  if (extension === "pdf")
208
  return [
209
  vendorUrl("pdf", base),
 
212
  ...pdfSupportAssets(base)
213
  ];
214
  if (["djvu", "djv"].includes(extension)) return djvuSelectedAssets(base);
 
 
 
 
 
 
 
 
 
215
  if (["md", "markdown"].includes(extension))
216
  return [vendorUrl("marked", base), vendorUrl("purify", base)];
217
  if (["html", "htm"].includes(extension)) return [vendorUrl("purify", base)];
 
289
  }
290
  const resources = Object.freeze({
291
  vendors: Object.freeze(vendors),
 
 
 
 
292
  pdfArchive,
293
  ruffleArchive,
294
  ruffleAssets,
static/reader.css CHANGED
@@ -1250,86 +1250,13 @@ body {
1250
  text-align: center;
1251
  line-height: 1.6;
1252
  }
1253
- /* Chapter bundles and Foliate hosts. Chapter Shadow DOM has its own stylesheet. */
1254
  .epub-frame {
1255
  width: 100%;
1256
  height: auto;
1257
  min-height: 100%;
1258
  background: #181b1e;
1259
  }
1260
- .foliate-reader-view {
1261
- display: block;
1262
- width: 100%;
1263
- height: 100%;
1264
- min-height: 100%;
1265
- background: #181b1e;
1266
- }
1267
- .foliate-continuous {
1268
- --reader-book-link: #8ab4e8;
1269
- width: min(100%, 900px);
1270
- min-height: 100%;
1271
- margin: 0 auto;
1272
- padding: 24px 20px 64px;
1273
- background: #181b1e;
1274
- color: #e7e9eb;
1275
- }
1276
- .foliate-continuous > article {
1277
- min-height: 0 !important;
1278
- height: auto !important;
1279
- margin: 0 auto 32px;
1280
- padding-top: 0 !important;
1281
- line-height: 1.7;
1282
- break-before: auto !important;
1283
- page-break-before: auto !important;
1284
- font-size: calc(var(--reader-prose-size, 1em) * var(--reader-zoom));
1285
- }
1286
- /* Virtualized chapters must reserve their measured height. */
1287
- .foliate-continuous > article.foliate-section-placeholder {
1288
- height: var(--foliate-placeholder-height) !important;
1289
- min-height: var(--foliate-placeholder-height) !important;
1290
- padding: 0 !important;
1291
- contain: strict;
1292
- pointer-events: none;
1293
- }
1294
- .foliate-continuous > article > :first-child {
1295
- margin-top: 0 !important;
1296
- }
1297
- .foliate-continuous a {
1298
- color: #8ab4e8 !important;
1299
- }
1300
- .foliate-continuous a[href]:not([href^="http:"]):not([href^="https:"]) {
1301
- text-decoration: none !important;
1302
- }
1303
- .foliate-continuous :is(p, div, span, li, td, th, blockquote, pre, code, h1, h2, h3, h4, h5, h6) {
1304
- color: inherit !important;
1305
- }
1306
- .foliate-continuous img,
1307
- .foliate-continuous svg,
1308
- .foliate-continuous video {
1309
- max-width: 100%;
1310
- height: auto;
1311
- }
1312
- :root[data-theme="light"] .foliate-continuous {
1313
- --reader-book-link: #185abc;
1314
- background: #fff;
1315
- color: #202124;
1316
- }
1317
- :root[data-theme="light"] .foliate-continuous a {
1318
- color: #185abc !important;
1319
- }
1320
- .reader-content[data-mode="foliate"] {
1321
- width: 100%;
1322
- height: calc(100vh - var(--reader-toolbar-height));
1323
- height: calc(100dvh - var(--reader-toolbar-height));
1324
- min-height: calc(100vh - var(--reader-toolbar-height));
1325
- min-height: calc(100dvh - var(--reader-toolbar-height));
1326
- padding: 0;
1327
- }
1328
- .reader-content[data-mode="foliate"] > .foliate-reader-view {
1329
- width: 100%;
1330
- height: 100%;
1331
- min-height: 320px;
1332
- }
1333
  /* Isolated HTML */
1334
  .html-frame {
1335
  display: block;
@@ -1491,8 +1418,7 @@ body {
1491
  --reader-paper: #f7f3eb;
1492
  }
1493
  .reader-viewport:has(> .reader-content:is([data-mode="text"], [data-mode="markdown"])),
1494
- .reader-content[data-mode="epub-chapters"] > .epub-frame,
1495
- .reader-content[data-mode="foliate"] > .foliate-continuous {
1496
  background-color: var(--reader-paper);
1497
  }
1498
  }
@@ -1580,10 +1506,7 @@ body {
1580
  outline: 3px solid currentColor;
1581
  outline-offset: 2px;
1582
  }
1583
- /* Shadow-root chapter links need this preference in their JS-owned stylesheet. */
1584
- .reader-content a,
1585
- .foliate-continuous a,
1586
- .foliate-continuous a[href]:not([href^="http:"]):not([href^="https:"]) {
1587
  text-decoration: underline !important;
1588
  }
1589
  .reader-pdf-text span.full-search-highlight,
@@ -1695,12 +1618,6 @@ body {
1695
  max-width: none;
1696
  overflow-wrap: anywhere;
1697
  }
1698
- .foliate-continuous {
1699
- padding: 16px 12px 48px;
1700
- }
1701
- .foliate-continuous > article {
1702
- overflow-wrap: anywhere;
1703
- }
1704
  .html-frame {
1705
  height: calc(100dvh - var(--reader-toolbar-height));
1706
  }
 
1250
  text-align: center;
1251
  line-height: 1.6;
1252
  }
1253
+ /* Chapter bundles. */
1254
  .epub-frame {
1255
  width: 100%;
1256
  height: auto;
1257
  min-height: 100%;
1258
  background: #181b1e;
1259
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1260
  /* Isolated HTML */
1261
  .html-frame {
1262
  display: block;
 
1418
  --reader-paper: #f7f3eb;
1419
  }
1420
  .reader-viewport:has(> .reader-content:is([data-mode="text"], [data-mode="markdown"])),
1421
+ .reader-content[data-mode="epub-chapters"] > .epub-frame {
 
1422
  background-color: var(--reader-paper);
1423
  }
1424
  }
 
1506
  outline: 3px solid currentColor;
1507
  outline-offset: 2px;
1508
  }
1509
+ .reader-content a {
 
 
 
1510
  text-decoration: underline !important;
1511
  }
1512
  .reader-pdf-text span.full-search-highlight,
 
1618
  max-width: none;
1619
  overflow-wrap: anywhere;
1620
  }
 
 
 
 
 
 
1621
  .html-frame {
1622
  height: calc(100dvh - var(--reader-toolbar-height));
1623
  }
static/reader.js CHANGED
@@ -1,6 +1,7 @@
1
  import { createReaderDomSearch, fullSearchEscape, fullSearchSnippet, fullSearchPageOffset } from "./reader/search/reader-dom-search.mjs";
2
  import { createReaderSearchController } from "./reader/search/reader-search-controller.mjs";
3
  import { createReaderImageLoader } from "./reader/formats/reader-image-loader.mjs";
 
4
  import "/static/reader-resources.js";
5
  import "/static/reader/core/reader-contract.js";
6
  import "/static/reader/core/reader-request-manager.js";
@@ -30,7 +31,6 @@ import {
30
  createReaderSearchBackends,
31
  createReaderPdfScheduler,
32
  createReaderNavigation,
33
- createReaderFoliateFormat,
34
  createReaderProgress,
35
  createReaderBookmarks,
36
  createReaderMediaFormat,
@@ -56,8 +56,6 @@ const readerContext = {
56
  get DISCOURSE_TITLE_SELECTOR() { return DISCOURSE_TITLE_SELECTOR; },
57
  get EPUB_HTML_TAGS() { return EPUB_HTML_TAGS; },
58
  get EPUB_HTML_VOID_TAGS() { return EPUB_HTML_VOID_TAGS; },
59
- get FOLIATE_LOADED_SECTION_LIMIT() { return FOLIATE_LOADED_SECTION_LIMIT; },
60
- get FOLIATE_PREFETCH_MARGIN() { return FOLIATE_PREFETCH_MARGIN; },
61
  get HTML_FRAME_STYLE() { return HTML_FRAME_STYLE; },
62
  get MARKED_URL() { return MARKED_URL; },
63
  get PDFJS_CMAP_URL() { return PDFJS_CMAP_URL; },
@@ -91,7 +89,6 @@ const readerContext = {
91
  get seedPdfPageGeometry() { return seedPdfPageGeometry; }, set seedPdfPageGeometry(value) { seedPdfPageGeometry = value; },
92
  get acquirePdfRenderSlot() { return acquirePdfRenderSlot; }, set acquirePdfRenderSlot(value) { acquirePdfRenderSlot = value; },
93
  get acquirePdfTextSlot() { return acquirePdfTextSlot; }, set acquirePdfTextSlot(value) { acquirePdfTextSlot = value; },
94
- get activateFoliateTocEntry() { return activateFoliateTocEntry; }, set activateFoliateTocEntry(value) { activateFoliateTocEntry = value; },
95
  get applyChapterSearchPage() { return applyChapterSearchPage; },
96
  get applyInitialRestoration() { return applyInitialRestoration; }, set applyInitialRestoration(value) { applyInitialRestoration = value; },
97
  get applyReaderMetadata() { return applyReaderMetadata; }, set applyReaderMetadata(value) { applyReaderMetadata = value; },
@@ -108,7 +105,6 @@ const readerContext = {
108
  get cancelSpeculativePdfRenders() { return cancelSpeculativePdfRenders; }, set cancelSpeculativePdfRenders(value) { cancelSpeculativePdfRenders = value; },
109
  get capability() { return capability; }, set capability(value) { capability = value; },
110
  get captureChapterPosition() { return captureChapterPosition; }, set captureChapterPosition(value) { captureChapterPosition = value; },
111
- get captureFoliateBookmarkPosition() { return captureFoliateBookmarkPosition; }, set captureFoliateBookmarkPosition(value) { captureFoliateBookmarkPosition = value; },
112
  get chapterManifestCleanup() { return chapterManifestCleanup; }, set chapterManifestCleanup(value) { chapterManifestCleanup = value; },
113
  get chapterManifestLoader() { return chapterManifestLoader; }, set chapterManifestLoader(value) { chapterManifestLoader = value; },
114
  get chapterManifestObserver() { return chapterManifestObserver; }, set chapterManifestObserver(value) { chapterManifestObserver = value; },
@@ -138,9 +134,7 @@ const readerContext = {
138
  get downloadUrl() { return downloadUrl; }, set downloadUrl(value) { downloadUrl = value; },
139
  get drainPdfTextWaiters() { return drainPdfTextWaiters; }, set drainPdfTextWaiters(value) { drainPdfTextWaiters = value; },
140
  get emptyPanel() { return emptyPanel; }, set emptyPanel(value) { emptyPanel = value; },
141
- get epubBook() { return epubBook; }, set epubBook(value) { epubBook = value; },
142
  get epubContentBody() { return epubContentBody; }, set epubContentBody(value) { epubContentBody = value; },
143
- get epubRendition() { return epubRendition; }, set epubRendition(value) { epubRendition = value; },
144
  get epubSeekFrame() { return epubSeekFrame; }, set epubSeekFrame(value) { epubSeekFrame = value; },
145
  get epubSeekPromise() { return epubSeekPromise; }, set epubSeekPromise(value) { epubSeekPromise = value; },
146
  get epubSeekTarget() { return epubSeekTarget; }, set epubSeekTarget(value) { epubSeekTarget = value; },
@@ -151,16 +145,7 @@ const readerContext = {
151
  get filterPanel() { return filterPanel; }, set filterPanel(value) { filterPanel = value; },
152
  get folderNavigationTarget() { return folderNavigationTarget; }, set folderNavigationTarget(value) { folderNavigationTarget = value; },
153
  get folderReturnUrl() { return folderReturnUrl; },
154
- get foliateChapterRepository() { return foliateChapterRepository; }, set foliateChapterRepository(value) { foliateChapterRepository = value; },
155
- get foliateContinuous() { return foliateContinuous; }, set foliateContinuous(value) { foliateContinuous = value; },
156
- get foliateScrollAnchors() { return foliateScrollAnchors; },
157
- get foliateScrollFrame() { return foliateScrollFrame; }, set foliateScrollFrame(value) { foliateScrollFrame = value; },
158
- get foliateSectionLoader() { return foliateSectionLoader; }, set foliateSectionLoader(value) { foliateSectionLoader = value; },
159
- get foliateSectionObserver() { return foliateSectionObserver; }, set foliateSectionObserver(value) { foliateSectionObserver = value; },
160
- get foliateSectionRoot() { return foliateSectionRoot; }, set foliateSectionRoot(value) { foliateSectionRoot = value; },
161
- get foliateSectionSettler() { return foliateSectionSettler; }, set foliateSectionSettler(value) { foliateSectionSettler = value; },
162
- get foliateSectionVirtualizer() { return foliateSectionVirtualizer; }, set foliateSectionVirtualizer(value) { foliateSectionVirtualizer = value; },
163
- get foliateWindowFrame() { return foliateWindowFrame; }, set foliateWindowFrame(value) { foliateWindowFrame = value; },
164
  get formatAdapters() { return formatAdapters; },
165
  get formatMediaTime() { return formatMediaTime; }, set formatMediaTime(value) { formatMediaTime = value; },
166
  get fullSearchButton() { return fullSearchButton; },
@@ -187,7 +172,6 @@ const readerContext = {
187
  get imageLoader() { return imageLoader; },
188
  get independentTextCaret() { return independentTextCaret; },
189
  get initialReaderPage() { return initialReaderPage; }, set initialReaderPage(value) { initialReaderPage = value; },
190
- get initialReaderTargetSection() { return initialReaderTargetSection; }, set initialReaderTargetSection(value) { initialReaderTargetSection = value; },
191
  get installReaderTapSelectionClear() { return installReaderTapSelectionClear; }, set installReaderTapSelectionClear(value) { installReaderTapSelectionClear = value; },
192
  get isPdfPageVisible() { return isPdfPageVisible; }, set isPdfPageVisible(value) { isPdfPageVisible = value; },
193
  get isReaderGenerationCurrent() { return isReaderGenerationCurrent; }, set isReaderGenerationCurrent(value) { isReaderGenerationCurrent = value; },
@@ -335,7 +319,6 @@ const readerContext = {
335
  get releasePdfWorker() { return releasePdfWorker; }, set releasePdfWorker(value) { releasePdfWorker = value; },
336
  get renderBookmarks() { return renderBookmarks; }, set renderBookmarks(value) { renderBookmarks = value; },
337
  get renderChapterManifest() { return renderChapterManifest; }, set renderChapterManifest(value) { renderChapterManifest = value; },
338
- get renderFoliate() { return renderFoliate; }, set renderFoliate(value) { renderFoliate = value; },
339
  get renderFullSearchResults() { return renderFullSearchResults; },
340
  get renderHtml() { return renderHtml; }, set renderHtml(value) { renderHtml = value; },
341
  get renderImageDocument() { return renderImageDocument; }, set renderImageDocument(value) { renderImageDocument = value; },
@@ -358,20 +341,17 @@ const readerContext = {
358
  get resolvedReaderData() { return resolvedReaderData; }, set resolvedReaderData(value) { resolvedReaderData = value; },
359
  get restorationFailed() { return restorationFailed; }, set restorationFailed(value) { restorationFailed = value; },
360
  get restoreChapterPosition() { return restoreChapterPosition; }, set restoreChapterPosition(value) { restoreChapterPosition = value; },
361
- get restoreFoliateBookmarkPosition() { return restoreFoliateBookmarkPosition; }, set restoreFoliateBookmarkPosition(value) { restoreFoliateBookmarkPosition = value; },
362
  get restoreFormat() { return restoreFormat; }, set restoreFormat(value) { restoreFormat = value; },
363
  get retryReaderProxy() { return retryReaderProxy; }, set retryReaderProxy(value) { retryReaderProxy = value; },
364
  get retryableReaderProxyError() { return retryableReaderProxyError; }, set retryableReaderProxyError(value) { retryableReaderProxyError = value; },
365
  get returnHistoryKey() { return returnHistoryKey; },
366
  get runFullSearch() { return runFullSearch; },
367
  get sanitizeEpubDocument() { return sanitizeEpubDocument; }, set sanitizeEpubDocument(value) { sanitizeEpubDocument = value; },
368
- get sanitizeFoliateStyles() { return sanitizeFoliateStyles; }, set sanitizeFoliateStyles(value) { sanitizeFoliateStyles = value; },
369
  get saveDeadline() { return saveDeadline; }, set saveDeadline(value) { saveDeadline = value; },
370
  get saveProgress() { return saveProgress; }, set saveProgress(value) { saveProgress = value; },
371
  get progressNotSaved() { return progressNotSaved; },
372
  get captureProgressEntry() { return captureProgressEntry; },
373
  get saveTimer() { return saveTimer; }, set saveTimer(value) { saveTimer = value; },
374
- get scheduleFoliateScrollSync() { return scheduleFoliateScrollSync; }, set scheduleFoliateScrollSync(value) { scheduleFoliateScrollSync = value; },
375
  get scheduleMarkerSync() { return scheduleMarkerSync; }, set scheduleMarkerSync(value) { scheduleMarkerSync = value; },
376
  get schedulePdfBookSearchPrefetch() { return schedulePdfBookSearchPrefetch; }, set schedulePdfBookSearchPrefetch(value) { schedulePdfBookSearchPrefetch = value; },
377
  get schedulePdfManifestPrefetch() { return schedulePdfManifestPrefetch; }, set schedulePdfManifestPrefetch(value) { schedulePdfManifestPrefetch = value; },
@@ -379,7 +359,6 @@ const readerContext = {
379
  get scheduleSave() { return scheduleSave; }, set scheduleSave(value) { scheduleSave = value; },
380
  get searchConcentratedPdf() { return searchConcentratedPdf; }, set searchConcentratedPdf(value) { searchConcentratedPdf = value; },
381
  get searchState() { return searchState; },
382
- get seekFoliateProgress() { return seekFoliateProgress; }, set seekFoliateProgress(value) { seekFoliateProgress = value; },
383
  get selectPanel() { return selectPanel; }, set selectPanel(value) { selectPanel = value; },
384
  get setPdfPageLoadingState() { return setPdfPageLoadingState; }, set setPdfPageLoadingState(value) { setPdfPageLoadingState = value; },
385
  get setReaderPanelOpen() { return setReaderPanelOpen; }, set setReaderPanelOpen(value) { setReaderPanelOpen = value; },
@@ -399,7 +378,6 @@ const readerContext = {
399
  get swfPlayer() { return swfPlayer; }, set swfPlayer(value) { swfPlayer = value; },
400
  get syncCapabilityControls() { return syncCapabilityControls; }, set syncCapabilityControls(value) { syncCapabilityControls = value; },
401
  get syncCurrentPageFromMarker() { return syncCurrentPageFromMarker; }, set syncCurrentPageFromMarker(value) { syncCurrentPageFromMarker = value; },
402
- get syncFoliateScrollLocation() { return syncFoliateScrollLocation; }, set syncFoliateScrollLocation(value) { syncFoliateScrollLocation = value; },
403
  get syncHeadingLocation() { return syncHeadingLocation; }, set syncHeadingLocation(value) { syncHeadingLocation = value; },
404
  get takePdfManifestPrefetch() { return takePdfManifestPrefetch; }, set takePdfManifestPrefetch(value) { takePdfManifestPrefetch = value; },
405
  get themeAnimationTimer() { return themeAnimationTimer; }, set themeAnimationTimer(value) { themeAnimationTimer = value; },
@@ -484,8 +462,6 @@ const readerContext = {
484
  get cancelPdfManifestPrefetch() { return cancelPdfManifestPrefetch; }, set cancelPdfManifestPrefetch(value) { cancelPdfManifestPrefetch = value; },
485
  get chapterSearchModule() { return chapterSearchModule; }, set chapterSearchModule(value) { chapterSearchModule = value; },
486
  get cleanTocLabel() { return cleanTocLabel; }, set cleanTocLabel(value) { cleanTocLabel = value; },
487
- get cloneFoliateDocument() { return cloneFoliateDocument; }, set cloneFoliateDocument(value) { cloneFoliateDocument = value; },
488
- get createFoliateSection() { return createFoliateSection; }, set createFoliateSection(value) { createFoliateSection = value; },
489
  get createHeadingLocationCache() { return createHeadingLocationCache; }, set createHeadingLocationCache(value) { createHeadingLocationCache = value; },
490
  get createPdfShellWindow() { return createPdfShellWindow; }, set createPdfShellWindow(value) { createPdfShellWindow = value; },
491
  get createTocRow() { return createTocRow; }, set createTocRow(value) { createTocRow = value; },
@@ -496,10 +472,6 @@ const readerContext = {
496
  get estimatePdfTextContentBytes() { return estimatePdfTextContentBytes; }, set estimatePdfTextContentBytes(value) { estimatePdfTextContentBytes = value; },
497
  get excerptFromCaret() { return excerptFromCaret; }, set excerptFromCaret(value) { excerptFromCaret = value; },
498
  get fetchWithReaderTimeout() { return fetchWithReaderTimeout; }, set fetchWithReaderTimeout(value) { fetchWithReaderTimeout = value; },
499
- get foliateSearchAnchor() { return foliateSearchAnchor; }, set foliateSearchAnchor(value) { foliateSearchAnchor = value; },
500
- get foliateSectionQuery() { return foliateSectionQuery; }, set foliateSectionQuery(value) { foliateSectionQuery = value; },
501
- get foliateTocEntries() { return foliateTocEntries; }, set foliateTocEntries(value) { foliateTocEntries = value; },
502
- get fullSearchFoliateMatches() { return fullSearchFoliateMatches; }, set fullSearchFoliateMatches(value) { fullSearchFoliateMatches = value; },
503
  get getPdfPersistentTextStore() { return getPdfPersistentTextStore; }, set getPdfPersistentTextStore(value) { getPdfPersistentTextStore = value; },
504
  get highlightPanelItem() { return highlightPanelItem; }, set highlightPanelItem(value) { highlightPanelItem = value; },
505
  get loadPdfEngine() { return loadPdfEngine; }, set loadPdfEngine(value) { loadPdfEngine = value; },
@@ -526,20 +498,15 @@ const readerContext = {
526
  get publishSearchResults() { return publishSearchResults; }, set publishSearchResults(value) { publishSearchResults = value; },
527
  get readPdfOcrJson() { return readPdfOcrJson; }, set readPdfOcrJson(value) { readPdfOcrJson = value; },
528
  get readerAssetObjectFamily() { return readerAssetObjectFamily; }, set readerAssetObjectFamily(value) { readerAssetObjectFamily = value; },
529
- get refreshFoliateWindow() { return refreshFoliateWindow; }, set refreshFoliateWindow(value) { refreshFoliateWindow = value; },
530
  get renderPdfImageShell() { return renderPdfImageShell; }, set renderPdfImageShell(value) { renderPdfImageShell = value; },
531
  get renderVirtualToc() { return renderVirtualToc; }, set renderVirtualToc(value) { renderVirtualToc = value; },
532
  get repairHtmlContrast() { return repairHtmlContrast; }, set repairHtmlContrast(value) { repairHtmlContrast = value; },
533
  get resolveReaderSource() { return resolveReaderSource; }, set resolveReaderSource(value) { resolveReaderSource = value; },
534
  get restoreInitialPosition() { return restoreInitialPosition; }, set restoreInitialPosition(value) { restoreInitialPosition = value; },
535
- get rewriteFoliateResources() { return rewriteFoliateResources; }, set rewriteFoliateResources(value) { rewriteFoliateResources = value; },
536
  get sanitizeOfflineHtml() { return sanitizeOfflineHtml; }, set sanitizeOfflineHtml(value) { sanitizeOfflineHtml = value; },
537
  get sanitizeReaderDocument() { return sanitizeReaderDocument; }, set sanitizeReaderDocument(value) { sanitizeReaderDocument = value; },
538
- get scheduleFoliateWindowRefresh() { return scheduleFoliateWindowRefresh; }, set scheduleFoliateWindowRefresh(value) { scheduleFoliateWindowRefresh = value; },
539
  get searchChapterBook() { return searchChapterBook; }, set searchChapterBook(value) { searchChapterBook = value; },
540
  get setBookmarkDialogModal() { return setBookmarkDialogModal; }, set setBookmarkDialogModal(value) { setBookmarkDialogModal = value; },
541
- get setupFoliateWindow() { return setupFoliateWindow; }, set setupFoliateWindow(value) { setupFoliateWindow = value; },
542
- get trimFoliateSections() { return trimFoliateSections; }, set trimFoliateSections(value) { trimFoliateSections = value; },
543
  get trimPdfManifestPrefetches() { return trimPdfManifestPrefetches; }, set trimPdfManifestPrefetches(value) { trimPdfManifestPrefetches = value; },
544
  get trimPdfSurfaces() { return trimPdfSurfaces; }, set trimPdfSurfaces(value) { trimPdfSurfaces = value; },
545
  get waitForSpreadsheetImages() { return waitForSpreadsheetImages; }, set waitForSpreadsheetImages(value) { waitForSpreadsheetImages = value; }
@@ -579,7 +546,7 @@ let {
579
 
580
  let {
581
  updateSearchState, publishSearchResults, clearSearchHighlights, chapterSearchModule,
582
- searchChapterBook, navigateChapterSearchResult, fullSearchFoliateMatches, navigateFoliateSearchResult,
583
  searchReaderText
584
  } = createReaderSearchBackends(readerContext);
585
 
@@ -600,14 +567,6 @@ let {
600
  navigateReader, notePdfScrollIntent, installReaderTapSelectionClear
601
  } = createReaderNavigation(readerContext);
602
 
603
- let {
604
- foliateSectionRoot, foliateSectionQuery, foliateSectionCandidates, syncFoliateScrollLocation,
605
- refreshFoliateWindow, scheduleFoliateWindowRefresh, trimFoliateSections, scheduleFoliateScrollSync,
606
- activateFoliateTocEntry, cloneFoliateDocument, foliateSearchAnchor, settleReaderImages,
607
- rewriteFoliateResources, createFoliateSection, setupFoliateWindow, foliateTocEntries,
608
- renderFoliate
609
- } = createReaderFoliateFormat(readerContext);
610
-
611
  let {
612
  scheduleSave, saveProgress, progressNotSaved, captureProgressEntry, placeReadingProgress, currentReaderUrl,
613
  loadReaderRestoration, getInitialReaderRestoration, initialReaderPage, readerProgressPercent,
@@ -618,8 +577,7 @@ let {
618
  } = createReaderProgress(readerContext);
619
 
620
  let {
621
- consumeBookmarkHandoff, excerptFromCaret, bookmarkExcerpt, captureFoliateBookmarkPosition,
622
- restoreFoliateBookmarkPosition, seekFoliateProgress, renderBookmarks, captureBookmarkSnapshot,
623
  setBookmarkDialogModal, openBookmarkPopover, closeBookmarkPopover
624
  } = createReaderBookmarks(readerContext);
625
 
@@ -649,7 +607,7 @@ let {
649
  } = createReaderPdfTextRuntime(readerContext);
650
 
651
  let {
652
- normalizeEpubDocument, sanitizeReaderDocument, sanitizeEpubDocument, sanitizeFoliateStyles, parseChapterDocument,
653
  epubContentBody, renderText, sanitizeOfflineHtml, buildDiscourseDocument,
654
  prepareHtmlDocument, buildHtmlFrameSource, waitForSpreadsheetImages, renderHtml,
655
  detectHtmlEncoding, repairHtmlContrast
@@ -893,29 +851,8 @@ let pdfManifestPrefetchCount = 0;
893
  let pdfManifestPrefetchWrapped = false;
894
 
895
  readerBindings.ownPdfPrefetchAndQueues();
896
- /** @type {import('../typings/reader-foliate-format-strict').FoliateView | null} */
897
- let epubRendition = null;
898
- /** @type {import('../typings/reader-foliate-format-strict').FoliateBook | null} */
899
- let epubBook = null;
900
- let foliateContinuous = false;
901
- /** @type {ReturnType<ReaderChaptersApi['createChapterRepository']> | null} */
902
- let foliateChapterRepository = null;
903
- /** @type {ReturnType<ReaderVirtualApi['createSectionVirtualizer']> | null} */
904
- let foliateSectionVirtualizer = null;
905
- /** @type {import('../typings/reader-foliate-format-strict').FoliateLoader | null} */
906
- let foliateSectionLoader = null;
907
- /** @type {(() => Promise<unknown>) | null} */
908
- let foliateSectionSettler = null;
909
- /** @type {IntersectionObserver | null} */
910
- let foliateSectionObserver = null;
911
- let foliateScrollFrame = 0, foliateWindowFrame = 0;
912
- /** @type {number | null} */
913
- let initialReaderTargetSection = null;
914
  /** @type {import('../typings/reader-entry-strict').ReaderEntryFormatState['chapterManifestCleanup']} */
915
  let chapterManifestCleanup = null;
916
- const FOLIATE_PREFETCH_SECTIONS = 6;
917
- const FOLIATE_PREFETCH_MARGIN = 4000;
918
- const FOLIATE_LOADED_SECTION_LIMIT = 12;
919
  const PDF_PREFETCH_MARGIN = 2400;
920
  const TOC_VIRTUALIZATION_THRESHOLD = 500;
921
  const TOC_VIRTUAL_ROW_HEIGHT = 40;
@@ -1083,10 +1020,11 @@ const holdReaderDestination = (target, offset = 0) => {
1083
  return release;
1084
  };
1085
 
1086
- const foliateScrollAnchors = readerRuntime.track(
 
1087
  VoiceOfMLReaderScroll.createScrollAnchorManager({
1088
  viewport,
1089
- candidates: foliateSectionCandidates
1090
  })
1091
  );
1092
 
@@ -1145,9 +1083,6 @@ readerBindings.bindSelectionAndPageLifecycle();
1145
 
1146
  // Resolve once, then keep source URLs, capability, and presentation in sync.
1147
 
1148
- // Foliate keeps a source-to-rendered text mapping because CFI addresses the
1149
- // original document, before sanitization and insertion into a shadow root.
1150
-
1151
  // Reading progress controls and undo.
1152
  const progressTools = document.createElement("div");
1153
  readerBindings.mountProgressControls();
@@ -1171,7 +1106,7 @@ readerBindings.bindProgressActions();
1171
  const domSearch = createReaderDomSearch({
1172
  content, runtime: readerRuntime, isCurrent: isReaderGenerationCurrent,
1173
  yieldTask: waitForReader, getTocEntries: () => navigationState.tocEntries,
1174
- unwrapRoot: foliateSectionRoot,
1175
  publishPage: (page, loader, partial) => {
1176
  fullSearchSession.pageLoader = loader;
1177
  fullSearchSession.page = page;
@@ -1200,8 +1135,7 @@ const fullSearchController = createReaderSearchController({
1200
  pdfClient: () => pdfBookSearchClient,
1201
  chapterResult: result => ({ ...result,
1202
  activate: (generation = readerRuntime.currentGeneration("navigation")) => navigateChapterSearchResult(result, generation) }),
1203
- activate: (result, generation) => "activate" in result
1204
- ? result.activate(generation) : navigateFoliateSearchResult(result, generation)
1205
  },
1206
  navigation: {
1207
  begin: beginReaderNavigation,
 
1
  import { createReaderDomSearch, fullSearchEscape, fullSearchSnippet, fullSearchPageOffset } from "./reader/search/reader-dom-search.mjs";
2
  import { createReaderSearchController } from "./reader/search/reader-search-controller.mjs";
3
  import { createReaderImageLoader } from "./reader/formats/reader-image-loader.mjs";
4
+ import { chapterAnchorCandidates, createImageSettler } from "./reader/core/reader-shared-content.mjs";
5
  import "/static/reader-resources.js";
6
  import "/static/reader/core/reader-contract.js";
7
  import "/static/reader/core/reader-request-manager.js";
 
31
  createReaderSearchBackends,
32
  createReaderPdfScheduler,
33
  createReaderNavigation,
 
34
  createReaderProgress,
35
  createReaderBookmarks,
36
  createReaderMediaFormat,
 
56
  get DISCOURSE_TITLE_SELECTOR() { return DISCOURSE_TITLE_SELECTOR; },
57
  get EPUB_HTML_TAGS() { return EPUB_HTML_TAGS; },
58
  get EPUB_HTML_VOID_TAGS() { return EPUB_HTML_VOID_TAGS; },
 
 
59
  get HTML_FRAME_STYLE() { return HTML_FRAME_STYLE; },
60
  get MARKED_URL() { return MARKED_URL; },
61
  get PDFJS_CMAP_URL() { return PDFJS_CMAP_URL; },
 
89
  get seedPdfPageGeometry() { return seedPdfPageGeometry; }, set seedPdfPageGeometry(value) { seedPdfPageGeometry = value; },
90
  get acquirePdfRenderSlot() { return acquirePdfRenderSlot; }, set acquirePdfRenderSlot(value) { acquirePdfRenderSlot = value; },
91
  get acquirePdfTextSlot() { return acquirePdfTextSlot; }, set acquirePdfTextSlot(value) { acquirePdfTextSlot = value; },
 
92
  get applyChapterSearchPage() { return applyChapterSearchPage; },
93
  get applyInitialRestoration() { return applyInitialRestoration; }, set applyInitialRestoration(value) { applyInitialRestoration = value; },
94
  get applyReaderMetadata() { return applyReaderMetadata; }, set applyReaderMetadata(value) { applyReaderMetadata = value; },
 
105
  get cancelSpeculativePdfRenders() { return cancelSpeculativePdfRenders; }, set cancelSpeculativePdfRenders(value) { cancelSpeculativePdfRenders = value; },
106
  get capability() { return capability; }, set capability(value) { capability = value; },
107
  get captureChapterPosition() { return captureChapterPosition; }, set captureChapterPosition(value) { captureChapterPosition = value; },
 
108
  get chapterManifestCleanup() { return chapterManifestCleanup; }, set chapterManifestCleanup(value) { chapterManifestCleanup = value; },
109
  get chapterManifestLoader() { return chapterManifestLoader; }, set chapterManifestLoader(value) { chapterManifestLoader = value; },
110
  get chapterManifestObserver() { return chapterManifestObserver; }, set chapterManifestObserver(value) { chapterManifestObserver = value; },
 
134
  get downloadUrl() { return downloadUrl; }, set downloadUrl(value) { downloadUrl = value; },
135
  get drainPdfTextWaiters() { return drainPdfTextWaiters; }, set drainPdfTextWaiters(value) { drainPdfTextWaiters = value; },
136
  get emptyPanel() { return emptyPanel; }, set emptyPanel(value) { emptyPanel = value; },
 
137
  get epubContentBody() { return epubContentBody; }, set epubContentBody(value) { epubContentBody = value; },
 
138
  get epubSeekFrame() { return epubSeekFrame; }, set epubSeekFrame(value) { epubSeekFrame = value; },
139
  get epubSeekPromise() { return epubSeekPromise; }, set epubSeekPromise(value) { epubSeekPromise = value; },
140
  get epubSeekTarget() { return epubSeekTarget; }, set epubSeekTarget(value) { epubSeekTarget = value; },
 
145
  get filterPanel() { return filterPanel; }, set filterPanel(value) { filterPanel = value; },
146
  get folderNavigationTarget() { return folderNavigationTarget; }, set folderNavigationTarget(value) { folderNavigationTarget = value; },
147
  get folderReturnUrl() { return folderReturnUrl; },
148
+ get chapterScrollAnchors() { return chapterScrollAnchors; },
 
 
 
 
 
 
 
 
 
149
  get formatAdapters() { return formatAdapters; },
150
  get formatMediaTime() { return formatMediaTime; }, set formatMediaTime(value) { formatMediaTime = value; },
151
  get fullSearchButton() { return fullSearchButton; },
 
172
  get imageLoader() { return imageLoader; },
173
  get independentTextCaret() { return independentTextCaret; },
174
  get initialReaderPage() { return initialReaderPage; }, set initialReaderPage(value) { initialReaderPage = value; },
 
175
  get installReaderTapSelectionClear() { return installReaderTapSelectionClear; }, set installReaderTapSelectionClear(value) { installReaderTapSelectionClear = value; },
176
  get isPdfPageVisible() { return isPdfPageVisible; }, set isPdfPageVisible(value) { isPdfPageVisible = value; },
177
  get isReaderGenerationCurrent() { return isReaderGenerationCurrent; }, set isReaderGenerationCurrent(value) { isReaderGenerationCurrent = value; },
 
319
  get releasePdfWorker() { return releasePdfWorker; }, set releasePdfWorker(value) { releasePdfWorker = value; },
320
  get renderBookmarks() { return renderBookmarks; }, set renderBookmarks(value) { renderBookmarks = value; },
321
  get renderChapterManifest() { return renderChapterManifest; }, set renderChapterManifest(value) { renderChapterManifest = value; },
 
322
  get renderFullSearchResults() { return renderFullSearchResults; },
323
  get renderHtml() { return renderHtml; }, set renderHtml(value) { renderHtml = value; },
324
  get renderImageDocument() { return renderImageDocument; }, set renderImageDocument(value) { renderImageDocument = value; },
 
341
  get resolvedReaderData() { return resolvedReaderData; }, set resolvedReaderData(value) { resolvedReaderData = value; },
342
  get restorationFailed() { return restorationFailed; }, set restorationFailed(value) { restorationFailed = value; },
343
  get restoreChapterPosition() { return restoreChapterPosition; }, set restoreChapterPosition(value) { restoreChapterPosition = value; },
 
344
  get restoreFormat() { return restoreFormat; }, set restoreFormat(value) { restoreFormat = value; },
345
  get retryReaderProxy() { return retryReaderProxy; }, set retryReaderProxy(value) { retryReaderProxy = value; },
346
  get retryableReaderProxyError() { return retryableReaderProxyError; }, set retryableReaderProxyError(value) { retryableReaderProxyError = value; },
347
  get returnHistoryKey() { return returnHistoryKey; },
348
  get runFullSearch() { return runFullSearch; },
349
  get sanitizeEpubDocument() { return sanitizeEpubDocument; }, set sanitizeEpubDocument(value) { sanitizeEpubDocument = value; },
 
350
  get saveDeadline() { return saveDeadline; }, set saveDeadline(value) { saveDeadline = value; },
351
  get saveProgress() { return saveProgress; }, set saveProgress(value) { saveProgress = value; },
352
  get progressNotSaved() { return progressNotSaved; },
353
  get captureProgressEntry() { return captureProgressEntry; },
354
  get saveTimer() { return saveTimer; }, set saveTimer(value) { saveTimer = value; },
 
355
  get scheduleMarkerSync() { return scheduleMarkerSync; }, set scheduleMarkerSync(value) { scheduleMarkerSync = value; },
356
  get schedulePdfBookSearchPrefetch() { return schedulePdfBookSearchPrefetch; }, set schedulePdfBookSearchPrefetch(value) { schedulePdfBookSearchPrefetch = value; },
357
  get schedulePdfManifestPrefetch() { return schedulePdfManifestPrefetch; }, set schedulePdfManifestPrefetch(value) { schedulePdfManifestPrefetch = value; },
 
359
  get scheduleSave() { return scheduleSave; }, set scheduleSave(value) { scheduleSave = value; },
360
  get searchConcentratedPdf() { return searchConcentratedPdf; }, set searchConcentratedPdf(value) { searchConcentratedPdf = value; },
361
  get searchState() { return searchState; },
 
362
  get selectPanel() { return selectPanel; }, set selectPanel(value) { selectPanel = value; },
363
  get setPdfPageLoadingState() { return setPdfPageLoadingState; }, set setPdfPageLoadingState(value) { setPdfPageLoadingState = value; },
364
  get setReaderPanelOpen() { return setReaderPanelOpen; }, set setReaderPanelOpen(value) { setReaderPanelOpen = value; },
 
378
  get swfPlayer() { return swfPlayer; }, set swfPlayer(value) { swfPlayer = value; },
379
  get syncCapabilityControls() { return syncCapabilityControls; }, set syncCapabilityControls(value) { syncCapabilityControls = value; },
380
  get syncCurrentPageFromMarker() { return syncCurrentPageFromMarker; }, set syncCurrentPageFromMarker(value) { syncCurrentPageFromMarker = value; },
 
381
  get syncHeadingLocation() { return syncHeadingLocation; }, set syncHeadingLocation(value) { syncHeadingLocation = value; },
382
  get takePdfManifestPrefetch() { return takePdfManifestPrefetch; }, set takePdfManifestPrefetch(value) { takePdfManifestPrefetch = value; },
383
  get themeAnimationTimer() { return themeAnimationTimer; }, set themeAnimationTimer(value) { themeAnimationTimer = value; },
 
462
  get cancelPdfManifestPrefetch() { return cancelPdfManifestPrefetch; }, set cancelPdfManifestPrefetch(value) { cancelPdfManifestPrefetch = value; },
463
  get chapterSearchModule() { return chapterSearchModule; }, set chapterSearchModule(value) { chapterSearchModule = value; },
464
  get cleanTocLabel() { return cleanTocLabel; }, set cleanTocLabel(value) { cleanTocLabel = value; },
 
 
465
  get createHeadingLocationCache() { return createHeadingLocationCache; }, set createHeadingLocationCache(value) { createHeadingLocationCache = value; },
466
  get createPdfShellWindow() { return createPdfShellWindow; }, set createPdfShellWindow(value) { createPdfShellWindow = value; },
467
  get createTocRow() { return createTocRow; }, set createTocRow(value) { createTocRow = value; },
 
472
  get estimatePdfTextContentBytes() { return estimatePdfTextContentBytes; }, set estimatePdfTextContentBytes(value) { estimatePdfTextContentBytes = value; },
473
  get excerptFromCaret() { return excerptFromCaret; }, set excerptFromCaret(value) { excerptFromCaret = value; },
474
  get fetchWithReaderTimeout() { return fetchWithReaderTimeout; }, set fetchWithReaderTimeout(value) { fetchWithReaderTimeout = value; },
 
 
 
 
475
  get getPdfPersistentTextStore() { return getPdfPersistentTextStore; }, set getPdfPersistentTextStore(value) { getPdfPersistentTextStore = value; },
476
  get highlightPanelItem() { return highlightPanelItem; }, set highlightPanelItem(value) { highlightPanelItem = value; },
477
  get loadPdfEngine() { return loadPdfEngine; }, set loadPdfEngine(value) { loadPdfEngine = value; },
 
498
  get publishSearchResults() { return publishSearchResults; }, set publishSearchResults(value) { publishSearchResults = value; },
499
  get readPdfOcrJson() { return readPdfOcrJson; }, set readPdfOcrJson(value) { readPdfOcrJson = value; },
500
  get readerAssetObjectFamily() { return readerAssetObjectFamily; }, set readerAssetObjectFamily(value) { readerAssetObjectFamily = value; },
 
501
  get renderPdfImageShell() { return renderPdfImageShell; }, set renderPdfImageShell(value) { renderPdfImageShell = value; },
502
  get renderVirtualToc() { return renderVirtualToc; }, set renderVirtualToc(value) { renderVirtualToc = value; },
503
  get repairHtmlContrast() { return repairHtmlContrast; }, set repairHtmlContrast(value) { repairHtmlContrast = value; },
504
  get resolveReaderSource() { return resolveReaderSource; }, set resolveReaderSource(value) { resolveReaderSource = value; },
505
  get restoreInitialPosition() { return restoreInitialPosition; }, set restoreInitialPosition(value) { restoreInitialPosition = value; },
 
506
  get sanitizeOfflineHtml() { return sanitizeOfflineHtml; }, set sanitizeOfflineHtml(value) { sanitizeOfflineHtml = value; },
507
  get sanitizeReaderDocument() { return sanitizeReaderDocument; }, set sanitizeReaderDocument(value) { sanitizeReaderDocument = value; },
 
508
  get searchChapterBook() { return searchChapterBook; }, set searchChapterBook(value) { searchChapterBook = value; },
509
  get setBookmarkDialogModal() { return setBookmarkDialogModal; }, set setBookmarkDialogModal(value) { setBookmarkDialogModal = value; },
 
 
510
  get trimPdfManifestPrefetches() { return trimPdfManifestPrefetches; }, set trimPdfManifestPrefetches(value) { trimPdfManifestPrefetches = value; },
511
  get trimPdfSurfaces() { return trimPdfSurfaces; }, set trimPdfSurfaces(value) { trimPdfSurfaces = value; },
512
  get waitForSpreadsheetImages() { return waitForSpreadsheetImages; }, set waitForSpreadsheetImages(value) { waitForSpreadsheetImages = value; }
 
546
 
547
  let {
548
  updateSearchState, publishSearchResults, clearSearchHighlights, chapterSearchModule,
549
+ searchChapterBook, navigateChapterSearchResult,
550
  searchReaderText
551
  } = createReaderSearchBackends(readerContext);
552
 
 
567
  navigateReader, notePdfScrollIntent, installReaderTapSelectionClear
568
  } = createReaderNavigation(readerContext);
569
 
 
 
 
 
 
 
 
 
570
  let {
571
  scheduleSave, saveProgress, progressNotSaved, captureProgressEntry, placeReadingProgress, currentReaderUrl,
572
  loadReaderRestoration, getInitialReaderRestoration, initialReaderPage, readerProgressPercent,
 
577
  } = createReaderProgress(readerContext);
578
 
579
  let {
580
+ consumeBookmarkHandoff, excerptFromCaret, bookmarkExcerpt, renderBookmarks, captureBookmarkSnapshot,
 
581
  setBookmarkDialogModal, openBookmarkPopover, closeBookmarkPopover
582
  } = createReaderBookmarks(readerContext);
583
 
 
607
  } = createReaderPdfTextRuntime(readerContext);
608
 
609
  let {
610
+ normalizeEpubDocument, sanitizeReaderDocument, sanitizeEpubDocument, parseChapterDocument,
611
  epubContentBody, renderText, sanitizeOfflineHtml, buildDiscourseDocument,
612
  prepareHtmlDocument, buildHtmlFrameSource, waitForSpreadsheetImages, renderHtml,
613
  detectHtmlEncoding, repairHtmlContrast
 
851
  let pdfManifestPrefetchWrapped = false;
852
 
853
  readerBindings.ownPdfPrefetchAndQueues();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  /** @type {import('../typings/reader-entry-strict').ReaderEntryFormatState['chapterManifestCleanup']} */
855
  let chapterManifestCleanup = null;
 
 
 
856
  const PDF_PREFETCH_MARGIN = 2400;
857
  const TOC_VIRTUALIZATION_THRESHOLD = 500;
858
  const TOC_VIRTUAL_ROW_HEIGHT = 40;
 
1020
  return release;
1021
  };
1022
 
1023
+ let settleReaderImages = createImageSettler(readerContext);
1024
+ const chapterScrollAnchors = readerRuntime.track(
1025
  VoiceOfMLReaderScroll.createScrollAnchorManager({
1026
  viewport,
1027
+ candidates: () => chapterAnchorCandidates(content)
1028
  })
1029
  );
1030
 
 
1083
 
1084
  // Resolve once, then keep source URLs, capability, and presentation in sync.
1085
 
 
 
 
1086
  // Reading progress controls and undo.
1087
  const progressTools = document.createElement("div");
1088
  readerBindings.mountProgressControls();
 
1106
  const domSearch = createReaderDomSearch({
1107
  content, runtime: readerRuntime, isCurrent: isReaderGenerationCurrent,
1108
  yieldTask: waitForReader, getTocEntries: () => navigationState.tocEntries,
1109
+ unwrapRoot: root => root,
1110
  publishPage: (page, loader, partial) => {
1111
  fullSearchSession.pageLoader = loader;
1112
  fullSearchSession.page = page;
 
1135
  pdfClient: () => pdfBookSearchClient,
1136
  chapterResult: result => ({ ...result,
1137
  activate: (generation = readerRuntime.currentGeneration("navigation")) => navigateChapterSearchResult(result, generation) }),
1138
+ activate: (result, generation) => result.activate(generation)
 
1139
  },
1140
  navigation: {
1141
  begin: beginReaderNavigation,
static/reader/core/reader-bindings.mjs CHANGED
@@ -22,7 +22,7 @@ export function createReaderBindings(readerContext) {
22
  if (window.VoiceOfMLReaderPdfDiagnostics === readerContext.pdfDiagnostics) delete window.VoiceOfMLReaderPdfDiagnostics;
23
  });
24
 
25
- // Polyfills for vendor engines (pdf.js, foliate): neither helper has a direct
26
  // caller in first-party code, but both are required by pinned vendor bundles.
27
  if (!Map.prototype.getOrInsertComputed) {
28
  Map.prototype.getOrInsertComputed = function (key, callback) {
@@ -274,16 +274,6 @@ export function createReaderBindings(readerContext) {
274
 
275
  function applyMetadataAndWatchSanitizedContent() {
276
  readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
277
- readerContext.contentSanitizerObserver = new MutationObserver(() => {
278
- const seen = new Set();
279
- for (const article of /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll(".foliate-continuous > article[data-section]"))) {
280
- article.querySelectorAll("style,link[rel=stylesheet]").forEach((node) => node.remove());
281
- const index = article.dataset.section;
282
- if (seen.has(index)) article.remove();
283
- else seen.add(index);
284
- }
285
- });
286
- readerContext.contentSanitizerObserver.observe(readerContext.content, { childList: true, subtree: true });
287
  readerContext.bookmarkPopover.className = "bookmark-popover";
288
  readerContext.bookmarkPopover.setAttribute("role", "dialog");
289
  readerContext.bookmarkPopover.setAttribute("aria-modal", "true");
@@ -487,34 +477,6 @@ export function createReaderBindings(readerContext) {
487
  readerContext.trackReaderResource(() => document.removeEventListener("click", readerContext.handleReaderOutsideClick));
488
  readerContext.trackReaderResource(() => { readerContext.headingLocationCache?.dispose(); readerContext.headingLocationCache = null; });
489
 
490
- document.addEventListener("click", async (event) => {
491
- const path = event.composedPath(),
492
- link = /** @type {Element | undefined} */ (path.find((node) => node instanceof Element && node.matches?.("a[href]"))),
493
- article = /** @type {HTMLElement | undefined} */ (path.find(
494
- (node) =>
495
- node instanceof Element && node.matches?.(".foliate-continuous article[data-section]")
496
- ));
497
- if (!link || !article || !readerContext.epubRendition?.book) return;
498
- const raw = link.getAttribute("href") || "";
499
- if (raw.startsWith("/api/reader-resource?")) return;
500
- if (!raw || readerContext.epubRendition.book.isExternal?.(raw) || /^(?:https?:|mailto:|tel:)/i.test(raw))
501
- return;
502
- event.preventDefault();
503
- const generation = readerContext.beginReaderNavigation(),
504
- index = Number(article.dataset.section),
505
- section = index < 0 ? readerContext.epubRendition.book.sections[-index - 1]
506
- : readerContext.epubRendition.book.sections.filter((item) => item.linear !== "no")[index];
507
- let href = raw;
508
- try {
509
- href = section?.resolveHref?.(raw) || raw;
510
- } catch (_) {}
511
- try {
512
- await readerContext.activateFoliateTocEntry({ href }, generation);
513
- } catch (error) {
514
- readerContext.reportNavigationError(error, generation);
515
- }
516
- });
517
-
518
  // Bookmark dialog owns focus and temporarily makes only its siblings inert.
519
 
520
  readerContext.bookmarkRibbon.addEventListener("click", () => readerContext.openBookmarkPopover(readerContext.bookmarkRibbon));
@@ -803,7 +765,6 @@ export function createReaderBindings(readerContext) {
803
  });
804
  window.addEventListener("pageshow", (event) => {
805
  if (event.persisted && !readerContext.readerLifecycle.disposed) {
806
- readerContext.scheduleFoliateScrollSync();
807
  readerContext.updateProgressTools();
808
  }
809
  });
 
22
  if (window.VoiceOfMLReaderPdfDiagnostics === readerContext.pdfDiagnostics) delete window.VoiceOfMLReaderPdfDiagnostics;
23
  });
24
 
25
+ // Polyfills for pdf.js: neither helper has a direct
26
  // caller in first-party code, but both are required by pinned vendor bundles.
27
  if (!Map.prototype.getOrInsertComputed) {
28
  Map.prototype.getOrInsertComputed = function (key, callback) {
 
274
 
275
  function applyMetadataAndWatchSanitizedContent() {
276
  readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
 
 
 
 
 
 
 
 
 
 
277
  readerContext.bookmarkPopover.className = "bookmark-popover";
278
  readerContext.bookmarkPopover.setAttribute("role", "dialog");
279
  readerContext.bookmarkPopover.setAttribute("aria-modal", "true");
 
477
  readerContext.trackReaderResource(() => document.removeEventListener("click", readerContext.handleReaderOutsideClick));
478
  readerContext.trackReaderResource(() => { readerContext.headingLocationCache?.dispose(); readerContext.headingLocationCache = null; });
479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  // Bookmark dialog owns focus and temporarily makes only its siblings inert.
481
 
482
  readerContext.bookmarkRibbon.addEventListener("click", () => readerContext.openBookmarkPopover(readerContext.bookmarkRibbon));
 
765
  });
766
  window.addEventListener("pageshow", (event) => {
767
  if (event.persisted && !readerContext.readerLifecycle.disposed) {
 
768
  readerContext.updateProgressTools();
769
  }
770
  });
static/reader/core/reader-contract.js CHANGED
@@ -118,12 +118,6 @@
118
  "pdf-pages": "pdf-pages",
119
  "image-pages": "image-pages",
120
  image: "image",
121
- epub: "foliate",
122
- mobi: "foliate",
123
- azw: "foliate",
124
- azw3: "foliate",
125
- fb2: "foliate",
126
- fbz: "foliate",
127
  "epub-chapters": "epub-chapters",
128
  html: "html",
129
  htm: "html",
@@ -174,14 +168,6 @@
174
  pagination: true,
175
  media: false
176
  },
177
- foliate: {
178
- toc: true,
179
- search: true,
180
- zoom: true,
181
- bookmarks: true,
182
- pagination: false,
183
- media: false
184
- },
185
  "epub-chapters": {
186
  toc: true,
187
  search: true,
 
118
  "pdf-pages": "pdf-pages",
119
  "image-pages": "image-pages",
120
  image: "image",
 
 
 
 
 
 
121
  "epub-chapters": "epub-chapters",
122
  html: "html",
123
  htm: "html",
 
168
  pagination: true,
169
  media: false
170
  },
 
 
 
 
 
 
 
 
171
  "epub-chapters": {
172
  toc: true,
173
  search: true,
static/reader/core/reader-lifecycle.mjs CHANGED
@@ -16,13 +16,11 @@
16
  * @property {number} themeAnimationTimer
17
  * @property {number} panelAnimationTimer
18
  * @property {number} markerFrame
19
- * @property {number} foliateScrollFrame
20
- * @property {number} foliateWindowFrame
21
  * @property {number} epubSeekFrame
22
  * @property {{mode: string | null} | null | undefined} capability
23
  * @property {HTMLElement} loadingIndicator
24
  * @property {HTMLElement} loadingStatus
25
- * @property {{preserve<T>(change: () => T): T}} foliateScrollAnchors
26
  * @property {(open: boolean) => unknown} setReaderPanelOpen
27
  * @property {() => unknown} stopReaderWork
28
  * @property {{dispose(): unknown}} readerRequestManager
@@ -123,8 +121,8 @@ export function createReaderLifecycle(readerContext) {
123
  }
124
 
125
  function markReaderContentReady() {
126
- if ((readerContext.capability?.mode === "foliate" || readerContext.capability?.mode === "epub-chapters") && readerContext.loadingIndicator.isConnected)
127
- readerContext.foliateScrollAnchors.preserve(() => readerContext.loadingIndicator.remove());
128
  else readerContext.loadingIndicator.remove();
129
  readerContext.loadingStatus.hidden = true;
130
  }
@@ -156,14 +154,12 @@ export function createReaderLifecycle(readerContext) {
156
  clearTimeout(readerContext.saveTimer);
157
  clearTimeout(readerContext.themeAnimationTimer);
158
  clearTimeout(readerContext.panelAnimationTimer);
159
- for (const frame of [readerContext.markerFrame, readerContext.foliateScrollFrame, readerContext.foliateWindowFrame, readerContext.epubSeekFrame])
160
  if (frame) cancelAnimationFrame(frame);
161
  readerContext.saveTimer =
162
  readerContext.themeAnimationTimer =
163
  readerContext.panelAnimationTimer =
164
  readerContext.markerFrame =
165
- readerContext.foliateScrollFrame =
166
- readerContext.foliateWindowFrame =
167
  readerContext.epubSeekFrame =
168
  0;
169
  VoiceOfMLReaderStore.dispose?.();
 
16
  * @property {number} themeAnimationTimer
17
  * @property {number} panelAnimationTimer
18
  * @property {number} markerFrame
 
 
19
  * @property {number} epubSeekFrame
20
  * @property {{mode: string | null} | null | undefined} capability
21
  * @property {HTMLElement} loadingIndicator
22
  * @property {HTMLElement} loadingStatus
23
+ * @property {{preserve<T>(change: () => T): T}} chapterScrollAnchors
24
  * @property {(open: boolean) => unknown} setReaderPanelOpen
25
  * @property {() => unknown} stopReaderWork
26
  * @property {{dispose(): unknown}} readerRequestManager
 
121
  }
122
 
123
  function markReaderContentReady() {
124
+ if (readerContext.capability?.mode === "epub-chapters" && readerContext.loadingIndicator.isConnected)
125
+ readerContext.chapterScrollAnchors.preserve(() => readerContext.loadingIndicator.remove());
126
  else readerContext.loadingIndicator.remove();
127
  readerContext.loadingStatus.hidden = true;
128
  }
 
154
  clearTimeout(readerContext.saveTimer);
155
  clearTimeout(readerContext.themeAnimationTimer);
156
  clearTimeout(readerContext.panelAnimationTimer);
157
+ for (const frame of [readerContext.markerFrame, readerContext.epubSeekFrame])
158
  if (frame) cancelAnimationFrame(frame);
159
  readerContext.saveTimer =
160
  readerContext.themeAnimationTimer =
161
  readerContext.panelAnimationTimer =
162
  readerContext.markerFrame =
 
 
163
  readerContext.epubSeekFrame =
164
  0;
165
  VoiceOfMLReaderStore.dispose?.();
static/reader/core/reader-runtime.js CHANGED
@@ -67,7 +67,7 @@
67
  navigation: { tocEntries: [], currentChapterIndex: -1 },
68
  search: { query: "", results: [], index: -1 },
69
  panel: { open: false, selected: "toc", showingAllBookmarks: false, editingBookmark: null },
70
- formats: { active: null, pdf: {}, foliate: {}, html: {}, media: {} },
71
  capability: null,
72
  ...(options.initialState || {})
73
  };
 
67
  navigation: { tocEntries: [], currentChapterIndex: -1 },
68
  search: { query: "", results: [], index: -1 },
69
  panel: { open: false, selected: "toc", showingAllBookmarks: false, editingBookmark: null },
70
+ formats: { active: null, pdf: {}, html: {}, media: {} },
71
  capability: null,
72
  ...(options.initialState || {})
73
  };
static/reader/core/reader-shared-content.mjs ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Shared content helpers for the chapter reader and HTML documents.
2
+ * @param {Element} content
3
+ */
4
+ export function chapterAnchorCandidates(content) {
5
+ return [...content.querySelectorAll('.reader-epub-chapter')].flatMap(article => [
6
+ article,
7
+ ...article.querySelectorAll(':is(h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,img,table)')
8
+ ]);
9
+ }
10
+
11
+ /** @param {{assertReaderActive: () => void, awaitReader: (value: Promise<unknown>) => Promise<unknown>}} readerContext */
12
+ export function createImageSettler(readerContext) {
13
+ /** @param {ParentNode} root @param {number} [timeoutMs] */
14
+ return async function settleReaderImages(root, timeoutMs = 2500) {
15
+ readerContext.assertReaderActive();
16
+ const images = [...root.querySelectorAll(/** @type {'img'} */ ('img[src],img[srcset]'))];
17
+ if (!images.length) return;
18
+ let timeout = 0, active = true;
19
+ /** @type {Set<() => void>} */
20
+ const cleanups = new Set();
21
+ const decoded = Promise.allSettled(images.map(async image => {
22
+ image.loading = 'eager';
23
+ image.decoding = 'async';
24
+ if (!image.complete) await /** @type {Promise<void>} */ (new Promise(resolve => {
25
+ const finish = () => {
26
+ image.removeEventListener('load', finish);
27
+ image.removeEventListener('error', finish);
28
+ cleanups.delete(finish);
29
+ resolve();
30
+ };
31
+ cleanups.add(finish);
32
+ image.addEventListener('load', finish, { once: true });
33
+ image.addEventListener('error', finish, { once: true });
34
+ if (image.complete) finish();
35
+ }));
36
+ if (active) {
37
+ try { await image.decode?.(); } catch (_) {}
38
+ }
39
+ }));
40
+ try {
41
+ await readerContext.awaitReader(Promise.race([
42
+ decoded,
43
+ new Promise(resolve => { timeout = setTimeout(resolve, timeoutMs); })
44
+ ]));
45
+ } finally {
46
+ active = false;
47
+ clearTimeout(timeout);
48
+ for (const cleanup of cleanups) cleanup();
49
+ }
50
+ };
51
+ }
static/reader/formats/reader-chapter-format.mjs CHANGED
@@ -224,10 +224,10 @@ export function createReaderChapterFormat(readerContext) {
224
  } else frame.insertBefore(article, next || null);
225
  };
226
  const preservePosition = chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration);
227
- if (preservePosition) readerContext.foliateScrollAnchors.preserve(insert);
228
  else insert();
229
  /** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).observe(article);
230
- if (preservePosition) readerContext.foliateScrollAnchors.observe(article);
231
  return article;
232
  };
233
  /** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter @param {boolean} [previous] */
@@ -253,7 +253,7 @@ export function createReaderChapterFormat(readerContext) {
253
  ".reader-epub-chapter[data-chapter], .reader-chapter-sentinel[data-chapter]");
254
  const insert = () => frame.insertBefore(marker, next || null);
255
  if (chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration))
256
- readerContext.foliateScrollAnchors.preserve(insert);
257
  else insert();
258
  /** @type {IntersectionObserver} */ (previous ? chapterPreviousObserver : readerContext.chapterManifestObserver).observe(marker);
259
  return marker;
@@ -425,7 +425,7 @@ export function createReaderChapterFormat(readerContext) {
425
  readerContext.assertReaderActive();
426
  if (loaded.has(chapter.index)) return Promise.resolve();
427
  return chapterScheduler.load(chapter.index, demand, exclusive).then(() => {
428
- readerContext.foliateScrollAnchors.whenIdle(trimChapterWindow);
429
  }).catch(error => {
430
  if (error.name !== "AbortError" && !readerContext.readerAbortController.signal.aborted) {
431
  const marker = ensureSentinel(chapter);
@@ -454,11 +454,11 @@ export function createReaderChapterFormat(readerContext) {
454
  } catch (_) {}
455
  const anchor = chapterTarget(/** @type {Element} */ (node), id);
456
  if (!anchor) throw new Error("EPUB_MISSING_ANCHOR");
457
- readerContext.foliateScrollAnchors.invalidate();
458
  // Measure the anchor instead of using scrollIntoView: the demanded landing line is
459
  // this viewport's top edge, and scrollIntoView can also move ancestor scrollers.
460
  readerContext.alignReaderDestination(anchor);
461
- readerContext.foliateScrollAnchors.remember();
462
  // Chapter images and lazy placeholders keep changing height after the jump; hold
463
  // the anchor on the landing line until the layout settles.
464
  readerContext.holdReaderDestination(anchor);
@@ -559,7 +559,7 @@ export function createReaderChapterFormat(readerContext) {
559
  marker.style.marginBottom = style.marginBottom;
560
  marker.setAttribute("aria-hidden", "true");
561
  /** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).unobserve(article);
562
- readerContext.foliateScrollAnchors.unobserve(article);
563
  for (const entry of chapterTocEntries(index)) entry.target = null;
564
  for (const image of article.querySelectorAll("img")) image.removeAttribute("src");
565
  article.replaceWith(marker);
@@ -569,7 +569,7 @@ export function createReaderChapterFormat(readerContext) {
569
  chapterBudget.release(retainedBytes.get(index));
570
  retainedBytes.delete(index);
571
  },
572
- preserve: change => readerContext.foliateScrollAnchors.preserve(change)
573
  });
574
  function trimChapterWindow() {
575
  if (chapterWindowReady && !chapterNavigating) chapterVirtualizer.trim(navigationTargetChapter || chapterFocusIndex);
@@ -611,7 +611,7 @@ export function createReaderChapterFormat(readerContext) {
611
  current.top < view.bottom)
612
  fetchChapter(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(chapterFocusIndex))).catch(() => {});
613
  if (!chapterNavigating) chapterScheduler.prefetch(chapterPrefetchIndices());
614
- readerContext.foliateScrollAnchors.whenIdle(trimChapterWindow);
615
  }
616
  function scheduleChapterWindow() {
617
  if (!chapterWindowFrame) chapterWindowFrame = requestAnimationFrame(refreshChapterWindow);
@@ -657,7 +657,7 @@ export function createReaderChapterFormat(readerContext) {
657
  if (limit !== progressEnd.limit || limit - viewport.scrollTop > 1) {
658
  progressEnd.limit = limit;
659
  viewport.scrollTop = limit;
660
- readerContext.foliateScrollAnchors.remember();
661
  }
662
  }
663
  readerContext.updateProgressTools();
@@ -739,8 +739,8 @@ export function createReaderChapterFormat(readerContext) {
739
  });
740
  }
741
  chapterWindowReady = true;
742
- if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.foliateScrollAnchors.invalidate();
743
- for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.foliateScrollAnchors.observe(article);
744
  frame.style.overflowAnchor = "none";
745
  scheduleChapterWindow();
746
  readerContext.assertReaderActive();
@@ -798,7 +798,7 @@ export function createReaderChapterFormat(readerContext) {
798
  : chapterProgressHeight(rect, marker, last) * progressFraction;
799
  viewport.scrollTop += rect.top - marker + offset;
800
  }
801
- readerContext.foliateScrollAnchors.remember();
802
  readerContext.syncHeadingLocation();
803
  readerContext.updateProgressTools();
804
  readerContext.scheduleSave();
 
224
  } else frame.insertBefore(article, next || null);
225
  };
226
  const preservePosition = chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration);
227
+ if (preservePosition) readerContext.chapterScrollAnchors.preserve(insert);
228
  else insert();
229
  /** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).observe(article);
230
+ if (preservePosition) readerContext.chapterScrollAnchors.observe(article);
231
  return article;
232
  };
233
  /** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter @param {boolean} [previous] */
 
253
  ".reader-epub-chapter[data-chapter], .reader-chapter-sentinel[data-chapter]");
254
  const insert = () => frame.insertBefore(marker, next || null);
255
  if (chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration))
256
+ readerContext.chapterScrollAnchors.preserve(insert);
257
  else insert();
258
  /** @type {IntersectionObserver} */ (previous ? chapterPreviousObserver : readerContext.chapterManifestObserver).observe(marker);
259
  return marker;
 
425
  readerContext.assertReaderActive();
426
  if (loaded.has(chapter.index)) return Promise.resolve();
427
  return chapterScheduler.load(chapter.index, demand, exclusive).then(() => {
428
+ readerContext.chapterScrollAnchors.whenIdle(trimChapterWindow);
429
  }).catch(error => {
430
  if (error.name !== "AbortError" && !readerContext.readerAbortController.signal.aborted) {
431
  const marker = ensureSentinel(chapter);
 
454
  } catch (_) {}
455
  const anchor = chapterTarget(/** @type {Element} */ (node), id);
456
  if (!anchor) throw new Error("EPUB_MISSING_ANCHOR");
457
+ readerContext.chapterScrollAnchors.invalidate();
458
  // Measure the anchor instead of using scrollIntoView: the demanded landing line is
459
  // this viewport's top edge, and scrollIntoView can also move ancestor scrollers.
460
  readerContext.alignReaderDestination(anchor);
461
+ readerContext.chapterScrollAnchors.remember();
462
  // Chapter images and lazy placeholders keep changing height after the jump; hold
463
  // the anchor on the landing line until the layout settles.
464
  readerContext.holdReaderDestination(anchor);
 
559
  marker.style.marginBottom = style.marginBottom;
560
  marker.setAttribute("aria-hidden", "true");
561
  /** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).unobserve(article);
562
+ readerContext.chapterScrollAnchors.unobserve(article);
563
  for (const entry of chapterTocEntries(index)) entry.target = null;
564
  for (const image of article.querySelectorAll("img")) image.removeAttribute("src");
565
  article.replaceWith(marker);
 
569
  chapterBudget.release(retainedBytes.get(index));
570
  retainedBytes.delete(index);
571
  },
572
+ preserve: change => readerContext.chapterScrollAnchors.preserve(change)
573
  });
574
  function trimChapterWindow() {
575
  if (chapterWindowReady && !chapterNavigating) chapterVirtualizer.trim(navigationTargetChapter || chapterFocusIndex);
 
611
  current.top < view.bottom)
612
  fetchChapter(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(chapterFocusIndex))).catch(() => {});
613
  if (!chapterNavigating) chapterScheduler.prefetch(chapterPrefetchIndices());
614
+ readerContext.chapterScrollAnchors.whenIdle(trimChapterWindow);
615
  }
616
  function scheduleChapterWindow() {
617
  if (!chapterWindowFrame) chapterWindowFrame = requestAnimationFrame(refreshChapterWindow);
 
657
  if (limit !== progressEnd.limit || limit - viewport.scrollTop > 1) {
658
  progressEnd.limit = limit;
659
  viewport.scrollTop = limit;
660
+ readerContext.chapterScrollAnchors.remember();
661
  }
662
  }
663
  readerContext.updateProgressTools();
 
739
  });
740
  }
741
  chapterWindowReady = true;
742
+ if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate();
743
+ for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(article);
744
  frame.style.overflowAnchor = "none";
745
  scheduleChapterWindow();
746
  readerContext.assertReaderActive();
 
798
  : chapterProgressHeight(rect, marker, last) * progressFraction;
799
  viewport.scrollTop += rect.top - marker + offset;
800
  }
801
+ readerContext.chapterScrollAnchors.remember();
802
  readerContext.syncHeadingLocation();
803
  readerContext.updateProgressTools();
804
  readerContext.scheduleSave();
static/reader/formats/reader-foliate-format.mjs DELETED
@@ -1,773 +0,0 @@
1
- import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs";
2
-
3
- /** @param {import('../../../typings/reader-foliate-format-strict').FoliateFormatContext} readerContext */
4
- export function createReaderFoliateFormat(readerContext) {
5
- /** @param {Element} article */
6
- function foliateSectionRoot(article) {
7
- return article?.shadowRoot || article;
8
- }
9
-
10
- /** @param {Element} article @param {string} selector */
11
- function foliateSectionQuery(article, selector) {
12
- return readerContext.foliateSectionRoot(article)?.querySelector(selector) || null;
13
- }
14
-
15
- function foliateSectionCandidates() {
16
- return [
17
- ...readerContext.content.querySelectorAll(
18
- ".foliate-continuous > article[data-section]:not(.foliate-section-placeholder), .reader-epub-chapter"
19
- )
20
- ].flatMap((article) => [
21
- article,
22
- ...readerContext.foliateSectionRoot(article).querySelectorAll(
23
- ":is(h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,img,table)"
24
- )
25
- ]);
26
- }
27
-
28
- /** @typedef {{sectionIndex: number, anchor?: import('../../../typings/reader-foliate-format-strict').FoliateAnchor | null, fragment?: string, target?: {getBoundingClientRect(): {top: number}} | null}} LocationEntry */
29
- /** @param {unknown} entry @returns {entry is LocationEntry} */
30
- function isFoliateLocationEntry(entry) {
31
- if (typeof entry !== "object" || entry === null || !("sectionIndex" in entry) || typeof entry.sectionIndex !== "number") return false;
32
- if ("anchor" in entry && entry.anchor != null && typeof entry.anchor !== "function") return false;
33
- if ("fragment" in entry && entry.fragment !== undefined && typeof entry.fragment !== "string") return false;
34
- if ("target" in entry && entry.target != null && (typeof entry.target !== "object" || !("getBoundingClientRect" in entry.target) || typeof entry.target.getBoundingClientRect !== "function")) return false;
35
- return true;
36
- }
37
-
38
- /** @type {unknown[] | undefined} */
39
- let indexedToc;
40
- /** @type {Map<number, [number, LocationEntry][]>} */
41
- const locations = new Map();
42
-
43
- /** @param {unknown[]} entries @param {number} section */
44
- function sectionLocations(entries, section) {
45
- // Foliate resolves sectionIndex before publishing a new TOC array.
46
- if (indexedToc !== entries) {
47
- indexedToc = entries;
48
- locations.clear();
49
- for (const [index, entry] of entries.entries()) {
50
- if (!isFoliateLocationEntry(entry)) continue;
51
- const key = entry.sectionIndex;
52
- if (Number.isNaN(key)) continue;
53
- const bucket = locations.get(key);
54
- if (bucket) bucket.push([index, entry]);
55
- else locations.set(key, [[index, entry]]);
56
- }
57
- }
58
- return locations.get(section) || [];
59
- }
60
-
61
- function syncFoliateScrollLocation() {
62
- const toc = readerContext.navigationState.tocEntries;
63
- if (!readerContext.foliateContinuous || !toc.length) return;
64
- const rows = /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll(".foliate-continuous article[data-section]")),
65
- top = readerContext.viewport.getBoundingClientRect().top + 80;
66
- let sectionTop = 0, sectionNode = null;
67
- for (const row of rows) {
68
- if (row.hidden) continue;
69
- const rowTop = row.getBoundingClientRect().top;
70
- if (rowTop <= top) { sectionTop = rowTop; sectionNode = row; }
71
- }
72
- if (!sectionNode) return;
73
- const entries = sectionLocations(toc, Number(sectionNode.dataset.section));
74
- let best = -1;
75
- let bestPosition = -Infinity;
76
- for (const [index, entry] of entries) {
77
- let position = sectionTop;
78
- try {
79
- if (entry.anchor) {
80
- const root = readerContext.foliateSectionRoot(sectionNode);
81
- const anchor = entry.anchor({
82
- getElementById: (id) => root.querySelector(`[id="${CSS.escape(id)}"]`),
83
- querySelector: (selector) => root.querySelector(selector)
84
- });
85
- if (anchor) position = anchor.getBoundingClientRect().top;
86
- }
87
- if (entry.fragment) {
88
- const anchor = readerContext.foliateSectionQuery(
89
- sectionNode,
90
- `[id="${CSS.escape(entry.fragment)}"], [name="${CSS.escape(entry.fragment)}"]`
91
- );
92
- if (anchor) position = anchor.getBoundingClientRect().top;
93
- }
94
- } catch (_) { continue; }
95
- if (position <= top && (position > bestPosition || (position === bestPosition && index > best))) {
96
- best = index;
97
- bestPosition = position;
98
- }
99
- }
100
- if (best < 0) {
101
- let firstPosition = Infinity;
102
- for (const [index, entry] of entries) {
103
- let position;
104
- try { position = entry.target?.getBoundingClientRect?.().top; } catch (_) { continue; }
105
- if (position !== undefined && Number.isFinite(position) && position < firstPosition) {
106
- best = index;
107
- firstPosition = position;
108
- }
109
- }
110
- }
111
- if (best >= 0 && best !== readerContext.navigationState.currentChapterIndex) {
112
- readerContext.updateNavigationState({ currentChapterIndex: best });
113
- readerContext.updateTocCurrentMark();
114
- readerContext.updateProgressTools();
115
- }
116
- }
117
-
118
- function refreshFoliateWindow() {
119
- readerContext.foliateWindowFrame = 0;
120
- readerContext.foliateSectionLoader?.refresh?.();
121
- }
122
-
123
- function scheduleFoliateWindowRefresh() {
124
- if (!readerContext.foliateWindowFrame) readerContext.foliateWindowFrame = requestAnimationFrame(readerContext.refreshFoliateWindow);
125
- }
126
-
127
- function trimFoliateSections() {
128
- if (!readerContext.foliateContinuous || !readerContext.foliateSectionVirtualizer ||
129
- readerContext.content.querySelector(".foliate-supplement-active")) return;
130
- const marker = readerContext.viewport.getBoundingClientRect().top + 80,
131
- rows = [...document.querySelectorAll(".foliate-continuous article[data-section]")].map(row => /** @type {HTMLElement} */ (row)),
132
- current =
133
- rows.find((row) => {
134
- const rect = row.getBoundingClientRect();
135
- return rect.top <= marker && rect.bottom > marker;
136
- }) || rows.find((row) => row.getBoundingClientRect().top > marker);
137
- if (current) readerContext.foliateSectionVirtualizer.trim(Number(current.dataset.section));
138
- }
139
-
140
- function scheduleFoliateScrollSync() {
141
- if (readerContext.foliateScrollFrame) return;
142
- readerContext.foliateScrollFrame = requestAnimationFrame(() => {
143
- readerContext.foliateScrollFrame = 0;
144
- readerContext.syncFoliateScrollLocation();
145
- readerContext.foliateScrollAnchors.whenIdle(readerContext.trimFoliateSections);
146
- });
147
- }
148
-
149
- /** @param {import('../../../typings/reader-foliate-format-strict').FoliateTocEntry} entry @param {number} [generation] @param {{closePanel?: boolean}} [options] */
150
- async function activateFoliateTocEntry(entry, generation = readerContext.beginReaderNavigation(), { closePanel = true } = {}) {
151
- const book = readerContext.epubRendition?.book,
152
- href = String(entry.href || ""),
153
- target = await readerContext.epubRendition?.book?.resolveHref(href);
154
- if (!book || !target || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
155
- const section = target && book.sections[target.index],
156
- sections = book.sections.filter((item) => item.linear !== "no"),
157
- visibleIndex = section ? sections.indexOf(section) : -1,
158
- destinationIndex = visibleIndex >= 0 ? visibleIndex : -target.index - 1;
159
- if (!section || !readerContext.foliateSectionLoader) return false;
160
- let node = await readerContext.foliateSectionLoader(destinationIndex);
161
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
162
- // Background neighbors are not part of a demanded TOC destination.
163
- await readerContext.waitForReader(0, true);
164
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
165
- if (!node?.isConnected) node = await readerContext.foliateSectionLoader(destinationIndex);
166
- if (!node?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
167
- const root = readerContext.foliateSectionRoot(node),
168
- /** @type {import('../../../typings/reader-foliate-format-strict').FoliateAnchorDocument} */
169
- anchorDocument = {
170
- getElementById: (id) => root.querySelector(`[id="${CSS.escape(id)}"]`),
171
- querySelector: (selector) => root.querySelector(selector)
172
- };
173
- let anchor = null;
174
- try {
175
- anchor = typeof target.anchor === "function" ? target.anchor(anchorDocument) : null;
176
- } catch (_) {}
177
- if (!anchor) {
178
- try {
179
- const fragment = href.split("#")[1] || "",
180
- id = fragment ? decodeURIComponent(fragment) : "";
181
- anchor = id ? root.querySelector(`[id="${CSS.escape(id)}"], [name="${CSS.escape(id)}"]`) : null;
182
- } catch (_) {}
183
- }
184
- const destination = anchor || node;
185
- readerContext.foliateScrollAnchors.invalidate();
186
- const landing = readerContext.alignReaderDestination(destination, 8);
187
- readerContext.foliateScrollAnchors.remember();
188
- // Section heights and images keep settling after the jump; hold the destination on
189
- // the landing line until the layout stops moving.
190
- readerContext.holdReaderDestination(destination, 8);
191
- readerContext.syncFoliateScrollLocation();
192
- readerContext.updateTocCurrentMark();
193
- readerContext.updateProgressTools();
194
- readerContext.scheduleSave();
195
- if (closePanel) readerContext.setReaderPanelOpen(false, true);
196
- readerContext.foliateScrollAnchors.remember();
197
- return true;
198
- }
199
-
200
- /** @param {Document} source */
201
- function cloneFoliateDocument(source) {
202
- const doc = /** @type {Document} */ (source.cloneNode(true)),
203
- original = source.createTreeWalker(source, NodeFilter.SHOW_TEXT),
204
- cloned = doc.createTreeWalker(doc, NodeFilter.SHOW_TEXT);
205
- /** @type {WeakMap<Node, Node>} */
206
- const sourceNodes = new WeakMap();
207
- while (original.nextNode() && cloned.nextNode())
208
- sourceNodes.set(cloned.currentNode, original.currentNode);
209
- return { doc: readerContext.sanitizeEpubDocument(doc, { keepBlobImports: true }), sourceNodes };
210
- }
211
-
212
- /** @param {Document} source @param {WeakMap<Node, Node>} sourceNodes @param {Element} body @param {Element} renderedBody */
213
- function foliateSearchAnchor(source, sourceNodes, body, renderedBody) {
214
- const sourceWalker = body.ownerDocument.createTreeWalker(body, NodeFilter.SHOW_TEXT);
215
- /** @type {{original: Text; offset: number}[]} */
216
- const pairs = [];
217
- let offset = 0;
218
- while (sourceWalker.nextNode()) {
219
- const node = /** @type {Text} */ (sourceWalker.currentNode);
220
- const original = sourceNodes.get(node);
221
- if (original) pairs.push({ original: /** @type {Text} */ (original), offset });
222
- offset += node.length;
223
- }
224
- return (/** @type {import('../../../typings/reader-foliate-format-strict').SearchAnchor} */ anchor) => {
225
- const range = anchor(source);
226
- if (!range || typeof range.intersectsNode !== "function") return null;
227
- const intervals = [];
228
- for (const { original, offset } of pairs) {
229
- if (!range.intersectsNode(original)) continue;
230
- const start = range.startContainer === original ? range.startOffset : 0;
231
- const end = range.endContainer === original ? range.endOffset : original.length;
232
- if (end > start) intervals.push({ start: offset + start, end: offset + end });
233
- }
234
- const walker = document.createTreeWalker(renderedBody, NodeFilter.SHOW_TEXT),
235
- selected = [];
236
- let offset = 0;
237
- while (walker.nextNode()) {
238
- const node = /** @type {Text} */ (walker.currentNode),
239
- end = offset + node.length;
240
- for (const interval of intervals)
241
- if (interval.start < end && interval.end > offset)
242
- selected.push({
243
- node,
244
- start: Math.max(0, interval.start - offset),
245
- end: Math.min(node.length, interval.end - offset)
246
- });
247
- offset = end;
248
- }
249
- return selected;
250
- };
251
- }
252
-
253
- /** @param {ParentNode} root @param {number} [timeoutMs] */
254
- async function settleReaderImages(root, timeoutMs = 2500) {
255
- readerContext.assertReaderActive();
256
- const images = [...root.querySelectorAll(/** @type {'img'} */ ("img[src],img[srcset]"))];
257
- if (!images.length) return;
258
- let timeout = 0, active = true;
259
- /** @type {Set<() => void>} */
260
- const cleanups = new Set();
261
- const decoded = Promise.allSettled(
262
- images.map(async (image) => {
263
- // Sections are prepared off-DOM; lazy images cannot enter a viewport yet.
264
- image.loading = "eager";
265
- image.decoding = "async";
266
- if (!image.complete) await /** @type {Promise<void>} */ (new Promise((resolve) => {
267
- const finish = () => {
268
- image.removeEventListener("load", finish);
269
- image.removeEventListener("error", finish);
270
- cleanups.delete(finish);
271
- resolve();
272
- };
273
- cleanups.add(finish);
274
- image.addEventListener("load", finish, { once: true });
275
- image.addEventListener("error", finish, { once: true });
276
- if (image.complete) finish();
277
- }));
278
- if (active) {
279
- try { await image.decode?.(); } catch (_) {}
280
- }
281
- })
282
- );
283
- try {
284
- await readerContext.awaitReader(
285
- Promise.race([
286
- decoded,
287
- new Promise((resolve) => {
288
- timeout = setTimeout(resolve, timeoutMs);
289
- })
290
- ])
291
- );
292
- } finally {
293
- active = false;
294
- clearTimeout(timeout);
295
- for (const cleanup of cleanups) cleanup();
296
- }
297
- }
298
-
299
- /** @param {Document} doc @param {import('../../../typings/reader-foliate-format-strict').FoliateSection} section */
300
- function rewriteFoliateResources(doc, section) {
301
- /** @param {string | null | undefined} value */
302
- const safeEmbeddedValue = (value) =>
303
- /^(?:blob:|data:image\/(?:gif|png|jpe?g|webp);)/i.test(String(value || "").trim());
304
- /** @param {string | null | undefined} value */
305
- const archiveResourceUrl = (value) => {
306
- const valueText = String(value || "").trim();
307
- if (!valueText || valueText.startsWith("#") || safeEmbeddedValue(valueText))
308
- return safeEmbeddedValue(valueText) ? valueText : null;
309
- const hash = valueText.indexOf("#"),
310
- raw = hash < 0 ? valueText : valueText.slice(0, hash);
311
- let fragment = "";
312
- try {
313
- if (hash >= 0) fragment = `#${encodeURIComponent(decodeURIComponent(valueText.slice(hash + 1)))}`;
314
- } catch (_) { return null; }
315
- if (!raw || /[?#\\\x00-\x1f\x7f]/.test(raw)) return null;
316
- if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(raw)) return null;
317
- try {
318
- const resolved = String(
319
- (section.resolveResourceHref
320
- ? section.resolveResourceHref(raw)
321
- : section.resolveHref?.(raw)) || ""
322
- );
323
- if (
324
- !resolved ||
325
- /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(resolved) ||
326
- /[\\\x00]/.test(resolved) ||
327
- resolved.split("/").some((part) => !part || part === "." || part === "..")
328
- )
329
- return null;
330
- return `/api/reader-resource?book=${encodeURIComponent(readerContext.sourceUrl)}&path=${encodeURIComponent(resolved)}${fragment}`;
331
- } catch (_) {
332
- return null;
333
- }
334
- };
335
- // Every src-bearing element (including input[type=image] and track) uses
336
- // the archive-only resource policy, not just images and media.
337
- for (const element of doc.querySelectorAll("[src],video[poster]")) {
338
- for (const name of ["src", "poster"])
339
- if (element.hasAttribute(name)) {
340
- const safe = archiveResourceUrl(element.getAttribute(name));
341
- if (safe) element.setAttribute(name, safe);
342
- else element.removeAttribute(name);
343
- }
344
- }
345
- for (const element of doc.querySelectorAll("[srcset]")) {
346
- const value = element.getAttribute("srcset") || "";
347
- const candidates = value
348
- .split(",")
349
- .map((part) => {
350
- const [raw, ...descriptor] = part.trim().split(/\s+/);
351
- const safe = archiveResourceUrl(raw);
352
- return safe ? [safe, ...descriptor].join(" ") : null;
353
- })
354
- .filter(Boolean);
355
- if (candidates.length) element.setAttribute("srcset", candidates.join(", "));
356
- else element.removeAttribute("srcset");
357
- }
358
- for (const image of doc.querySelectorAll("image")) {
359
- const value =
360
- image.getAttributeNS("http://www.w3.org/1999/xlink", "href") ||
361
- image.getAttribute("xlink:href") ||
362
- image.getAttribute("href");
363
- const safe = archiveResourceUrl(value);
364
- if (safe) {
365
- image.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", safe);
366
- image.setAttribute("href", safe);
367
- } else {
368
- image.removeAttributeNS("http://www.w3.org/1999/xlink", "href");
369
- image.removeAttribute("xlink:href");
370
- image.removeAttribute("href");
371
- }
372
- }
373
- // Other SVG references (feImage, use, textPath...) may only point inside the
374
- // chapter; feImage may also use a packaged image like <image>.
375
- for (const element of doc.querySelectorAll("*")) {
376
- if (element.namespaceURI !== "http://www.w3.org/2000/svg" || ["a", "image"].includes(element.localName)) continue;
377
- for (const attribute of [...element.attributes]) {
378
- if (attribute.localName !== "href" ||
379
- (attribute.namespaceURI && attribute.namespaceURI !== "http://www.w3.org/1999/xlink")) continue;
380
- const value = attribute.value.trim();
381
- if (value.startsWith("#")) continue;
382
- const safe = element.localName === "feImage" ? archiveResourceUrl(value) : null;
383
- if (safe) attribute.value = safe;
384
- else element.removeAttributeNode(attribute);
385
- }
386
- }
387
- for (const link of doc.querySelectorAll(/** @type {'a'} */ ("a[href]"))) {
388
- const href = link.getAttribute("href") || "";
389
- // An in-book link to a packaged image opens the image itself, not a dead chapter URL.
390
- if (/\.(?:gif|png|jpe?g|webp)(?:#.*)?$/i.test(href)) {
391
- const resource = archiveResourceUrl(href);
392
- if (resource) {
393
- link.setAttribute("href", resource);
394
- link.target = "_blank";
395
- link.rel = "noopener noreferrer";
396
- }
397
- }
398
- if (/^(?:https?:|mailto:|tel:)/i.test(href)) {
399
- link.target = "_blank";
400
- link.rel = "noopener noreferrer";
401
- }
402
- }
403
- }
404
-
405
- /** @param {import('../../../typings/reader-foliate-format-strict').FoliateSection} section @param {number} index @param {AbortSignal} [signal] @param {'high' | 'low'} [priority] */
406
- async function createFoliateSection(section, index, signal, priority) {
407
- signal = signal || readerContext.readerAbortController.signal;
408
- priority = priority || "high";
409
- const source = await readerContext.awaitReader(section.createDocument(), signal);
410
- const { doc, sourceNodes } = readerContext.cloneFoliateDocument(source);
411
- readerContext.assertReaderActive();
412
- readerContext.rewriteFoliateResources(doc, section);
413
- // Packaged CSS is loaded from Foliate blob: URLs; inline it sanitized so
414
- // remote url()/@import references cannot bypass the archive-only policy.
415
- const styles = await readerContext.sanitizeFoliateStyles([...doc.querySelectorAll("style,link")]);
416
- signal.throwIfAborted();
417
- readerContext.assertReaderActive();
418
- for (const node of doc.querySelectorAll("style,link")) node.remove();
419
- const article = /** @type {import('../../../typings/reader-foliate-format-strict').FoliateArticle} */ (document.createElement("article"));
420
- article.dataset.section = String(index);
421
- const shadow = article.attachShadow({ mode: "open" }),
422
- baseStyle = document.createElement("style"),
423
- layoutStyle = document.createElement("style"),
424
- sectionBody = document.createElement("div");
425
- // Chapter styles live in a shadow root, so document-level preferences cannot reach them.
426
- baseStyle.textContent = `
427
- :host { display: block; color: inherit; }
428
- * { box-sizing: border-box; }
429
- .reader-section-body { display: block; color: inherit; line-height: inherit; }
430
- .reader-section-body > :first-child { margin-top: 0 !important; }
431
- :host(.reader-document-dark) .reader-section-body,
432
- :host(.reader-document-dark) .reader-section-body :where(:not(svg, svg *, img, canvas, video, audio, math, math *)) {
433
- color: inherit !important;
434
- background-color: transparent !important;
435
- border-color: #4a5056 !important;
436
- text-shadow: none !important;
437
- }
438
- a { color: var(--reader-book-link) !important; }
439
- :host(.reader-document-dark) .reader-section-body a { color: var(--reader-book-link) !important; }
440
- img, svg, video { max-width: 100%; height: auto; }
441
- mark.full-search-highlight { background: #ffd54f; color: #111; }
442
- :host(.reader-document-dark) .reader-section-body mark.full-search-highlight { background: #ffd54f !important; color: #111 !important; }
443
- @media (prefers-contrast: more) {
444
- .reader-section-body a[href] { text-decoration: underline !important; }
445
- .reader-section-body mark.full-search-highlight { outline: 2px solid currentColor; }
446
- }
447
- `;
448
- sectionBody.className = "reader-section-body";
449
- const body = readerContext.epubContentBody(doc);
450
- // Import the sanitized nodes directly. Serializing and reparsing legacy
451
- // nested anchors lets HTML's adoption rules reorder footnotes and citations.
452
- if (body)
453
- sectionBody.append(...[...body.childNodes].map((node) => document.importNode(node, true)));
454
- wrapEbookTables(sectionBody);
455
- article._resolveSearchAnchor = readerContext.foliateSearchAnchor(source, sourceNodes, body, sectionBody);
456
- layoutStyle.textContent = EBOOK_LAYOUT_STYLE;
457
- shadow.append(baseStyle, ...styles, layoutStyle, sectionBody);
458
- for (const image of sectionBody.querySelectorAll("img")) {
459
- image.loading = priority === "high" ? "eager" : "lazy";
460
- image.fetchPriority = priority;
461
- image.decoding = "async";
462
- }
463
- signal.throwIfAborted();
464
- readerContext.assertReaderActive();
465
- article.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark");
466
- return article;
467
- }
468
-
469
- /** @param {HTMLElement} stream @param {import('../../../typings/reader-foliate-format-strict').FoliateSection[]} sections */
470
- function setupFoliateWindow(stream, sections) {
471
- let focus = readerContext.initialReaderTargetSection ?? 0, targetPending = false;
472
- stream.style.overflowAnchor = "none";
473
- /** @param {number} index */
474
- const existing = index => /** @type {import('../../../typings/reader-foliate-format-strict').FoliateArticle | null} */ (stream.querySelector(`article[data-section="${index}"]:not(.foliate-section-placeholder)`));
475
- /** @param {number} index */
476
- const ensurePlaceholder = index => {
477
- if (!sections[index] || stream.querySelector(`article[data-section="${index}"]`)) return;
478
- const placeholder = document.createElement("article");
479
- placeholder.className = "foliate-section-placeholder";
480
- placeholder.dataset.section = String(index);
481
- placeholder.hidden = stream.classList.contains("foliate-supplement-active");
482
- placeholder.style.setProperty("--foliate-placeholder-height", `${Math.max(400, readerContext.viewport.clientHeight)}px`);
483
- placeholder.setAttribute("aria-label", `加载第 ${index + 1} 节`);
484
- const next = [...stream.children].find(node => Number(/** @type {HTMLElement} */ (node).dataset.section) > index);
485
- readerContext.foliateScrollAnchors.preserve(() => stream.insertBefore(placeholder, next || null));
486
- observer.observe(placeholder);
487
- };
488
- const warm = () => {
489
- const indices = [];
490
- for (const offset of [-1, 1, -2, 2, 3, 4, 5, 6]) {
491
- const index = focus + offset;
492
- if (sections[index] && !existing(index)) indices.push(index);
493
- }
494
- scheduler.prefetch(document.hidden ? [] : indices);
495
- };
496
- const refresh = () => {
497
- if (readerContext.readerAbortController.signal.aborted || stream.classList.contains("foliate-supplement-active")) return;
498
- const marker = readerContext.viewport.getBoundingClientRect().top + 80;
499
- const rows = [...stream.children];
500
- const current = rows.find(node => {
501
- const rect = node.getBoundingClientRect();
502
- return rect.top <= marker && rect.bottom > marker;
503
- }) || rows.find(node => node.getBoundingClientRect().top > marker);
504
- const index = current ? Number(/** @type {HTMLElement} */ (current).dataset.section) : focus;
505
- if (targetPending && index !== focus && !readerContext.foliateScrollAnchors.scrolling) return;
506
- targetPending = false;
507
- focus = index;
508
- if (current?.classList.contains("foliate-section-placeholder")) scheduler.load(index).catch(() => {});
509
- warm();
510
- readerContext.foliateScrollAnchors.whenIdle(readerContext.trimFoliateSections);
511
- };
512
- const observer = new IntersectionObserver(readerContext.scheduleFoliateWindowRefresh,
513
- { root: readerContext.viewport, rootMargin: `${readerContext.FOLIATE_PREFETCH_MARGIN}px` });
514
- readerContext.foliateSectionObserver = observer;
515
- /** @param {number} index @param {import('../../../typings/reader-foliate-format-strict').FoliateArticle} article */
516
- const commitSection = (index, article) =>
517
- readerContext.foliateScrollAnchors.preserve(() => {
518
- const placeholder = stream.querySelector(
519
- `article.foliate-section-placeholder[data-section="${index}"]`
520
- ),
521
- next = [...stream.querySelectorAll("article[data-section]")].find(
522
- (item) => Number(/** @type {HTMLElement} */ (item).dataset.section) > index
523
- );
524
- if (stream.classList.contains("foliate-supplement-active")) article.hidden = true;
525
- if (placeholder) {
526
- observer.unobserve(placeholder);
527
- placeholder.replaceWith(article);
528
- } else stream.insertBefore(article, next || null);
529
- observer.observe(article);
530
- readerContext.foliateScrollAnchors.observe(article);
531
- ensurePlaceholder(index - 1);
532
- ensurePlaceholder(index + 1);
533
- return article;
534
- });
535
- const scheduler = readerContext.readerRuntime.track(VoiceOfMLReaderChapters.createChapterScheduler({
536
- create: async (index, signal, priority) => {
537
- const section = sections[index];
538
- if (!section) throw new RangeError("Foliate section is unavailable");
539
- const article = await readerContext.createFoliateSection(section, index, signal, priority);
540
- signal.throwIfAborted();
541
- if (existing(index)) return existing(index);
542
- return commitSection(index, article);
543
- }
544
- }));
545
- readerContext.foliateChapterRepository = VoiceOfMLReaderChapters.createChapterRepository({
546
- count: sections.length, find: existing, create: index => scheduler.load(index)
547
- });
548
- readerContext.foliateSectionVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({
549
- limit: readerContext.FOLIATE_LOADED_SECTION_LIMIT,
550
- getLoaded: () => [
551
- .../** @type {NodeListOf<import('../../../typings/reader-foliate-format-strict').FoliateArticle>} */ (stream.querySelectorAll("article[data-section]:not(.foliate-section-placeholder)"))
552
- ],
553
- getIndex: (article) => Number(article.dataset.section),
554
- getHeight: (article) => article.getBoundingClientRect().height,
555
- canVirtualize: (article) => {
556
- const rect = article.getBoundingClientRect(),
557
- viewportRect = readerContext.viewport.getBoundingClientRect();
558
- return (
559
- rect.bottom < viewportRect.top - readerContext.FOLIATE_PREFETCH_MARGIN ||
560
- rect.top > viewportRect.bottom + readerContext.FOLIATE_PREFETCH_MARGIN
561
- ) && !article.contains(document.activeElement) && !article.shadowRoot?.activeElement &&
562
- !readerContext.foliateSectionRoot(article).querySelector("mark.full-search-highlight") &&
563
- ![window.getSelection(), /** @type {(ShadowRoot & {getSelection?: () => Selection | null}) | null} */ (article.shadowRoot)?.getSelection?.()].some(selection =>
564
- selection && !selection.isCollapsed && (selection.containsNode(article, true) ||
565
- selection.anchorNode?.getRootNode() === article.shadowRoot));
566
- },
567
- virtualize: (article, index, height) => {
568
- const placeholder = document.createElement("article");
569
- placeholder.className = "foliate-section-placeholder";
570
- placeholder.dataset.section = String(index);
571
- placeholder.style.setProperty("--foliate-placeholder-height", `${height}px`);
572
- placeholder.setAttribute("aria-hidden", "true");
573
- observer.unobserve(article);
574
- readerContext.foliateScrollAnchors.unobserve(article);
575
- for (const image of readerContext.foliateSectionRoot(article).querySelectorAll("img")) {
576
- image.removeAttribute("src");
577
- image.removeAttribute("srcset");
578
- }
579
- article._resolveSearchAnchor = null;
580
- article.replaceWith(placeholder);
581
- observer.observe(placeholder);
582
- return placeholder;
583
- },
584
- release: (index) => readerContext.foliateChapterRepository?.release(index) ?? false,
585
- preserve: (change) => readerContext.foliateScrollAnchors.preserve(change)
586
- });
587
- // Negative indices encode the original spine index, preserving existing linear
588
- // bookmark indices while keeping supplemental sections out of progression.
589
- let supplementGeneration = 0;
590
- readerContext.foliateSectionLoader = /** @type {import('../../../typings/reader-foliate-format-strict').FoliateLoader} */ (index => {
591
- if (index < 0) {
592
- const source = readerContext.epubBook?.sections[-index - 1];
593
- if (!Number.isInteger(index) || !source || source.linear !== "no") return Promise.resolve(null);
594
- const generation = ++supplementGeneration;
595
- const present = existing(index);
596
- const task = present ? Promise.resolve(present) : readerContext.createFoliateSection(source, index);
597
- return task.then(article => {
598
- if (generation !== supplementGeneration || readerContext.readerAbortController.signal.aborted) return null;
599
- for (const old of stream.querySelectorAll("article[data-supplement]")) if (old !== article) old.remove();
600
- article.dataset.supplement = "true";
601
- if (!article.isConnected) stream.append(article);
602
- for (const row of stream.children) if (row !== article) /** @type {HTMLElement} */ (row).hidden = true;
603
- stream.classList.add("foliate-supplement-active");
604
- return article;
605
- });
606
- }
607
- ++supplementGeneration;
608
- if (stream.classList.contains("foliate-supplement-active")) {
609
- for (const row of stream.children) /** @type {HTMLElement} */ (row).hidden = false;
610
- for (const old of stream.querySelectorAll("article[data-supplement]")) old.remove();
611
- stream.classList.remove("foliate-supplement-active");
612
- }
613
- focus = index;
614
- targetPending = true;
615
- const task = existing(index) ? Promise.resolve(existing(index)) : scheduler.load(index, true, true);
616
- warm();
617
- return task;
618
- });
619
- readerContext.foliateSectionLoader.refresh = refresh;
620
- readerContext.foliateSectionSettler = () => readerContext.waitForReader(0, true);
621
- const scroll = readerContext.scheduleFoliateWindowRefresh;
622
- readerContext.viewport.addEventListener("scroll", scroll, { passive: true });
623
- document.addEventListener("visibilitychange", scroll);
624
- readerContext.trackReaderResource(() => {
625
- readerContext.viewport.removeEventListener("scroll", scroll);
626
- document.removeEventListener("visibilitychange", scroll);
627
- });
628
- }
629
-
630
- /** @param {import('../../../typings/reader-foliate-format-strict').FoliateView} view @param {import('../../../typings/reader-foliate-format-strict').FoliateSection[]} sections */
631
- async function foliateTocEntries(view, sections) {
632
- readerContext.assertReaderActive();
633
- /** @type {import('../../../typings/reader-foliate-format-strict').FoliateTocEntry[]} */
634
- const entries = [];
635
- /** @param {import('../../../typings/reader-foliate-format-strict').FoliateTocItem[] | undefined} items @param {number} [depth] */
636
- const append = (items, depth = 0) => {
637
- for (const item of items || []) {
638
- const href = item?.href ? String(item.href) : "";
639
- if (href || item?.label)
640
- entries.push({
641
- label: item.label || "未命名章节",
642
- href,
643
- depth,
644
- group: !href,
645
- activate: () => view.goTo(href)
646
- });
647
- append(item.subitems, depth + 1);
648
- }
649
- };
650
- append(view.book.toc);
651
- /** @type {Map<import('../../../typings/reader-foliate-format-strict').FoliateSection, number>} */
652
- const sectionIndices = new Map();
653
- for (const [index, section] of sections.entries())
654
- if (!sectionIndices.has(section)) sectionIndices.set(section, index);
655
- let next = 0, yieldDeadline = performance.now() + 8;
656
- /** @type {Promise<void> | null} */
657
- let yieldTask = null;
658
- const resolveEntries = async () => {
659
- while (next < entries.length) {
660
- readerContext.assertReaderActive();
661
- if (yieldTask || performance.now() >= yieldDeadline) {
662
- yieldTask ||= readerContext.waitForReader().finally(() => {
663
- yieldTask = null;
664
- yieldDeadline = performance.now() + 8;
665
- });
666
- await yieldTask;
667
- continue;
668
- }
669
- const entry = entries[next++];
670
- if (!entry) continue;
671
- if (entry.group) {
672
- entry.sectionIndex = -1;
673
- entry.fragment = "";
674
- continue;
675
- }
676
- try {
677
- const target = await view.book.resolveHref(entry.href),
678
- section = target && view.book.sections[target.index];
679
- readerContext.assertReaderActive();
680
- entry.sectionIndex = section ? sectionIndices.get(section) ?? -target.index - 1 : -1;
681
- entry.anchor = typeof target?.anchor === "function" ? target.anchor : null;
682
- const fragment = entry.href.split("#")[1] || "";
683
- try { entry.fragment = fragment ? decodeURIComponent(fragment) : ""; }
684
- catch (_) { entry.fragment = ""; }
685
- } catch (_) {
686
- readerContext.assertReaderActive();
687
- entry.sectionIndex = -1;
688
- entry.fragment = "";
689
- }
690
- }
691
- };
692
- await readerContext.awaitReader(Promise.all(Array.from({ length: Math.min(8, entries.length) }, resolveEntries)));
693
- readerContext.assertReaderActive();
694
- return entries;
695
- }
696
-
697
- async function renderFoliate() {
698
- const foliateModuleUrl = "/static/foliate-reader/view.js";
699
- const prepared = readerContext.prepareReaderDocument([import(foliateModuleUrl)]);
700
- const [response, bytes] = await Promise.all([prepared.response,readerContext.readPreparedBytes(
701
- prepared.response,prepared.engines,VoiceOfMLReaderSecurity.LIMITS.archiveCompressedBytes)]);
702
- readerContext.assertReaderActive();
703
- if (VoiceOfMLReaderSecurity.isZipContainer(readerContext.extension, bytes))
704
- VoiceOfMLReaderSecurity.inspectZip(bytes);
705
- const view = /** @type {import('../../../typings/reader-foliate-format-strict').FoliateView} */ (/** @type {unknown} */ (document.createElement("foliate-view"))),
706
- stream = document.createElement("div");
707
- view.className = "foliate-reader-view";
708
- stream.className = "foliate-continuous";
709
- readerContext.content.replaceChildren(readerContext.loadingIndicator, view, stream);
710
- readerContext.epubRendition = view;
711
- await view.open(
712
- new File([bytes], new URL(readerContext.sourceUrl).pathname.split("/").pop() || "book.epub", {
713
- type: response.headers.get("content-type") || "application/epub+zip"
714
- })
715
- );
716
- readerContext.assertReaderActive();
717
- readerContext.epubBook = view.book;
718
- view.style.display = "none";
719
- const sections = view.book.sections.filter((section) => section.linear !== "no");
720
- await readerContext.getInitialReaderRestoration();
721
- const savedSection = Number(readerContext.readerRestorationEntry?.foliateSection);
722
- const initialSection = Number.isInteger(savedSection) && savedSection < 0 && view.book.sections[-savedSection - 1]?.linear === "no"
723
- ? 0 : Number.isInteger(savedSection)
724
- ? Math.max(0, Math.min(sections.length - 1, savedSection))
725
- : 0;
726
- readerContext.initialReaderTargetSection = readerContext.readerRestorationEntry?.foliateSection == null ? null : initialSection;
727
- readerContext.setupFoliateWindow(stream, sections);
728
- const repository = readerContext.foliateChapterRepository;
729
- if (!repository) throw new Error("Foliate chapter repository not initialized");
730
- if (sections[initialSection]) await repository.load(initialSection);
731
- if (savedSection < 0 && view.book.sections[-savedSection - 1]?.linear === "no")
732
- await readerContext.foliateSectionLoader?.(savedSection);
733
- readerContext.assertReaderActive();
734
- readerContext.markReaderContentReady();
735
- // Restoration targets the selected section; an unrelated slow previous
736
- // section is loaded in the background and remains retryable.
737
- if (initialSection > 0) repository.load(initialSection - 1).catch(error => {
738
- if (!readerContext.readerAbortController.signal.aborted)
739
- console.warn("Previous EPUB chapter could not be loaded", error);
740
- });
741
- // Resolving every TOC href can be expensive for large books. The first
742
- // chapter is already visible, so finish the opening path before enriching
743
- // the navigation panel in the background.
744
- readerContext.foliateTocEntries(view, sections)
745
- .then((entries) => {
746
- if (entries.length && !readerContext.readerAbortController.signal.aborted) readerContext.setToc(entries);
747
- })
748
- .catch(() => {});
749
- readerContext.scheduleFoliateScrollSync();
750
- readerContext.markReaderContentReady();
751
- readerContext.status.textContent = "EPUB";
752
- }
753
-
754
- return {
755
- foliateSectionRoot,
756
- foliateSectionQuery,
757
- foliateSectionCandidates,
758
- syncFoliateScrollLocation,
759
- refreshFoliateWindow,
760
- scheduleFoliateWindowRefresh,
761
- trimFoliateSections,
762
- scheduleFoliateScrollSync,
763
- activateFoliateTocEntry,
764
- cloneFoliateDocument,
765
- foliateSearchAnchor,
766
- settleReaderImages,
767
- rewriteFoliateResources,
768
- createFoliateSection,
769
- setupFoliateWindow,
770
- foliateTocEntries,
771
- renderFoliate
772
- };
773
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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  for (const image of readerContext.content.querySelectorAll(".reader-page img")) image.removeAttribute("src");
38
  }
39
- if (mode === "foliate") {
40
- readerContext.foliateSectionObserver?.disconnect();
41
- readerContext.foliateSectionObserver = null;
42
- readerContext.foliateSectionVirtualizer?.dispose();
43
- readerContext.foliateChapterRepository?.dispose();
44
- readerContext.foliateSectionVirtualizer = null;
45
- readerContext.foliateChapterRepository = null;
46
- readerContext.foliateSectionLoader = null;
47
- readerContext.foliateSectionSettler = null;
48
- try {
49
- const closing = readerContext.epubRendition?.close?.();
50
- if (closing) closing.catch?.(() => {});
51
- } catch (_) {}
52
- readerContext.epubRendition = null;
53
- readerContext.epubBook = null;
54
- }
55
  if (mode === "html") {
56
  readerContext.htmlFrame?.remove();
57
  readerContext.htmlFrame = null;
@@ -102,8 +86,7 @@ export function createReaderFormatController(readerContext) {
102
  "epub-chapters": pair(readerContext.loadChapterManifestDocument, readerContext.renderChapterManifest),
103
  audio: pair(readerContext.loadMediaDocument, () => readerContext.renderMedia("audio")),
104
  video: pair(readerContext.loadMediaDocument, () => readerContext.renderMedia("video")),
105
- swf: pair(readerContext.loadSwfDocument, readerContext.renderSwf),
106
- foliate: pair(readerContext.loadMediaDocument, readerContext.renderFoliate)
107
  };
108
  for (const [mode, {open, render}] of Object.entries(formats))
109
  readerContext.formatAdapters.register(mode, {
@@ -169,13 +152,6 @@ export function createReaderFormatController(readerContext) {
169
  readerContext.readerSourcePromise = readerContext.measurePdf(readerContext.resolveReaderSource(), "resolve");
170
  await readerContext.readerSourcePromise;
171
  readerContext.assertReaderActive();
172
- if (readerContext.readerId && /\/calibre-chm-epub-[^/]+\/document\.epub(?:$|\?)/i.test(readerContext.sourceUrl)) {
173
- readerContext.extension = "epub";
174
- readerContext.readerRuntime.update("source", { extension: readerContext.extension });
175
- readerContext.capability = readerContext.readerRuntime.negotiate(VoiceOfMLReader.capability(readerContext.extension));
176
- readerContext.content.dataset.mode = readerContext.capability.mode || "unsupported";
177
- /** @type {HTMLElement} */ (document.querySelector(".page-controls")).hidden = true;
178
- }
179
  readerContext.syncCapabilityControls();
180
  /** @type {HTMLAnchorElement} */ (readerContext.downloadButton).href = readerContext.readerDownloadUrl(readerContext.documentState.title, readerContext.downloadUrl);
181
  if (
@@ -186,22 +162,6 @@ export function createReaderFormatController(readerContext) {
186
  readerContext.formatAdapters.activate(readerContext.capability.mode);
187
  readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
188
  try {
189
- if (readerContext.capability.mode === "foliate") {
190
- readerContext.setReaderStage("foliate");
191
- readerContext.foliateContinuous = true;
192
- const restorationPromise = readerContext.loadReaderRestoration();
193
- readerContext.readerRestorationPromise = restorationPromise;
194
- await readerContext.awaitReader(readerContext.renderFoliate());
195
- readerContext.assertReaderActive();
196
- const restored = await readerContext.awaitReader(restorationPromise);
197
- await readerContext.applyInitialRestoration(restored, generation);
198
- readerContext.initialReaderTargetSection = null;
199
- readerContext.assertReaderActive();
200
- if (!readerContext.setReaderPhase("ready")) return;
201
- readerContext.updateDocumentState({ restorationReady: !readerContext.restorationFailed });
202
- readerContext.scheduleSave();
203
- return;
204
- }
205
  readerContext.setReaderStage("prepare");
206
  const restorationPromise = readerContext.loadReaderRestoration();
207
  readerContext.readerRestorationPromise = restorationPromise;
@@ -268,7 +228,7 @@ export function createReaderFormatController(readerContext) {
268
  console.error(error);
269
  const message = detail && "code" in detail && detail.code === "READER_PDF_RATE_LIMIT" ? "请求过于频繁,请稍后重试加载。" :
270
  detail && "message" in detail && typeof detail.message === "string" && detail.message ? detail.message : "原文件加载失败";
271
- const fallback = readerContext.capability.mode === "foliate" ? "READER_CORRUPT" : "READER_PARSE";
272
  const code = readerContext.classifyReaderError(error, fallback);
273
  readerContext.fail(message, typeof code === "string" ? code : fallback);
274
  }
 
36
  }
37
  for (const image of readerContext.content.querySelectorAll(".reader-page img")) image.removeAttribute("src");
38
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  if (mode === "html") {
40
  readerContext.htmlFrame?.remove();
41
  readerContext.htmlFrame = null;
 
86
  "epub-chapters": pair(readerContext.loadChapterManifestDocument, readerContext.renderChapterManifest),
87
  audio: pair(readerContext.loadMediaDocument, () => readerContext.renderMedia("audio")),
88
  video: pair(readerContext.loadMediaDocument, () => readerContext.renderMedia("video")),
89
+ swf: pair(readerContext.loadSwfDocument, readerContext.renderSwf)
 
90
  };
91
  for (const [mode, {open, render}] of Object.entries(formats))
92
  readerContext.formatAdapters.register(mode, {
 
152
  readerContext.readerSourcePromise = readerContext.measurePdf(readerContext.resolveReaderSource(), "resolve");
153
  await readerContext.readerSourcePromise;
154
  readerContext.assertReaderActive();
 
 
 
 
 
 
 
155
  readerContext.syncCapabilityControls();
156
  /** @type {HTMLAnchorElement} */ (readerContext.downloadButton).href = readerContext.readerDownloadUrl(readerContext.documentState.title, readerContext.downloadUrl);
157
  if (
 
162
  readerContext.formatAdapters.activate(readerContext.capability.mode);
163
  readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
164
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  readerContext.setReaderStage("prepare");
166
  const restorationPromise = readerContext.loadReaderRestoration();
167
  readerContext.readerRestorationPromise = restorationPromise;
 
228
  console.error(error);
229
  const message = detail && "code" in detail && detail.code === "READER_PDF_RATE_LIMIT" ? "请求过于频繁,请稍后重试加载。" :
230
  detail && "message" in detail && typeof detail.message === "string" && detail.message ? detail.message : "原文件加载失败";
231
+ const fallback = "READER_PARSE";
232
  const code = readerContext.classifyReaderError(error, fallback);
233
  readerContext.fail(message, typeof code === "string" ? code : fallback);
234
  }
static/reader/formats/reader-html-format.mjs CHANGED
@@ -25,7 +25,6 @@ export function createReaderHtmlFormat(readerContext) {
25
  }
26
  // HTML parsing treats prefixed void tags as containers. Keep the following
27
  // content as siblings: serializing real <br>/<hr>/<img> drops their children.
28
- // Move the existing text nodes so Foliate's source/CFI mapping stays intact.
29
  const fragment = doc.createDocumentFragment();
30
  fragment.appendChild(replacement);
31
  if (readerContext.EPUB_HTML_VOID_TAGS.has(localName)) {
@@ -116,8 +115,6 @@ export function createReaderHtmlFormat(readerContext) {
116
  const CSS_REFERENCE_FUNCTIONS = new Set([
117
  "url", "src", "image", "image-set", "-webkit-image-set", "cross-fade", "-webkit-cross-fade"
118
  ]);
119
- const CSS_BLOB_STYLESHEET_MAX_BYTES = 4 * 1024 * 1024;
120
- const CSS_IMPORT_MAX_DEPTH = 4;
121
  const CSS_IMPORT_MAX_PER_SHEET = 32;
122
 
123
  /** @param {number} code */
@@ -379,99 +376,6 @@ export function createReaderHtmlFormat(readerContext) {
379
  return scanCss(css, options);
380
  }
381
 
382
- /** @param {string} url */
383
- async function readBlobStylesheet(url) {
384
- try {
385
- const response = await fetch(url);
386
- if (!response.ok) return null;
387
- const declared = Number(response.headers.get("content-length") || 0);
388
- if (declared > CSS_BLOB_STYLESHEET_MAX_BYTES) return null;
389
- const blob = await response.blob();
390
- return blob.size > CSS_BLOB_STYLESHEET_MAX_BYTES ? null : await blob.text();
391
- } catch (_) {
392
- return null;
393
- }
394
- }
395
-
396
- // Replace blob @imports with their sanitized contents, preserving cascade
397
- // position and media conditions. Cycles, excessive depth and unreadable
398
- // sheets are dropped rather than loaded unsanitized.
399
- /** @param {string} css @param {number} [depth] @param {Set<string>} [ancestors] @returns {Promise<string>} */
400
- async function inlineCssImports(css, depth = 0, ancestors = new Set()) {
401
- /** @type {{url: string, media: string}[]} */
402
- const blobImports = [];
403
- const nonce = `reader-import-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
404
- const sanitized = scanCss(css, { blobImports, nonce });
405
- if (!blobImports.length) return sanitized;
406
- const bodies = await Promise.all(blobImports.map(async ({ url, media }) => {
407
- if (depth >= CSS_IMPORT_MAX_DEPTH || ancestors.has(url)) return "";
408
- const text = await readBlobStylesheet(url);
409
- if (text === null) return "";
410
- const body = (await inlineCssImports(text, depth + 1, new Set([...ancestors, url])))
411
- .replace(/^\ufeff/, "").replace(/^\s*@charset\s+"[^"]*"\s*;/i, "");
412
- return media && !/^all$/i.test(media) ? `@media ${media} {\n${body}\n}` : body;
413
- }));
414
- return sanitized.replace(new RegExp(`/\\*${nonce}:(\\d+)\\*/`, "g"), (_, index) => bodies[Number(index)] ?? "");
415
- }
416
-
417
- // Foliate rewrites chapter stylesheets to blob: URLs. Load them as sanitized
418
- // inline styles so remote references inside packaged CSS cannot escape the
419
- // archive-only resource policy. Results are cached per blob URL.
420
- /** @type {Map<string, Promise<string | null>>} */
421
- const foliateStyleCache = new Map();
422
- const FOLIATE_STYLE_CACHE_MAX = 64;
423
-
424
- /** @param {Element} node @returns {Promise<Element | null>} */
425
- async function sanitizeFoliateStyle(node) {
426
- if (node.localName !== "link") {
427
- const style = /** @type {Element} */ (node.cloneNode(false));
428
- style.textContent = await inlineCssImports(node.textContent || "");
429
- return style;
430
- }
431
- const href = node.getAttribute("href") || "";
432
- if (!/^blob:/i.test(href)) return null;
433
- let pending = foliateStyleCache.get(href);
434
- if (!pending) {
435
- pending = readBlobStylesheet(href).then(text => {
436
- if (text !== null) return inlineCssImports(text, 0, new Set([href]));
437
- // An old failed read must not evict a newer entry after cache rotation.
438
- if (foliateStyleCache.get(href) === pending) foliateStyleCache.delete(href);
439
- return null;
440
- });
441
- foliateStyleCache.set(href, pending);
442
- while (foliateStyleCache.size > FOLIATE_STYLE_CACHE_MAX) {
443
- const oldest = foliateStyleCache.keys().next();
444
- if (oldest.done) break;
445
- foliateStyleCache.delete(oldest.value);
446
- }
447
- }
448
- const text = await pending;
449
- if (text === null) return null;
450
- const style = document.createElement("style");
451
- const media = node.getAttribute("media");
452
- if (media) style.setAttribute("media", media);
453
- style.textContent = text;
454
- return style;
455
- }
456
-
457
- /** @param {Iterable<Element>} nodes */
458
- async function sanitizeFoliateStyles(nodes) {
459
- const ordered = Array.from(nodes);
460
- /** @type {(Element | null)[]} */
461
- const output = [];
462
- let next = 0;
463
- // Overlap the archive's independent sheets without starting every read at
464
- // once. Insert only sanitized output, in the original cascade order.
465
- await Promise.all(Array.from({ length: Math.min(3, ordered.length) }, async () => {
466
- while (next < ordered.length) {
467
- readerContext.assertReaderActive();
468
- const index = next++;
469
- output[index] = await sanitizeFoliateStyle(/** @type {Element} */ (ordered[index]));
470
- }
471
- }));
472
- return output.filter(style => style !== null);
473
- }
474
-
475
  /** @param {Document} doc @param {{keepBlobImports?: boolean}} [options] */
476
  function sanitizeEpubDocument(doc, options = {}) {
477
  return readerContext.sanitizeReaderDocument(readerContext.normalizeEpubDocument(doc), { ...options, preserveEpubStyles: true });
@@ -842,7 +746,6 @@ export function createReaderHtmlFormat(readerContext) {
842
  sanitizeReaderDocument,
843
  sanitizeEpubDocument,
844
  sanitizeCssReferences,
845
- sanitizeFoliateStyles,
846
  parseChapterDocument,
847
  epubContentBody,
848
  renderText,
 
25
  }
26
  // HTML parsing treats prefixed void tags as containers. Keep the following
27
  // content as siblings: serializing real <br>/<hr>/<img> drops their children.
 
28
  const fragment = doc.createDocumentFragment();
29
  fragment.appendChild(replacement);
30
  if (readerContext.EPUB_HTML_VOID_TAGS.has(localName)) {
 
115
  const CSS_REFERENCE_FUNCTIONS = new Set([
116
  "url", "src", "image", "image-set", "-webkit-image-set", "cross-fade", "-webkit-cross-fade"
117
  ]);
 
 
118
  const CSS_IMPORT_MAX_PER_SHEET = 32;
119
 
120
  /** @param {number} code */
 
376
  return scanCss(css, options);
377
  }
378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  /** @param {Document} doc @param {{keepBlobImports?: boolean}} [options] */
380
  function sanitizeEpubDocument(doc, options = {}) {
381
  return readerContext.sanitizeReaderDocument(readerContext.normalizeEpubDocument(doc), { ...options, preserveEpubStyles: true });
 
746
  sanitizeReaderDocument,
747
  sanitizeEpubDocument,
748
  sanitizeCssReferences,
 
749
  parseChapterDocument,
750
  epubContentBody,
751
  renderText,
static/reader/pdf/reader-engine-preload.js CHANGED
@@ -44,7 +44,7 @@
44
  for (const href of assets) {
45
  if (support.includes(href) || href.endsWith(".wasm")) continue;
46
  const link = document.createElement("link");
47
- link.rel = /\.mjs(?:\?|$)/.test(href) || href.includes("/foliate-reader/") ? "modulepreload" : "preload";
48
  if (link.rel === "preload") link.as = "script";
49
  link.href = href;
50
  document.head.appendChild(link);
 
44
  for (const href of assets) {
45
  if (support.includes(href) || href.endsWith(".wasm")) continue;
46
  const link = document.createElement("link");
47
+ link.rel = /\.mjs(?:\?|$)/.test(href) ? "modulepreload" : "preload";
48
  if (link.rel === "preload") link.as = "script";
49
  link.href = href;
50
  document.head.appendChild(link);
static/reader/reader-components.mjs CHANGED
@@ -6,7 +6,6 @@ export { createReaderToc } from "./ui/reader-toc.mjs";
6
  export { createReaderSearchBackends } from "./search/reader-search-backends.mjs";
7
  export { createReaderPdfScheduler } from "./pdf/reader-pdf-scheduler.mjs";
8
  export { createReaderNavigation } from "./ui/reader-navigation.mjs";
9
- export { createReaderFoliateFormat } from "./formats/reader-foliate-format.mjs";
10
  export { createReaderProgress } from "./ui/reader-progress.mjs";
11
  export { createReaderBookmarks } from "./ui/reader-bookmarks.mjs";
12
  export { createReaderMediaFormat } from "./formats/reader-media-format.mjs";
 
6
  export { createReaderSearchBackends } from "./search/reader-search-backends.mjs";
7
  export { createReaderPdfScheduler } from "./pdf/reader-pdf-scheduler.mjs";
8
  export { createReaderNavigation } from "./ui/reader-navigation.mjs";
 
9
  export { createReaderProgress } from "./ui/reader-progress.mjs";
10
  export { createReaderBookmarks } from "./ui/reader-bookmarks.mjs";
11
  export { createReaderMediaFormat } from "./formats/reader-media-format.mjs";
static/reader/search/reader-dom-search.mjs CHANGED
@@ -376,8 +376,6 @@ export function createReaderDomSearch({
376
  const chunks = [];
377
  const breaks = cached ? cached.breaks : [];
378
  const findLineBreaks = query.includes(BLOCK_SEPARATOR);
379
- // Foliate's section-ordinal fallback must count the same concatenated text
380
- // matches as the Foliate engine which produced the ordinal.
381
  const respectBlocks = progressive || occurrence === null;
382
  let length = 0;
383
  /** @type {(node: Text, start: number, end: number) => void} */
 
376
  const chunks = [];
377
  const breaks = cached ? cached.breaks : [];
378
  const findLineBreaks = query.includes(BLOCK_SEPARATOR);
 
 
379
  const respectBlocks = progressive || occurrence === null;
380
  let length = 0;
381
  /** @type {(node: Text, start: number, end: number) => void} */
static/reader/search/reader-search-backends.mjs CHANGED
@@ -81,9 +81,9 @@ export function createReaderSearchBackends(readerContext) {
81
  parts.unshift({ node: /** @type {Text} */ (heading.firstChild), start, end: Math.min(start + result.length, headText.length) });
82
  }
83
  const [mark] = readerContext.highlightTextParts(parts);
84
- readerContext.foliateScrollAnchors.invalidate();
85
  (mark || article).scrollIntoView({ block: "center" });
86
- readerContext.foliateScrollAnchors.remember();
87
  const tocIndex = readerContext.navigationState.tocEntries.findIndex(
88
  (entry) => entry.chapterIndex === result.chapterIndex
89
  );
@@ -96,147 +96,6 @@ export function createReaderSearchBackends(readerContext) {
96
  return true;
97
  }
98
 
99
- /** @param {string} query @param {number} generation */
100
- async function fullSearchFoliateMatches(query, generation) {
101
- if (!readerContext.epubRendition?.search) return [];
102
- /** @type {{index: number, count: number, label: string}[]} */
103
- const groups = [];
104
- /** @type {ReaderSearchBackends.FoliateResult[]} */
105
- const firstPage = [];
106
- // Cache only visited pages for this query; never retain every match in the book.
107
- /** @type {Map<number, ReaderSearchBackends.Page<ReaderSearchBackends.FoliateResult>>} */
108
- const cachedPages = new Map();
109
- let total = 0;
110
- /** @param {ReaderSearchBackends.FoliateItem} item @param {string} label @param {number} occurrence */
111
- const toResult = (item, label, occurrence) => {
112
- const excerpt = item.excerpt || { pre: "", match: query, post: "" };
113
- return {
114
- location: label || "电子书位置",
115
- cfi: item.cfi,
116
- occurrence,
117
- snippet: {
118
- text: `${excerpt.pre}${excerpt.match}${excerpt.post}`,
119
- matchStart: excerpt.pre.length,
120
- matchLength: excerpt.match.length,
121
- prefix: "",
122
- suffix: ""
123
- }
124
- };
125
- };
126
- readerContext.fullSearchSession.pageLoader = async (requestedOffset, pageGeneration = readerContext.readerRuntime.currentGeneration("search")) => {
127
- const pageSize = 50;
128
- const offset = readerContext.fullSearchPageOffset(total, requestedOffset, pageSize);
129
- if (!offset) return { total, offset, pageSize, results: firstPage.slice() };
130
- const cached = cachedPages.get(offset);
131
- if (cached) {
132
- cachedPages.delete(offset);
133
- cachedPages.set(offset, cached);
134
- return cached;
135
- }
136
- /** @type {ReaderSearchBackends.FoliateResult[]} */
137
- const results = [];
138
- let passed = 0;
139
- for (const group of groups) {
140
- if (passed + group.count <= offset) { passed += group.count; continue; }
141
- const sectionOffset = Math.max(0, offset - passed);
142
- const limit = Math.min(pageSize - results.length, group.count - sectionOffset);
143
- for await (const batch of /** @type {ReaderSearchBackends.Rendition} */ (readerContext.epubRendition).search({
144
- query, index: group.index, offset: sectionOffset, limit, lean: true,
145
- current: () => readerContext.isReaderGenerationCurrent("search", pageGeneration)
146
- }))
147
- for (const [index, item] of batch.subitems.entries())
148
- results.push(toResult(item, group.label, sectionOffset + index));
149
- passed += group.count;
150
- if (results.length === pageSize) break;
151
- }
152
- const page = { total, offset, pageSize, results };
153
- if (readerContext.isReaderGenerationCurrent("search", pageGeneration) && JSON.stringify(page).length <= 128 * 1024) {
154
- cachedPages.set(offset, page);
155
- if (cachedPages.size > 4) cachedPages.delete(/** @type {number} */ (cachedPages.keys().next().value));
156
- }
157
- return page;
158
- };
159
- for await (const group of readerContext.epubRendition.search({
160
- query, lean: true, limit: 50,
161
- current: () => readerContext.isReaderGenerationCurrent("search", generation)
162
- })) {
163
- if (!readerContext.isReaderGenerationCurrent("search", generation)) return [];
164
- if (group.count) groups.push({ index: group.index, count: group.count, label: group.label });
165
- for (const [index, item] of group.subitems.entries()) {
166
- if (firstPage.length === 50) break;
167
- firstPage.push(toResult(item, group.label, index));
168
- }
169
- total += group.count;
170
- readerContext.fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };
171
- readerContext.updateSearchState({ results: firstPage.slice(), index: -1 });
172
- readerContext.renderFullSearchResults();
173
- readerContext.fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`;
174
- await readerContext.waitForReader();
175
- if (!readerContext.isReaderGenerationCurrent("search", generation)) return [];
176
- }
177
- readerContext.fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };
178
- return firstPage;
179
- }
180
-
181
- /** @param {ReaderSearchBackends.FoliateResult} result @param {number} generation */
182
- async function navigateFoliateSearchResult(result, generation) {
183
- const resolved = await readerContext.epubRendition?.resolveNavigation?.(result.cfi);
184
- if (!resolved || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
185
- const section = readerContext.epubBook?.sections?.[resolved.index],
186
- sections = readerContext.epubBook?.sections?.filter((item) => item.linear !== "no") || [],
187
- visibleIndex = section ? sections.indexOf(section) : -1,
188
- destinationIndex = visibleIndex >= 0 ? visibleIndex : -resolved.index - 1;
189
- if (!section || !readerContext.foliateSectionLoader) return false;
190
- let node = await readerContext.foliateSectionLoader(destinationIndex);
191
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
192
- await readerContext.waitForReader(0, true);
193
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
194
- if (!node?.isConnected) node = await readerContext.foliateSectionLoader(destinationIndex);
195
- if (!node?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
196
- readerContext.clearFullSearchMarks();
197
- let target;
198
- if (typeof resolved.anchor === "function" && node._resolveSearchAnchor) {
199
- let parts;
200
- try { parts = node._resolveSearchAnchor(resolved.anchor); } catch (_) { return false; }
201
- if (!parts?.length) return false;
202
- [target] = readerContext.highlightTextParts(parts);
203
- } else {
204
- // Some non-CFI engines expose only a section locator.
205
- const matches = await readerContext.fullSearchDomMatches(
206
- node,
207
- "电子书位置",
208
- readerContext.searchState.query,
209
- readerContext.readerRuntime.currentGeneration("search"),
210
- false,
211
- result.occurrence || 0,
212
- generation
213
- );
214
- target = matches[0]?.target;
215
- }
216
- if (!readerContext.isReaderGenerationCurrent("navigation", generation) || !target) return false;
217
- const targetRect = target.getBoundingClientRect(),
218
- viewportRect = readerContext.viewport.getBoundingClientRect();
219
- readerContext.foliateScrollAnchors.invalidate();
220
- readerContext.viewport.scrollTop = Math.max(
221
- 0,
222
- readerContext.viewport.scrollTop +
223
- targetRect.top -
224
- viewportRect.top -
225
- (readerContext.viewport.clientHeight - targetRect.height) / 2
226
- );
227
- const tocIndex = readerContext.navigationState.tocEntries.findIndex(
228
- (entry) => entry.sectionIndex === destinationIndex
229
- );
230
- if (tocIndex >= 0) {
231
- readerContext.updateNavigationState({ currentChapterIndex: tocIndex });
232
- readerContext.updateTocCurrentMark();
233
- }
234
- readerContext.updateProgressTools();
235
- readerContext.scheduleSave();
236
- readerContext.foliateScrollAnchors.remember();
237
- return true;
238
- }
239
-
240
  /** @param {string} query @param {number} generation */
241
  async function searchReaderText(query, generation) {
242
  if (readerContext.capability.mode === "pdf" && !readerContext.ocrManifestUrl) {
@@ -244,8 +103,6 @@ export function createReaderSearchBackends(readerContext) {
244
  }
245
  else if (/** @type {(string | null | undefined)[]} */ (["pdf", "pdf-pages"]).includes(readerContext.capability.mode))
246
  readerContext.publishSearchResults(generation, await readerContext.searchConcentratedPdf(query, generation));
247
- else if (readerContext.capability.mode === "foliate")
248
- readerContext.publishSearchResults(generation, await readerContext.fullSearchFoliateMatches(query, generation));
249
  else if (readerContext.capability.mode === "epub-chapters") await readerContext.searchChapterBook(query, generation);
250
  else if (/** @type {(string | null | undefined)[]} */ (["text", "markdown"]).includes(readerContext.capability.mode))
251
  readerContext.publishSearchResults(
@@ -275,8 +132,6 @@ export function createReaderSearchBackends(readerContext) {
275
  chapterSearchModule,
276
  searchChapterBook,
277
  navigateChapterSearchResult,
278
- fullSearchFoliateMatches,
279
- navigateFoliateSearchResult,
280
  searchReaderText
281
  };
282
  }
 
81
  parts.unshift({ node: /** @type {Text} */ (heading.firstChild), start, end: Math.min(start + result.length, headText.length) });
82
  }
83
  const [mark] = readerContext.highlightTextParts(parts);
84
+ readerContext.chapterScrollAnchors.invalidate();
85
  (mark || article).scrollIntoView({ block: "center" });
86
+ readerContext.chapterScrollAnchors.remember();
87
  const tocIndex = readerContext.navigationState.tocEntries.findIndex(
88
  (entry) => entry.chapterIndex === result.chapterIndex
89
  );
 
96
  return true;
97
  }
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  /** @param {string} query @param {number} generation */
100
  async function searchReaderText(query, generation) {
101
  if (readerContext.capability.mode === "pdf" && !readerContext.ocrManifestUrl) {
 
103
  }
104
  else if (/** @type {(string | null | undefined)[]} */ (["pdf", "pdf-pages"]).includes(readerContext.capability.mode))
105
  readerContext.publishSearchResults(generation, await readerContext.searchConcentratedPdf(query, generation));
 
 
106
  else if (readerContext.capability.mode === "epub-chapters") await readerContext.searchChapterBook(query, generation);
107
  else if (/** @type {(string | null | undefined)[]} */ (["text", "markdown"]).includes(readerContext.capability.mode))
108
  readerContext.publishSearchResults(
 
132
  chapterSearchModule,
133
  searchChapterBook,
134
  navigateChapterSearchResult,
 
 
135
  searchReaderText
136
  };
137
  }
static/reader/search/reader-search-controller.mjs CHANGED
@@ -176,7 +176,7 @@ export function createReaderSearchController({
176
  initialSearch = null;
177
  if (interrupted) {
178
  if (mode === "epub-chapters") backend.chapterClient()?.cancel();
179
- else if (mode === "pdf" || mode === "pdf-pages" || mode === "foliate") backend.pdfClient()?.cancel();
180
  resetResults();
181
  }
182
  cancel.hidden = retry.hidden = true;
@@ -251,7 +251,7 @@ export function createReaderSearchController({
251
  state.failedPage = null;
252
  const generation = nextGeneration();
253
  navigation.begin();
254
- if (!(/** @type {(string | null)[]} */ (["foliate", "epub-chapters"])).includes(backend.mode())) cancel.hidden = false;
255
  retry.hidden = true;
256
  status.textContent = `${state.page.total} 个结果`;
257
  try {
 
176
  initialSearch = null;
177
  if (interrupted) {
178
  if (mode === "epub-chapters") backend.chapterClient()?.cancel();
179
+ else if (mode === "pdf" || mode === "pdf-pages") backend.pdfClient()?.cancel();
180
  resetResults();
181
  }
182
  cancel.hidden = retry.hidden = true;
 
251
  state.failedPage = null;
252
  const generation = nextGeneration();
253
  navigation.begin();
254
+ if (backend.mode() !== "epub-chapters") cancel.hidden = false;
255
  retry.hidden = true;
256
  status.textContent = `${state.page.total} 个结果`;
257
  try {
static/reader/ui/reader-bookmarks.mjs CHANGED
@@ -147,121 +147,11 @@ export function createReaderBookmarks(readerContext) {
147
  } catch (_) {}
148
  const exact = readerContext.excerptFromCaret(document, readerContext.content, x, y);
149
  if (exact) return exact;
150
- const sourceText = readerContext.foliateContinuous
151
- ? [
152
- ...readerContext.content.querySelectorAll(
153
- ".foliate-continuous article[data-section]:not(.foliate-section-placeholder)"
154
- )
155
- ]
156
- .map((article) => readerContext.foliateSectionRoot(article).textContent)
157
- .join(" ")
158
- : readerContext.content.textContent,
159
- text = sourceText.replace(/\s+/g, " ").trim(),
160
  start = Math.floor((text.length * readerContext.readerProgressPercent()) / 100);
161
  return text.slice(start, start + 160).trim();
162
  }
163
 
164
- function captureFoliateBookmarkPosition() {
165
- if (!readerContext.foliateContinuous) return null;
166
- const marker = readerContext.viewport.getBoundingClientRect().top + 8;
167
- const rows = /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll(".foliate-continuous article[data-section]"));
168
- /** @type {{article: HTMLElement, top: number} | null} */
169
- let following = null, last = null;
170
- for (const article of rows) {
171
- if (article.hidden) continue;
172
- const { top, bottom } = article.getBoundingClientRect();
173
- last = { article, top };
174
- if (top <= marker && bottom > marker) { following = last; break; }
175
- if (!following && top > marker) following = last;
176
- }
177
- const current = following || last;
178
- return current ? {
179
- foliateSection: Number(current.article.dataset.section),
180
- foliateOffset: marker - current.top,
181
- foliateTocIndex: readerContext.navigationState.currentChapterIndex
182
- } : null;
183
- }
184
-
185
- /** @param {import('../../../typings/reader-progress-strict').ProgressState} entry @param {number} [generation] */
186
- async function restoreFoliateBookmarkPosition(entry, generation = readerContext.beginReaderNavigation()) {
187
- try {
188
- if (
189
- !readerContext.foliateSectionLoader ||
190
- !Number.isInteger(entry.foliateSection) ||
191
- !readerContext.isReaderGenerationCurrent("navigation", generation)
192
- )
193
- return false;
194
- const section = /** @type {number} */ (entry.foliateSection);
195
- let article = await readerContext.foliateSectionLoader(section);
196
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
197
- await readerContext.waitForReader(0, true);
198
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
199
- if (!article?.isConnected) article = await readerContext.foliateSectionLoader(section);
200
- if (!article?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
201
- const marker = readerContext.viewport.getBoundingClientRect().top + 8;
202
- const offset = Number(entry.foliateOffset) || 0;
203
- const start = !offset
204
- ? readerContext.foliateSectionRoot(article).querySelector("h1,h2,h3,h4,h5,h6,p,li,blockquote,pre") || article
205
- : article;
206
- readerContext.foliateScrollAnchors.invalidate();
207
- readerContext.viewport.scrollTop = Math.max(
208
- 0,
209
- readerContext.viewport.scrollTop +
210
- start.getBoundingClientRect().top -
211
- marker +
212
- offset
213
- );
214
- readerContext.syncFoliateScrollLocation();
215
- readerContext.updateTocCurrentMark();
216
- readerContext.updateProgressTools();
217
- readerContext.scheduleSave();
218
- readerContext.setReaderPanelOpen(false, true);
219
- readerContext.foliateScrollAnchors.remember();
220
- return true;
221
- } catch (error) {
222
- readerContext.reportNavigationError(error, generation);
223
- return false;
224
- }
225
- }
226
-
227
- /** @param {number} percent @param {number} generation */
228
- async function seekFoliateProgress(percent, generation) {
229
- try {
230
- const sections = readerContext.epubBook?.sections?.filter((section) => section.linear !== "no") || [];
231
- if (
232
- !sections.length ||
233
- !readerContext.foliateSectionLoader ||
234
- !readerContext.isReaderGenerationCurrent("navigation", generation)
235
- )
236
- return;
237
- const position = Math.max(0, Math.min(0.999999, Number(percent) / 100)) * sections.length,
238
- index = Math.min(sections.length - 1, Math.floor(position));
239
- let article = await readerContext.foliateSectionLoader(index);
240
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return;
241
- await readerContext.waitForReader(0, true);
242
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return;
243
- if (!article?.isConnected) article = await readerContext.foliateSectionLoader(index);
244
- if (!article?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return;
245
- const marker = readerContext.viewport.getBoundingClientRect().top + 8,
246
- offset = article.getBoundingClientRect().height * (position - index);
247
- readerContext.foliateScrollAnchors.invalidate();
248
- readerContext.viewport.scrollTop = Math.max(
249
- 0,
250
- readerContext.viewport.scrollTop + article.getBoundingClientRect().top - marker + offset
251
- );
252
- await readerContext.waitForReader(0, true);
253
- if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return;
254
- readerContext.viewport.scrollTop += article.getBoundingClientRect().top - marker + offset + 4;
255
- readerContext.syncFoliateScrollLocation();
256
- readerContext.updateTocCurrentMark();
257
- readerContext.updateProgressTools();
258
- readerContext.scheduleSave();
259
- readerContext.foliateScrollAnchors.remember();
260
- } catch (error) {
261
- readerContext.reportNavigationError(error, generation);
262
- }
263
- }
264
-
265
  async function renderBookmarks() {
266
  const list = /** @type {HTMLElement} */ (document.querySelector("#bookmarks-list")),
267
  generation = readerContext.nextReaderGeneration("bookmarks");
@@ -339,7 +229,7 @@ export function createReaderBookmarks(readerContext) {
339
  };
340
  }
341
  readerContext.syncCurrentPageFromMarker();
342
- const foliatePosition = readerContext.captureFoliateBookmarkPosition() || readerContext.captureChapterPosition();
343
  const shell = readerContext.documentState.pageCount ? readerContext.pageAtMarker() : null;
344
  const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0;
345
  const progress = readerContext.readerProgressPercent();
@@ -347,11 +237,9 @@ export function createReaderBookmarks(readerContext) {
347
  const scrollTop = readerContext.viewport.scrollTop;
348
  const mode = readerContext.capability.mode;
349
  const pagedDocument = readerContext.documentState.pageCount && mode !== "text" && mode !== "markdown";
350
- const locator = Number.isInteger(foliatePosition?.chapterIndex)
351
- ? `chapter:${/** @type {import('../../../typings/reader-progress-strict').ChapterPosition} */ (foliatePosition).chapterIndex}:${Math.round(/** @type {import('../../../typings/reader-progress-strict').ChapterPosition} */ (foliatePosition).chapterOffset)}`
352
- : foliatePosition
353
- ? `foliate:${foliatePosition.foliateSection}:${Math.round(/** @type {number} */ (foliatePosition.foliateOffset))}`
354
- : pagedDocument
355
  ? `page:${readerContext.documentState.page}:${Math.round(pageOffset)}`
356
  : `progress:${progress}:${Math.round(readerContext.htmlFrame ? htmlScrollTop : scrollTop)}`;
357
  return {
@@ -365,7 +253,7 @@ export function createReaderBookmarks(readerContext) {
365
  pageOffset,
366
  scrollTop,
367
  htmlScrollTop,
368
- ...(foliatePosition || {})
369
  };
370
  }
371
 
@@ -421,9 +309,6 @@ export function createReaderBookmarks(readerContext) {
421
  consumeBookmarkHandoff,
422
  excerptFromCaret,
423
  bookmarkExcerpt,
424
- captureFoliateBookmarkPosition,
425
- restoreFoliateBookmarkPosition,
426
- seekFoliateProgress,
427
  renderBookmarks,
428
  captureBookmarkSnapshot,
429
  setBookmarkDialogModal,
 
147
  } catch (_) {}
148
  const exact = readerContext.excerptFromCaret(document, readerContext.content, x, y);
149
  if (exact) return exact;
150
+ const text = readerContext.content.textContent.replace(/\s+/g, " ").trim(),
 
 
 
 
 
 
 
 
 
151
  start = Math.floor((text.length * readerContext.readerProgressPercent()) / 100);
152
  return text.slice(start, start + 160).trim();
153
  }
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  async function renderBookmarks() {
156
  const list = /** @type {HTMLElement} */ (document.querySelector("#bookmarks-list")),
157
  generation = readerContext.nextReaderGeneration("bookmarks");
 
229
  };
230
  }
231
  readerContext.syncCurrentPageFromMarker();
232
+ const chapterPosition = readerContext.captureChapterPosition();
233
  const shell = readerContext.documentState.pageCount ? readerContext.pageAtMarker() : null;
234
  const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0;
235
  const progress = readerContext.readerProgressPercent();
 
237
  const scrollTop = readerContext.viewport.scrollTop;
238
  const mode = readerContext.capability.mode;
239
  const pagedDocument = readerContext.documentState.pageCount && mode !== "text" && mode !== "markdown";
240
+ const locator = chapterPosition
241
+ ? `chapter:${chapterPosition.chapterIndex}:${Math.round(chapterPosition.chapterOffset)}`
242
+ : pagedDocument
 
 
243
  ? `page:${readerContext.documentState.page}:${Math.round(pageOffset)}`
244
  : `progress:${progress}:${Math.round(readerContext.htmlFrame ? htmlScrollTop : scrollTop)}`;
245
  return {
 
253
  pageOffset,
254
  scrollTop,
255
  htmlScrollTop,
256
+ ...(chapterPosition || {})
257
  };
258
  }
259
 
 
309
  consumeBookmarkHandoff,
310
  excerptFromCaret,
311
  bookmarkExcerpt,
 
 
 
312
  renderBookmarks,
313
  captureBookmarkSnapshot,
314
  setBookmarkDialogModal,
static/reader/ui/reader-navigation.mjs CHANGED
@@ -4,7 +4,7 @@ export function createReaderNavigation(readerContext) {
4
  readerContext.cancelReaderDestinationHold?.();
5
  if (readerContext.epubSeekFrame) cancelAnimationFrame(readerContext.epubSeekFrame);
6
  readerContext.epubSeekFrame = 0;
7
- readerContext.foliateScrollAnchors.invalidate();
8
  return readerContext.nextReaderGeneration("navigation");
9
  }
10
 
@@ -167,8 +167,7 @@ export function createReaderNavigation(readerContext) {
167
  readerContext.pdfShellWindow?.schedule();
168
  readerContext.scheduleVisiblePdfRenderReconciliation?.(true);
169
  readerContext.scheduleMarkerSync();
170
- readerContext.scheduleFoliateScrollSync();
171
- readerContext.foliateScrollAnchors.remember();
172
  }
173
 
174
  /** @param {string} rawUrl @param {{id: string, url: string} | null} [bookmark] @param {boolean} [resumeHistory] */
 
4
  readerContext.cancelReaderDestinationHold?.();
5
  if (readerContext.epubSeekFrame) cancelAnimationFrame(readerContext.epubSeekFrame);
6
  readerContext.epubSeekFrame = 0;
7
+ readerContext.chapterScrollAnchors.invalidate();
8
  return readerContext.nextReaderGeneration("navigation");
9
  }
10
 
 
167
  readerContext.pdfShellWindow?.schedule();
168
  readerContext.scheduleVisiblePdfRenderReconciliation?.(true);
169
  readerContext.scheduleMarkerSync();
170
+ readerContext.chapterScrollAnchors.remember();
 
171
  }
172
 
173
  /** @param {string} rawUrl @param {{id: string, url: string} | null} [bookmark] @param {boolean} [resumeHistory] */
static/reader/ui/reader-progress.mjs CHANGED
@@ -36,7 +36,7 @@ export function createReaderProgress(readerContext) {
36
  const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0;
37
  const htmlScrollTop = readerContext.htmlFrame && readerContext.htmlFrame.contentWindow ? readerContext.htmlFrame.contentWindow.scrollY : 0;
38
  const readerUrl = readerContext.currentReaderUrl();
39
- const foliatePosition = readerContext.captureFoliateBookmarkPosition() || readerContext.captureChapterPosition();
40
  return {
41
  url: readerContext.sourceUrl,
42
  title: readerContext.documentState.title,
@@ -50,7 +50,7 @@ export function createReaderProgress(readerContext) {
50
  scrollTop: readerContext.viewport.scrollTop,
51
  htmlScrollTop,
52
  zoom: Math.round(readerContext.documentState.zoom * 100),
53
- ...(foliatePosition || {})
54
  };
55
  }
56
 
@@ -157,33 +157,6 @@ export function createReaderProgress(readerContext) {
157
  return readerContext.mediaElement.duration
158
  ? Math.round((readerContext.mediaElement.currentTime / readerContext.mediaElement.duration) * 1000) / 10
159
  : 0;
160
- if (readerContext.foliateContinuous) {
161
- const position = readerContext.captureFoliateBookmarkPosition(),
162
- count = readerContext.epubBook?.sections?.filter((section) => section.linear !== "no").length || 0,
163
- article =
164
- position &&
165
- document.querySelector(
166
- `.foliate-continuous article[data-section="${position.foliateSection}"]`
167
- ),
168
- fraction = article
169
- ? Math.max(
170
- 0,
171
- Math.min(
172
- 1,
173
- position.foliateOffset / Math.max(1, article.getBoundingClientRect().height)
174
- )
175
- )
176
- : 0;
177
- if (position && position.foliateSection < 0) {
178
- const index = -position.foliateSection - 1, spine = readerContext.epubBook?.sections || [];
179
- if (!spine[index]) return 0;
180
- const preceding = spine.slice(0, index).filter(item => item.linear !== "no").length;
181
- return count ? Math.round((preceding / count) * 1000) / 10 : 0;
182
- }
183
- return count && position
184
- ? Math.round(((position.foliateSection + fraction) / count) * 1000) / 10
185
- : 0;
186
- }
187
  if (readerContext.capability.mode === "epub-chapters")
188
  return Math.round((readerContext.chapterManifestLoader?.progressFraction() ?? 0) * 1000) / 10;
189
  if (readerContext.htmlFrame && readerContext.htmlFrame.contentDocument) {
@@ -270,8 +243,6 @@ export function createReaderProgress(readerContext) {
270
  if (Number.isInteger(entry.chapterIndex)) {
271
  if (!(await readerContext.restoreChapterPosition(entry, generation))) return false;
272
  } else if (!(await readerContext.restoreProgressState(entry, generation))) return false;
273
- } else if (mode === "foliate" && Number.isInteger(entry.foliateSection)) {
274
- if (!(await readerContext.restoreFoliateBookmarkPosition(entry, generation))) return false;
275
  } else if (readerContext.documentState.pageCount && entry.page) {
276
  if (
277
  !(await readerContext.goToPage(entry.page, generation)) ||
@@ -351,9 +322,7 @@ export function createReaderProgress(readerContext) {
351
  }
352
 
353
  function captureProgressState() {
354
- return readerContext.foliateContinuous
355
- ? readerContext.captureFoliateBookmarkPosition()
356
- : readerContext.capability.mode === "epub-chapters"
357
  ? readerContext.captureChapterPosition()
358
  : readerContext.mediaElement
359
  ? { mediaTime: readerContext.mediaElement.currentTime }
@@ -366,8 +335,6 @@ export function createReaderProgress(readerContext) {
366
  * @param {number} [generation] */
367
  async function restoreProgressState(state, generation = readerContext.beginReaderNavigation()) {
368
  if (!state || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
369
- if (readerContext.foliateContinuous && Number.isInteger(state.foliateSection))
370
- return readerContext.restoreFoliateBookmarkPosition(state, generation);
371
  if (readerContext.capability.mode === "epub-chapters" && Number.isInteger(state.chapterIndex))
372
  return readerContext.restoreChapterPosition(state, generation);
373
  try {
@@ -426,11 +393,6 @@ export function createReaderProgress(readerContext) {
426
  }
427
 
428
  function flushEpubSeek() {
429
- if (readerContext.epubSeekFrame) {
430
- cancelAnimationFrame(readerContext.epubSeekFrame);
431
- readerContext.epubSeekFrame = 0;
432
- readerContext.epubSeekPromise = readerContext.seekFoliateProgress((/** @type {{percent: number, generation: number}} */ (readerContext.epubSeekTarget)).percent, (/** @type {{percent: number, generation: number}} */ (readerContext.epubSeekTarget)).generation);
433
- }
434
  return readerContext.epubSeekPromise;
435
  }
436
 
@@ -443,13 +405,7 @@ export function createReaderProgress(readerContext) {
443
  if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return;
444
  if (readerContext.mediaElement && readerContext.mediaElement.duration)
445
  readerContext.mediaElement.currentTime = (readerContext.mediaElement.duration * percent) / 100;
446
- else if (readerContext.foliateContinuous) {
447
- readerContext.epubSeekTarget = { percent, generation };
448
- readerContext.epubSeekFrame = requestAnimationFrame(() => {
449
- readerContext.epubSeekFrame = 0;
450
- readerContext.epubSeekPromise = readerContext.seekFoliateProgress(percent, generation);
451
- });
452
- } else if (readerContext.capability.mode === "epub-chapters") {
453
  const target = Number.isFinite(percent) ? readerContext.chapterManifestLoader?.progressTarget(percent / 100) : null;
454
  if (target) {
455
  readerContext.epubSeekPromise = readerContext.restoreChapterPosition({
 
36
  const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0;
37
  const htmlScrollTop = readerContext.htmlFrame && readerContext.htmlFrame.contentWindow ? readerContext.htmlFrame.contentWindow.scrollY : 0;
38
  const readerUrl = readerContext.currentReaderUrl();
39
+ const chapterPosition = readerContext.captureChapterPosition();
40
  return {
41
  url: readerContext.sourceUrl,
42
  title: readerContext.documentState.title,
 
50
  scrollTop: readerContext.viewport.scrollTop,
51
  htmlScrollTop,
52
  zoom: Math.round(readerContext.documentState.zoom * 100),
53
+ ...(chapterPosition || {})
54
  };
55
  }
56
 
 
157
  return readerContext.mediaElement.duration
158
  ? Math.round((readerContext.mediaElement.currentTime / readerContext.mediaElement.duration) * 1000) / 10
159
  : 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  if (readerContext.capability.mode === "epub-chapters")
161
  return Math.round((readerContext.chapterManifestLoader?.progressFraction() ?? 0) * 1000) / 10;
162
  if (readerContext.htmlFrame && readerContext.htmlFrame.contentDocument) {
 
243
  if (Number.isInteger(entry.chapterIndex)) {
244
  if (!(await readerContext.restoreChapterPosition(entry, generation))) return false;
245
  } else if (!(await readerContext.restoreProgressState(entry, generation))) return false;
 
 
246
  } else if (readerContext.documentState.pageCount && entry.page) {
247
  if (
248
  !(await readerContext.goToPage(entry.page, generation)) ||
 
322
  }
323
 
324
  function captureProgressState() {
325
+ return readerContext.capability.mode === "epub-chapters"
 
 
326
  ? readerContext.captureChapterPosition()
327
  : readerContext.mediaElement
328
  ? { mediaTime: readerContext.mediaElement.currentTime }
 
335
  * @param {number} [generation] */
336
  async function restoreProgressState(state, generation = readerContext.beginReaderNavigation()) {
337
  if (!state || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
 
 
338
  if (readerContext.capability.mode === "epub-chapters" && Number.isInteger(state.chapterIndex))
339
  return readerContext.restoreChapterPosition(state, generation);
340
  try {
 
393
  }
394
 
395
  function flushEpubSeek() {
 
 
 
 
 
396
  return readerContext.epubSeekPromise;
397
  }
398
 
 
405
  if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return;
406
  if (readerContext.mediaElement && readerContext.mediaElement.duration)
407
  readerContext.mediaElement.currentTime = (readerContext.mediaElement.duration * percent) / 100;
408
+ else if (readerContext.capability.mode === "epub-chapters") {
 
 
 
 
 
 
409
  const target = Number.isFinite(percent) ? readerContext.chapterManifestLoader?.progressTarget(percent / 100) : null;
410
  if (target) {
411
  readerContext.epubSeekPromise = readerContext.restoreChapterPosition({
static/reader/ui/reader-speech.mjs CHANGED
@@ -84,15 +84,12 @@ export function createReaderSpeech(readerContext, loadPlayer) {
84
  const readerSpeechTitle = () => document.querySelector("#title")?.textContent?.trim() || document.title || "朗读";
85
 
86
  // ---- Per-format unit sources -------------------------------------------
87
- function foliateSections() {
88
- return (readerContext.epubBook?.sections || []).filter((section) => section.linear !== "no");
89
- }
90
  function chapterCount() { return readerContext.chapterManifestLoader?.count || 0; }
91
  function pageCount() { return Number(readerContext.documentState?.pageCount) || 0; }
92
 
93
  function hasText() {
94
  const current = mode();
95
- if (["text", "markdown", "html", "foliate", "epub-chapters", "pdf"].includes(current)) return true;
96
  if (current === "pdf-pages") return !!(readerContext.ocrManifestUrl || readerContext.pdfOcrManifest || readerContext.pdfDocument);
97
  return false;
98
  }
@@ -109,25 +106,6 @@ export function createReaderSpeech(readerContext, loadPlayer) {
109
  const root = () => frame?.contentDocument?.body || null;
110
  return { units: 1, first: 0, root, load: async () => rootText(root()), dom: true, frame };
111
  }
112
- if (current === "foliate") {
113
- const sections = foliateSections();
114
- /** @param {number} index */
115
- const article = (index) => readerContext.content.querySelector(`.foliate-continuous article[data-section="${index}"]:not(.foliate-section-placeholder)`);
116
- /** @param {number} index */
117
- const body = (index) => { const node = article(index); const root = node && readerContext.foliateSectionRoot(node); return root?.querySelector(".reader-section-body") || root || null; };
118
- return {
119
- units: sections.length, first: 0, root: body,
120
- load: async (index) => {
121
- const loaded = body(index);
122
- if (loaded) return rootText(loaded);
123
- const section = sections[index];
124
- if (!section) return "";
125
- const doc = await section.createDocument();
126
- return rootText(doc.body || doc.documentElement);
127
- },
128
- locate: (index) => readerContext.foliateSectionLoader?.(index)
129
- };
130
- }
131
  if (current === "epub-chapters") {
132
  // Valid chapter manifests have consecutive 1-based indices. Reading
133
  // their text doesn't require the optional full-text search index.
@@ -385,11 +363,7 @@ export function createReaderSpeech(readerContext, loadPlayer) {
385
  const box = readerContext.viewport.getBoundingClientRect();
386
  const current = mode();
387
  let unit = info.first;
388
- if (current === "foliate") {
389
- const article = [...readerContext.content.querySelectorAll(/** @type {string} */ (".foliate-continuous article[data-section]"))]
390
- .find((node) => node.getBoundingClientRect().bottom > box.top + 8);
391
- unit = article ? Number(/** @type {HTMLElement} */ (article).dataset.section) : 0;
392
- } else if (current === "epub-chapters") {
393
  const article = [...readerContext.content.querySelectorAll(".reader-epub-chapter[data-chapter]")]
394
  .find((node) => node.getBoundingClientRect().bottom > box.top + 8);
395
  const chapter = Number(/** @type {HTMLElement | undefined} */ (article)?.dataset.chapter);
 
84
  const readerSpeechTitle = () => document.querySelector("#title")?.textContent?.trim() || document.title || "朗读";
85
 
86
  // ---- Per-format unit sources -------------------------------------------
 
 
 
87
  function chapterCount() { return readerContext.chapterManifestLoader?.count || 0; }
88
  function pageCount() { return Number(readerContext.documentState?.pageCount) || 0; }
89
 
90
  function hasText() {
91
  const current = mode();
92
+ if (["text", "markdown", "html", "epub-chapters", "pdf"].includes(current)) return true;
93
  if (current === "pdf-pages") return !!(readerContext.ocrManifestUrl || readerContext.pdfOcrManifest || readerContext.pdfDocument);
94
  return false;
95
  }
 
106
  const root = () => frame?.contentDocument?.body || null;
107
  return { units: 1, first: 0, root, load: async () => rootText(root()), dom: true, frame };
108
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  if (current === "epub-chapters") {
110
  // Valid chapter manifests have consecutive 1-based indices. Reading
111
  // their text doesn't require the optional full-text search index.
 
363
  const box = readerContext.viewport.getBoundingClientRect();
364
  const current = mode();
365
  let unit = info.first;
366
+ if (current === "epub-chapters") {
 
 
 
 
367
  const article = [...readerContext.content.querySelectorAll(".reader-epub-chapter[data-chapter]")]
368
  .find((node) => node.getBoundingClientRect().bottom > box.top + 8);
369
  const chapter = Number(/** @type {HTMLElement | undefined} */ (article)?.dataset.chapter);
static/reader/ui/reader-toc.mjs CHANGED
@@ -103,7 +103,7 @@ export function createReaderToc(readerContext) {
103
  }
104
  const marker = readerContext.htmlFrame ? 8 : readerContext.viewport.getBoundingClientRect().top + 8;
105
  const root = readerContext.htmlFrame?.contentDocument?.body || readerContext.content;
106
- if (!["foliate", "epub-chapters"].some(mode => mode === readerContext.capability.mode)) {
107
  if (readerContext.headingLocationCache?.root !== root || readerContext.headingLocationCache?.entries !== readerContext.navigationState.tocEntries) {
108
  readerContext.headingLocationCache?.dispose();
109
  readerContext.headingLocationCache = readerContext.createHeadingLocationCache(root, readerContext.navigationState.tocEntries);
@@ -145,9 +145,7 @@ export function createReaderToc(readerContext) {
145
  if (!entry || entry.group) return;
146
  const generation = readerContext.beginReaderNavigation();
147
  try {
148
- const activated = readerContext.foliateContinuous
149
- ? await readerContext.activateFoliateTocEntry(entry, generation, { closePanel: false })
150
- : await entry.activate(generation);
151
  if (activated === false || !readerContext.isReaderGenerationCurrent("navigation", generation)) return;
152
  readerContext.updateNavigationState({ currentChapterIndex: index });
153
  readerContext.updateTocCurrentMark();
 
103
  }
104
  const marker = readerContext.htmlFrame ? 8 : readerContext.viewport.getBoundingClientRect().top + 8;
105
  const root = readerContext.htmlFrame?.contentDocument?.body || readerContext.content;
106
+ if (readerContext.capability.mode !== "epub-chapters") {
107
  if (readerContext.headingLocationCache?.root !== root || readerContext.headingLocationCache?.entries !== readerContext.navigationState.tocEntries) {
108
  readerContext.headingLocationCache?.dispose();
109
  readerContext.headingLocationCache = readerContext.createHeadingLocationCache(root, readerContext.navigationState.tocEntries);
 
145
  if (!entry || entry.group) return;
146
  const generation = readerContext.beginReaderNavigation();
147
  try {
148
+ const activated = await entry.activate(generation);
 
 
149
  if (activated === false || !readerContext.isReaderGenerationCurrent("navigation", generation)) return;
150
  readerContext.updateNavigationState({ currentChapterIndex: index });
151
  readerContext.updateTocCurrentMark();
static/reader/ui/reader-ui.mjs CHANGED
@@ -31,7 +31,7 @@ export function createReaderUi(readerContext) {
31
 
32
  /** @param {string} theme @param {boolean} [persist] @param {boolean} [animate] */
33
  function applyReaderTheme(theme, persist = true, animate = true) {
34
- const anchor = readerContext.foliateScrollAnchors.capture();
35
  if (animate) {
36
  clearTimeout(readerContext.themeAnimationTimer);
37
  document.documentElement.classList.add("theme-transition");
@@ -52,17 +52,15 @@ export function createReaderUi(readerContext) {
52
  readerContext.readerThemeToggle.title = readerContext.readerTheme === "dark" ? "切换到白天模式" : "切换到夜间模式";
53
  readerContext.readerThemeToggle.setAttribute("aria-label", readerContext.readerThemeToggle.title);
54
  readerContext.readerThemeToggle.setAttribute("aria-pressed", String(readerContext.readerTheme === "light"));
55
- for (const article of readerContext.content.querySelectorAll(".foliate-continuous > article"))
56
- article.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark");
57
  if (persist) {
58
  try { localStorage.setItem("theme", readerContext.readerTheme); } catch (_) {}
59
  }
60
- readerContext.foliateScrollAnchors.restore(anchor);
61
  }
62
 
63
  /** @param {number} percent @param {boolean} [persist] */
64
  function setZoom(percent, persist = true) {
65
- const anchor = readerContext.foliateScrollAnchors.capture();
66
  const pdfAnchor = ["pdf", "pdf-pages", "image-pages"].includes(readerContext.capability.mode || "unsupported")
67
  ? readerContext.pageAtMarker() : null;
68
  const pdfBounds = pdfAnchor?.getBoundingClientRect();
@@ -87,14 +85,12 @@ export function createReaderUi(readerContext) {
87
  if (readerContext.htmlFrame && readerContext.htmlFrame.contentDocument)
88
  readerContext.htmlFrame.contentDocument.documentElement.style.zoom = String(readerContext.documentState.zoom);
89
  if (readerContext.pdfDocument) readerContext.rerenderVisiblePdfPages();
90
- if (readerContext.capability.mode === "foliate")
91
- readerContext.content.style.setProperty("--reader-zoom", String(readerContext.documentState.zoom));
92
  readerContext.viewport.scrollLeft = horizontalCenter * readerContext.viewport.scrollWidth - readerContext.viewport.clientWidth / 2;
93
  if (persist) {
94
  readerContext.zoomChangedByUser = true;
95
  try { localStorage.setItem("reader-zoom", String(normalized)); } catch (_) {}
96
  }
97
- readerContext.foliateScrollAnchors.restore(anchor);
98
  if (persist) readerContext.scheduleSave();
99
  }
100
 
 
31
 
32
  /** @param {string} theme @param {boolean} [persist] @param {boolean} [animate] */
33
  function applyReaderTheme(theme, persist = true, animate = true) {
34
+ const anchor = readerContext.chapterScrollAnchors.capture();
35
  if (animate) {
36
  clearTimeout(readerContext.themeAnimationTimer);
37
  document.documentElement.classList.add("theme-transition");
 
52
  readerContext.readerThemeToggle.title = readerContext.readerTheme === "dark" ? "切换到白天模式" : "切换到夜间模式";
53
  readerContext.readerThemeToggle.setAttribute("aria-label", readerContext.readerThemeToggle.title);
54
  readerContext.readerThemeToggle.setAttribute("aria-pressed", String(readerContext.readerTheme === "light"));
 
 
55
  if (persist) {
56
  try { localStorage.setItem("theme", readerContext.readerTheme); } catch (_) {}
57
  }
58
+ readerContext.chapterScrollAnchors.restore(anchor);
59
  }
60
 
61
  /** @param {number} percent @param {boolean} [persist] */
62
  function setZoom(percent, persist = true) {
63
+ const anchor = readerContext.chapterScrollAnchors.capture();
64
  const pdfAnchor = ["pdf", "pdf-pages", "image-pages"].includes(readerContext.capability.mode || "unsupported")
65
  ? readerContext.pageAtMarker() : null;
66
  const pdfBounds = pdfAnchor?.getBoundingClientRect();
 
85
  if (readerContext.htmlFrame && readerContext.htmlFrame.contentDocument)
86
  readerContext.htmlFrame.contentDocument.documentElement.style.zoom = String(readerContext.documentState.zoom);
87
  if (readerContext.pdfDocument) readerContext.rerenderVisiblePdfPages();
 
 
88
  readerContext.viewport.scrollLeft = horizontalCenter * readerContext.viewport.scrollWidth - readerContext.viewport.clientWidth / 2;
89
  if (persist) {
90
  readerContext.zoomChangedByUser = true;
91
  try { localStorage.setItem("reader-zoom", String(normalized)); } catch (_) {}
92
  }
93
+ readerContext.chapterScrollAnchors.restore(anchor);
94
  if (persist) readerContext.scheduleSave();
95
  }
96
 
static/search/catalog/application/client.js CHANGED
@@ -4,6 +4,8 @@
4
  function create(deps) {
5
  const sidebarInitialCache = new Map();
6
  const sidebarInitialPending = new Map();
 
 
7
  const methods = {
8
  /** @this {SpaceCatalogOwner} */
9
  async getRepos() {
@@ -22,18 +24,36 @@
22
  /** @this {SpaceCatalogOwner} @param {string | null} repo */
23
  async getExtensions(repo) {
24
  const cacheKey = repo || "__global__";
25
- if (this._extCache && this._extCache.key === cacheKey) return this._extCache.data;
26
- if (!repo) {
27
- const bootstrap = await this.getBootstrap();
28
- if (bootstrap && Array.isArray(bootstrap.extensions)) {
29
- this._extCache = { key: cacheKey, data: bootstrap.extensions };
30
- return bootstrap.extensions;
31
- }
32
  }
33
- const url = repo ? `/api/extensions?repo=${repo}` : "/api/extensions";
34
- const data = await fetchMetadataList(url);
35
- this._extCache = { key: cacheKey, data };
36
- return data;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  },
38
  /** @param {string} repo */
39
  getFolders(repo) { return fetchMetadataList(`/api/folders/${repo}`); },
 
4
  function create(deps) {
5
  const sidebarInitialCache = new Map();
6
  const sidebarInitialPending = new Map();
7
+ /** @type {WeakMap<SpaceCatalogOwner, {marker: {key: string, data: VoiceOfMLFilterCount[]}, pending: Map<string, Promise<VoiceOfMLFilterCount[]>>}>} */
8
+ const extensionGenerations = new WeakMap();
9
  const methods = {
10
  /** @this {SpaceCatalogOwner} */
11
  async getRepos() {
 
24
  /** @this {SpaceCatalogOwner} @param {string | null} repo */
25
  async getExtensions(repo) {
26
  const cacheKey = repo || "__global__";
27
+ let generation = extensionGenerations.get(this);
28
+ if (!generation || this._extCache !== generation.marker) {
29
+ // The host invalidates by assigning null, even when a request is pending.
30
+ const marker = this._extCache || { key: "", data: [] };
31
+ this._extCache = marker;
32
+ generation = { marker, pending: new Map() };
33
+ extensionGenerations.set(this, generation);
34
  }
35
+ if (generation.marker.key === cacheKey) return generation.marker.data;
36
+ const current = generation;
37
+ const existing = current.pending.get(cacheKey);
38
+ if (existing) return existing;
39
+ const pending = Promise.resolve().then(async () => {
40
+ if (!repo) {
41
+ const bootstrap = await this.getBootstrap();
42
+ if (bootstrap && Array.isArray(bootstrap.extensions)) return bootstrap.extensions;
43
+ }
44
+ const url = repo ? `/api/extensions?repo=${repo}` : "/api/extensions";
45
+ return fetchMetadataList(url);
46
+ }).then(data => {
47
+ if (extensionGenerations.get(this) === current && this._extCache === current.marker) {
48
+ current.marker = { key: cacheKey, data };
49
+ this._extCache = current.marker;
50
+ }
51
+ return data;
52
+ }).finally(() => {
53
+ if (current.pending.get(cacheKey) === pending) current.pending.delete(cacheKey);
54
+ });
55
+ current.pending.set(cacheKey, pending);
56
+ return pending;
57
  },
58
  /** @param {string} repo */
59
  getFolders(repo) { return fetchMetadataList(`/api/folders/${repo}`); },
static/search/sidebar/presentation/folder-tree.js CHANGED
@@ -240,13 +240,12 @@ function persistFolderSelection(subtreeSet, selfSet) {
240
  deps.commitSelection(Array.from(subtreeSet), Array.from(selfSet));
241
  }
242
 
243
- /** @param {VoiceOfMLFilterFolder[]} nodes @param {string[]} subtreePaths @param {string[]} selfPaths */
244
- function collectFolderNodePaths(nodes, subtreePaths, selfPaths) {
245
  for (const node of nodes) {
246
- if (!node.isRoot && node.path) subtreePaths.push(node.path);
247
  if (node.hasDirectFiles) selfPaths.push(node.path);
248
  if (node.children && node.children.length > 0) {
249
- collectFolderNodePaths(node.children, subtreePaths, selfPaths);
250
  }
251
  }
252
  }
@@ -361,7 +360,7 @@ function appendFilterTreeNode(container, node, depth, subtreeSet, selfSet, looku
361
  function handleFolderCheckboxChange(node) {
362
  const subtreeSet = getFolderSubtreeSet();
363
  const selfSet = getFolderSelfSet();
364
- const { full } = deps.selection.folderSelectionState(node, subtreeSet, selfSet);
365
  setNodeSubtreeSelection(node, !full, subtreeSet, selfSet);
366
  persistFolderSelection(subtreeSet, selfSet);
367
  refreshFilterFolderSelectionState();
@@ -400,9 +399,8 @@ function invertSelection() {
400
  if (!deps.readView().tree || deps.readView().tree.length === 0) return;
401
  var subtreeSet = getFolderSubtreeSet();
402
  var selfSet = getFolderSelfSet();
403
- var allSubtreePaths = /** @type {string[]} */ ([]);
404
  var allSelfPaths = /** @type {string[]} */ ([]);
405
- collectFolderNodePaths(deps.readView().tree, allSubtreePaths, allSelfPaths);
406
  var nextSubtreeSet = new Set(/** @type {string[]} */ ([]));
407
  var nextSelfSet = new Set();
408
  for (const path of allSelfPaths) {
 
240
  deps.commitSelection(Array.from(subtreeSet), Array.from(selfSet));
241
  }
242
 
243
+ /** @param {VoiceOfMLFilterFolder[]} nodes @param {string[]} selfPaths */
244
+ function collectFolderNodePaths(nodes, selfPaths) {
245
  for (const node of nodes) {
 
246
  if (node.hasDirectFiles) selfPaths.push(node.path);
247
  if (node.children && node.children.length > 0) {
248
+ collectFolderNodePaths(node.children, selfPaths);
249
  }
250
  }
251
  }
 
360
  function handleFolderCheckboxChange(node) {
361
  const subtreeSet = getFolderSubtreeSet();
362
  const selfSet = getFolderSelfSet();
363
+ const { full } = deps.selection.folderSelectionState(node, subtreeSet, selfSet, getFolderSelectionLookup(subtreeSet, selfSet));
364
  setNodeSubtreeSelection(node, !full, subtreeSet, selfSet);
365
  persistFolderSelection(subtreeSet, selfSet);
366
  refreshFilterFolderSelectionState();
 
399
  if (!deps.readView().tree || deps.readView().tree.length === 0) return;
400
  var subtreeSet = getFolderSubtreeSet();
401
  var selfSet = getFolderSelfSet();
 
402
  var allSelfPaths = /** @type {string[]} */ ([]);
403
+ collectFolderNodePaths(deps.readView().tree, allSelfPaths);
404
  var nextSubtreeSet = new Set(/** @type {string[]} */ ([]));
405
  var nextSelfSet = new Set();
406
  for (const path of allSelfPaths) {
tests/fixtures/reader/issues/manifest.json CHANGED
@@ -2,7 +2,7 @@
2
  "schema": 1,
3
  "fixtures": [
4
  { "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" },
5
- { "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" },
6
  { "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" }
7
  ,{ "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" }
8
  ,{ "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" }
 
2
  "schema": 1,
3
  "fixtures": [
4
  { "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" },
5
+ { "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" },
6
  { "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" }
7
  ,{ "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" }
8
  ,{ "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" }
tests/gates/ci-test-inventory.json CHANGED
@@ -490,10 +490,6 @@
490
  "kind": "script",
491
  "source": "scripts/reader/check_reader_media_coverage.mjs"
492
  },
493
- "tests/reader/test_foliate_proxy.mjs": {
494
- "kind": "script",
495
- "source": "scripts/reader/check_reader_media_coverage.mjs"
496
- },
497
  "tests/reader/media/test_reader_media_baseline.mjs": {
498
  "kind": "script",
499
  "source": "scripts/reader/check_reader_media_coverage.mjs"
 
490
  "kind": "script",
491
  "source": "scripts/reader/check_reader_media_coverage.mjs"
492
  },
 
 
 
 
493
  "tests/reader/media/test_reader_media_baseline.mjs": {
494
  "kind": "script",
495
  "source": "scripts/reader/check_reader_media_coverage.mjs"
tests/gates/test_static_checks.py CHANGED
@@ -2887,9 +2887,9 @@ const options = {signal: undefined};
2887
  'scripts/reader/check_reader_media_coverage.mjs', 'scripts/check_tap_contracts.mjs',
2888
  'tests/reader/media/test_reader_media_baseline.mjs',
2889
  'tests/reader/media/test_reader_media_metadata.mjs',
2890
- 'tests/reader/copy_reader_vendor.test.mjs', 'tests/reader/test_foliate_proxy.mjs',
2891
  'tests/reader/media/test_ruffle_closure.mjs', 'tests/service_worker/test_ruffle_retention.js',
2892
- 'scripts/build/copy_reader_vendor.mjs', 'scripts/build/fetch_foliate_reader.mjs',
2893
  'scripts/build/check_reader_release.mjs', 'static/reader-resources.js', 'static/sw.js',
2894
  'static/reader/core/reader-source.mjs', 'static/reader/core/reader-document-loader.mjs']
2895
  for path in paths:
 
2887
  'scripts/reader/check_reader_media_coverage.mjs', 'scripts/check_tap_contracts.mjs',
2888
  'tests/reader/media/test_reader_media_baseline.mjs',
2889
  'tests/reader/media/test_reader_media_metadata.mjs',
2890
+ 'tests/reader/copy_reader_vendor.test.mjs',
2891
  'tests/reader/media/test_ruffle_closure.mjs', 'tests/service_worker/test_ruffle_retention.js',
2892
+ 'scripts/build/copy_reader_vendor.mjs',
2893
  'scripts/build/check_reader_release.mjs', 'static/reader-resources.js', 'static/sw.js',
2894
  'static/reader/core/reader-source.mjs', 'static/reader/core/reader-document-loader.mjs']
2895
  for path in paths:
tests/gates/test_static_contract.py CHANGED
@@ -355,8 +355,8 @@ console.log('OCR module contract passed; 6 negative controls rejected');
355
  self.assertIn("async function activateChapter", reader)
356
  assert_source_contains(self, "progressUndo.hidden = !previousProgressState", reader)
357
  assert_source_contains(self, "result.activate(generation)", reader)
358
- modes = {'pdf': 'pdf', 'pdf-pages': 'pdf-pages', 'epub': 'foliate', 'mobi': 'foliate',
359
- 'fb2': 'foliate', 'txt': 'text', 'md': 'markdown', 'jpg': 'image',
360
  'mp3': 'audio', 'wav': 'audio', 'flac': 'audio', 'mp4': 'video', 'mov': 'video',
361
  'docx': None, 'epub-chapters': 'epub-chapters', 'html': 'html', 'htm': 'html'}
362
  evaluated = subprocess.run(
@@ -375,7 +375,8 @@ console.log('OCR module contract passed; 6 negative controls rejected');
375
  self.assertIn('VoiceOfMLReaderResources.vendorUrl("pdf", "/static/")', reader)
376
  assert_source_contains(self, 'const PDFJS_WASM_URL = "/static/vendor/wasm/"', reader)
377
  assert_source_contains(self, 'wasmUrl: PDFJS_WASM_URL', reader)
378
- self.assertIn('/static/foliate-reader/view.js', reader)
 
379
  self.assertIn('VoiceOfMLReaderResources.vendorUrl("purify", "/static/")', reader)
380
  self.assertNotIn('cdn.jsdelivr.net', reader)
381
  self.assertIn("IntersectionObserver", reader)
@@ -606,13 +607,11 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
606
  self.assertIn('VoiceOfMLReaderStore.put', reader)
607
  self.assertIn('VoiceOfMLReaderStore.get', reader)
608
  self.assertIn('function goToPage', reader)
609
- self.assertIn('foliateContinuous', reader)
610
  self.assertIn('viewport.scrollTop', reader)
611
  self.assertIn("base-uri 'self' blob:", reader_html)
612
  self.assertIn("style-src 'self' 'unsafe-inline' blob:", reader_html)
613
  for value in ('epubSearchIndex', 'epubSearchIndexReady', 'epubZipPath', 'buildEpubSearchIndex', 'activateIndexedEpubResult', 'runIndexedEpubSearch'):
614
  self.assertNotIn(value, reader)
615
- self.assertRegex(reader, r'await view\.open\(\s*new File\(\s*\[bytes\]')
616
  self.assertNotIn('epubRendition.setReaderTheme(readerTheme)', reader)
617
  self.assertNotIn('epubRendition.themes', reader)
618
  self.assertIn('function applyReaderTheme', reader)
@@ -627,18 +626,7 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
627
  (ROOT / "static/search/reader-host/application/host.js").read_text())
628
  self.assertIn('readerHost.handleReaderMessage(event)', self.js)
629
  self.assertNotIn('loadFoliateDocument', reader)
630
- self.assertIn('async function renderFoliate', reader)
631
- foliate = (ROOT / "static/reader/formats/reader-foliate-format.mjs").read_text(encoding="utf-8")
632
- foliate_import = ('const foliateModuleUrl = "/static/foliate-reader/view.js"; '
633
- 'const prepared = readerContext.prepareReaderDocument([import(foliateModuleUrl)]);')
634
- assert_source_contains(self, foliate_import, foliate)
635
- for before, after in (('import(foliateModuleUrl)', 'Promise.resolve(null)'),
636
- ('/static/foliate-reader/view.js', '/static/wrong-view.js')):
637
- with self.subTest(foliate_import=before):
638
- self.assertEqual(foliate.count(before), 1)
639
- with self.assertRaises(AssertionError):
640
- assert_source_contains(self, foliate_import, foliate.replace(before, after))
641
- self.assertIn('async function renderFoliate', reader)
642
  assert_source_contains(self, 'const READER_PROXY_TIMEOUT_MS = 120000', reader)
643
  self.assertIn('function fetchWithReaderTimeout', reader)
644
  self.assertIn('function renderPdfShell', reader)
@@ -673,16 +661,12 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
673
  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'):
674
  self.assertNotIn(path, self.sw)
675
 
676
- def test_foliate_continuous_reader_preserves_embedded_resources(self):
677
- epub = (ROOT / "static/foliate-reader/epub.js").read_text(encoding="utf-8")
678
- mobi = (ROOT / "static/foliate-reader/mobi.js").read_text(encoding="utf-8")
679
  reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")
680
- self.assertIn("const url = await this.#loader.loadItem(item)", epub)
681
- self.assertIn("const text = await response.text()", epub)
682
- self.assertIn("parseFromString(text, MIME.HTML)", epub)
683
- self.assertIn("await this.replaceResources(doc)", mobi)
684
- self.assertIn("const replaced = await this.replaceResources(str)", mobi)
685
- self.assertIn("for (const [url, node] of this.#inlineMap)", mobi)
686
  self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:")
687
 
688
  def test_mobile_shell_hides_sidebars_before_application_startup(self):
@@ -747,7 +731,6 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
747
 
748
  def test_image_pages_prioritize_visible_pages_without_document_image_race(self):
749
  reader = read_reader_source(ROOT)
750
- assert_source_contains(self, 'root: viewport, rootMargin: `${FOLIATE_PREFETCH_MARGIN}px`', reader)
751
  assert_source_contains(self, 'root: viewport, rootMargin: `${PDF_PREFETCH_MARGIN}px 0px`', reader)
752
  assert_source_contains(self, 'const visibleObserver = new IntersectionObserver', reader)
753
  assert_source_contains(self, 'renderPdfInBackground(entry.target)', reader)
 
355
  self.assertIn("async function activateChapter", reader)
356
  assert_source_contains(self, "progressUndo.hidden = !previousProgressState", reader)
357
  assert_source_contains(self, "result.activate(generation)", reader)
358
+ modes = {'pdf': 'pdf', 'pdf-pages': 'pdf-pages', 'epub': None, 'mobi': None,
359
+ 'fb2': None, 'txt': 'text', 'md': 'markdown', 'jpg': 'image',
360
  'mp3': 'audio', 'wav': 'audio', 'flac': 'audio', 'mp4': 'video', 'mov': 'video',
361
  'docx': None, 'epub-chapters': 'epub-chapters', 'html': 'html', 'htm': 'html'}
362
  evaluated = subprocess.run(
 
375
  self.assertIn('VoiceOfMLReaderResources.vendorUrl("pdf", "/static/")', reader)
376
  assert_source_contains(self, 'const PDFJS_WASM_URL = "/static/vendor/wasm/"', reader)
377
  assert_source_contains(self, 'wasmUrl: PDFJS_WASM_URL', reader)
378
+ self.assertNotIn('/static/foliate-reader/', reader)
379
+ self.assertNotIn('renderFoliate', reader)
380
  self.assertIn('VoiceOfMLReaderResources.vendorUrl("purify", "/static/")', reader)
381
  self.assertNotIn('cdn.jsdelivr.net', reader)
382
  self.assertIn("IntersectionObserver", reader)
 
607
  self.assertIn('VoiceOfMLReaderStore.put', reader)
608
  self.assertIn('VoiceOfMLReaderStore.get', reader)
609
  self.assertIn('function goToPage', reader)
 
610
  self.assertIn('viewport.scrollTop', reader)
611
  self.assertIn("base-uri 'self' blob:", reader_html)
612
  self.assertIn("style-src 'self' 'unsafe-inline' blob:", reader_html)
613
  for value in ('epubSearchIndex', 'epubSearchIndexReady', 'epubZipPath', 'buildEpubSearchIndex', 'activateIndexedEpubResult', 'runIndexedEpubSearch'):
614
  self.assertNotIn(value, reader)
 
615
  self.assertNotIn('epubRendition.setReaderTheme(readerTheme)', reader)
616
  self.assertNotIn('epubRendition.themes', reader)
617
  self.assertIn('function applyReaderTheme', reader)
 
626
  (ROOT / "static/search/reader-host/application/host.js").read_text())
627
  self.assertIn('readerHost.handleReaderMessage(event)', self.js)
628
  self.assertNotIn('loadFoliateDocument', reader)
629
+ assert_source_contains(self, '"epub-chapters": pair(loadChapterManifestDocument, renderChapterManifest)', reader)
 
 
 
 
 
 
 
 
 
 
 
630
  assert_source_contains(self, 'const READER_PROXY_TIMEOUT_MS = 120000', reader)
631
  self.assertIn('function fetchWithReaderTimeout', reader)
632
  self.assertIn('function renderPdfShell', reader)
 
661
  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'):
662
  self.assertNotIn(path, self.sw)
663
 
664
+ def test_chapter_reader_bounds_embedded_resources(self):
665
+ chapter = (ROOT / "static/reader/formats/reader-chapter-format.mjs").read_text(encoding="utf-8")
 
666
  reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")
667
+ assert_source_contains(self, 'readerContext.trustedChapterReferenceUrl(value, url, manifestBase)', chapter)
668
+ assert_source_contains(self, 'const resolved = resourceUrl(value, url, name === "href" ? "href" : "resource")', chapter)
669
+ assert_source_contains(self, 'element.removeAttribute(name)', chapter)
 
 
 
670
  self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:")
671
 
672
  def test_mobile_shell_hides_sidebars_before_application_startup(self):
 
731
 
732
  def test_image_pages_prioritize_visible_pages_without_document_image_race(self):
733
  reader = read_reader_source(ROOT)
 
734
  assert_source_contains(self, 'root: viewport, rootMargin: `${PDF_PREFETCH_MARGIN}px 0px`', reader)
735
  assert_source_contains(self, 'const visibleObserver = new IntersectionObserver', reader)
736
  assert_source_contains(self, 'renderPdfInBackground(entry.target)', reader)
tests/live/test_reader_live_smoke.py CHANGED
@@ -31,6 +31,7 @@ class ReaderLiveSmokeTests(unittest.TestCase):
31
  inventory = json.loads(subprocess.check_output([
32
  "node", "-e", 'console.log(JSON.stringify(require("./static/reader-resources.js").readerFiles))'
33
  ], cwd=Path(__file__).resolve().parents[2]))
 
34
  sw = self.fetch('/sw.js')
35
  pinned = set(re.findall(r'/static/[^"\s]+\.[0-9a-f]{12}\.(?:js|mjs|css)', sw))
36
  def current(name):
@@ -38,7 +39,7 @@ class ReaderLiveSmokeTests(unittest.TestCase):
38
  matches = [url for url in pinned if re.fullmatch('/static/' + re.escape(stem) + r'\.[0-9a-f]{12}\.' + extension, url)]
39
  self.assertEqual(len(matches), 1, name)
40
  return matches[0]
41
- files = ["/static/reader.html", *map(current, inventory), "/static/foliate-reader/view.js"]
42
  bodies = {path: self.fetch(path) for path in files}
43
  self.assertTrue(all(len(body) > 20 for body in bodies.values()))
44
  self.assertRegex(bodies[current('reader.js')], r"createReaderRuntime|VoiceOfMLReaderRuntime")
 
31
  inventory = json.loads(subprocess.check_output([
32
  "node", "-e", 'console.log(JSON.stringify(require("./static/reader-resources.js").readerFiles))'
33
  ], cwd=Path(__file__).resolve().parents[2]))
34
+ self.assertFalse([name for name in inventory if 'foliate' in name.lower()])
35
  sw = self.fetch('/sw.js')
36
  pinned = set(re.findall(r'/static/[^"\s]+\.[0-9a-f]{12}\.(?:js|mjs|css)', sw))
37
  def current(name):
 
39
  matches = [url for url in pinned if re.fullmatch('/static/' + re.escape(stem) + r'\.[0-9a-f]{12}\.' + extension, url)]
40
  self.assertEqual(len(matches), 1, name)
41
  return matches[0]
42
+ files = ["/static/reader.html", *map(current, inventory)]
43
  bodies = {path: self.fetch(path) for path in files}
44
  self.assertTrue(all(len(body) > 20 for body in bodies.values()))
45
  self.assertRegex(bodies[current('reader.js')], r"createReaderRuntime|VoiceOfMLReaderRuntime")
tests/performance/test_reader_performance.py CHANGED
@@ -1558,465 +1558,22 @@ class ReaderPerformanceTest(unittest.TestCase):
1558
  self.assertIn("第二章", second.inner_text())
1559
  self.assertEqual(unexpected_requests, [])
1560
 
1561
- def test_foliate_normalizes_legacy_chm_markup_and_keeps_resources(self):
1562
- # This case verifies preservation of source CSS; night colors have a separate contract.
1563
- self.page.add_init_script("localStorage.setItem('theme', 'light')")
1564
- with zipfile.ZipFile(io.BytesIO(epub_with_legacy_chm_markup())) as archive:
1565
- files = {name: archive.read(name) for name in archive.namelist()}
1566
- chapter_path = "OEBPS/chapters space%20/chapter.xhtml"
1567
- files["OEBPS/content.opf"] = files["OEBPS/content.opf"].replace(
1568
- b'href="chapter.xhtml"',
1569
- f'href="{urllib.parse.quote(chapter_path.removeprefix("OEBPS/"))}"'.encode(),
1570
- )
1571
- resource_files = {
1572
- f"OEBPS/images %23/{name}": PNG_BYTES
1573
- for name in ("cover#1.png", "cover space.png", "literal%20.png", "literal%23.png")
1574
- }
1575
- resource_files["OEBPS/chapters space%20/local image.png"] = PNG_BYTES
1576
- images = []
1577
- for path in resource_files:
1578
- relative = (path.removeprefix("OEBPS/chapters space%20/")
1579
- if path.startswith("OEBPS/chapters space%20/")
1580
- else "../" + path.removeprefix("OEBPS/"))
1581
- images.append(f'<image href="{urllib.parse.quote(relative)}" width="16" height="16"/>')
1582
- chapter = files.pop("OEBPS/chapter.xhtml").decode().replace(
1583
- 'href="style.css"', 'href="../style.css"',
1584
- ).replace('src="picture.svg"', 'src="../picture.svg"')
1585
- files[chapter_path] = chapter.replace(
1586
- "<html:img",
1587
- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="16">'
1588
- + "".join(images) + '</svg><html:a id="full-image" href="local%20image.png">查看原图</html:a><html:img',
1589
- )
1590
- files.update(resource_files)
1591
- payload = zip_bytes(files)
1592
- requested_paths = []
1593
-
1594
- def resource(route):
1595
- params = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)
1596
- path = params["path"][0]
1597
- requested_paths.append(path)
1598
- self.assertEqual(params["book"], [source])
1599
- # Match the backend's literal ZIP lookup, without an extra URL decode.
1600
- with zipfile.ZipFile(io.BytesIO(payload)) as archive:
1601
- try:
1602
- body = archive.read(path)
1603
- except KeyError:
1604
- route.fulfill(status=404, body="missing member")
1605
- return
1606
- route.fulfill(status=200, content_type="image/png", body=body)
1607
 
1608
- self.context.route("**/api/reader-resource**", resource)
1609
- self.page.unroute("**/api/reader-content**")
1610
- self.page.route("**/api/reader-content**", lambda route: route.fulfill(
1611
- status=200, content_type="application/epub+zip", body=payload,
1612
- ))
1613
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/legacy.chm"
1614
- query = urllib.parse.quote(source, safe="")
1615
- self.page.goto(f"{self.origin}/static/reader.html?url={query}&ext=epub&title=Legacy", wait_until="domcontentloaded")
1616
- paragraph = self.page.locator(".foliate-continuous article[data-section='0'] #legacy")
1617
- paragraph.wait_for(state="visible")
1618
- self.assertEqual(paragraph.text_content(), "Legacy CHM content正文第一段正文第二段")
1619
- self.assertEqual(self.page.locator(".foliate-continuous #after-image").text_content(), "图片之后的正文")
1620
- self.assertEqual(self.page.locator(".foliate-continuous h1").text_content(), "Article title")
1621
- image = self.page.locator(".foliate-continuous article[data-section='0'] img")
1622
- image.wait_for(state="visible")
1623
- self.page.wait_for_timeout(100)
1624
- self.assertEqual(paragraph.evaluate("element => getComputedStyle(element).color"), "rgb(1, 2, 3)")
1625
- self.assertTrue((image.get_attribute("src") or "").startswith("blob:"))
1626
- self.assertGreater(image.bounding_box()["height"], 0)
1627
- self.page.wait_for_function("""count => performance.getEntriesByType('resource')
1628
- .filter(entry => entry.name.includes('/api/reader-resource?')).length >= count""",
1629
- arg=len(resource_files))
1630
- self.assertEqual(set(requested_paths), set(resource_files))
1631
- resource_paths = self.page.locator(".foliate-continuous article[data-section='0'] svg image").evaluate_all("""images =>
1632
- images.map(image => new URL(image.getAttribute('href'), location.origin).searchParams.get('path'))""")
1633
- self.assertCountEqual(resource_paths, resource_files)
1634
- with self.page.expect_popup() as opened:
1635
- self.page.locator('.foliate-continuous #full-image').click()
1636
- popup = opened.value
1637
- popup.wait_for_load_state()
1638
- self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(popup.url).query)['path'],
1639
- ['OEBPS/chapters space%20/local image.png'])
1640
- popup.wait_for_function('() => document.querySelector("img")?.naturalWidth === 1')
1641
- popup.close()
1642
-
1643
- def test_foliate_navigation_path_dark_links_and_unique_sections(self):
1644
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1645
- self.addCleanup(context.close)
1646
- page = context.new_page()
1647
- page.add_init_script("localStorage.setItem('theme', 'dark')")
1648
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1649
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_navigation()))
1650
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/e2e.epub"
1651
- url = f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=E2E&path=Test%2Fbooks"
1652
- page.goto(url, wait_until="domcontentloaded")
1653
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 2")
1654
- link = page.locator(".foliate-continuous article[data-section='0'] a").first
1655
- link.wait_for(state="attached")
1656
- self.assertIsNotNone(page.locator(".foliate-continuous article[data-section='0']").evaluate("article => article.shadowRoot"))
1657
- title_display = page.locator("#title").evaluate("element => getComputedStyle(element).display")
1658
- 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); }")
1659
- self.assertEqual(page.locator("#title").evaluate("element => getComputedStyle(element).display"), title_display)
1660
- self.assertEqual(link.evaluate("element => getComputedStyle(element).borderTopStyle"), "dotted")
1661
- self.assertEqual(link.evaluate("element => getComputedStyle(element).color"), "rgb(138, 180, 232)")
1662
- open_reader_panel(page)
1663
- for theme, color in (("light", "rgb(1, 2, 3)"), ("dark", "rgb(138, 180, 232)")):
1664
- page.locator("#theme-toggle").click()
1665
- page.wait_for_function("() => !document.documentElement.classList.contains('theme-transition')")
1666
- self.assertEqual(page.locator("html").get_attribute("data-theme"), theme)
1667
- self.assertEqual(link.evaluate("element => getComputedStyle(element).color"), color)
1668
- page.locator("#history").click()
1669
- self.assertEqual(page.locator("#reader-path").text_content(), "Test/books")
1670
- self.assertIsNone(page.locator("#reader-path").get_attribute("hidden"))
1671
- initial_url = page.url
1672
- link.click()
1673
- page.wait_for_function("() => document.querySelector('#viewport').scrollTop > 0")
1674
- self.assertEqual(page.url, initial_url)
1675
- self.assertAlmostEqual(page.locator("#one").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2)
1676
- open_reader_panel(page)
1677
- page.locator("#toc-list .panel-item-main").nth(1).click()
1678
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(2)').classList.contains('is-current')")
1679
- page.wait_for_function("() => document.querySelectorAll('.foliate-continuous article[data-section]').length === 3")
1680
- sections = page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => item.dataset.section)")
1681
- self.assertEqual(sections, ["0", "1", "2"])
1682
- page.locator("#viewport").evaluate("element => { element.scrollTop = element.scrollHeight; element.dispatchEvent(new Event('scroll')); }")
1683
- page.wait_for_timeout(250)
1684
- self.assertEqual(page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => item.dataset.section)"), ["0", "1", "2"])
1685
- context.close()
1686
 
1687
- def test_foliate_rapid_toc_navigation_keeps_latest_destination(self):
1688
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1689
- page = context.new_page()
1690
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1691
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1692
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/race.epub"
1693
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Race", wait_until="domcontentloaded")
1694
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1695
- page.evaluate("""() => {
1696
- const sections = document.querySelector('foliate-view').book.sections.filter(section => section.linear !== 'no');
1697
- for (const [index, delay] of [[6, 350], [10, 20]]) {
1698
- const original = sections[index].createDocument.bind(sections[index]);
1699
- sections[index].createDocument = () => new Promise((resolve, reject) => setTimeout(() => original().then(resolve, reject), delay));
1700
- }
1701
- document.querySelectorAll('#toc-list .panel-item-main')[5].click();
1702
- document.querySelectorAll('#toc-list .panel-item-main')[9].click();
1703
- }""")
1704
- page.wait_for_timeout(700)
1705
- self.assertTrue(page.locator("#toc-list .toc-item").nth(9).evaluate("item => item.classList.contains('is-current')"))
1706
- self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2)
1707
- sections = page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => Number(item.dataset.section))")
1708
- self.assertEqual(sections, sorted(set(sections)))
1709
- context.close()
1710
 
1711
- def test_foliate_failed_toc_section_can_retry(self):
1712
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1713
- page = context.new_page()
1714
- errors = []
1715
- page.on("pageerror", lambda error: errors.append(str(error)))
1716
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1717
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1718
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/retry.epub"
1719
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Retry", wait_until="domcontentloaded")
1720
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1721
- page.evaluate("""() => {
1722
- const sections = document.querySelector('foliate-view').book.sections.filter(item => item.linear !== 'no');
1723
- const section = sections[10];
1724
- window.__neighborFailures = 0;
1725
- sections[9].createDocument = () => { window.__neighborFailures++; return Promise.reject(new Error('neighbor unavailable')); };
1726
- const original = section.createDocument.bind(section); let attempts = 0;
1727
- section.createDocument = () => ++attempts === 1 ? Promise.reject(new Error('transient section failure')) : original();
1728
- window.__retrySection = () => document.querySelectorAll('#toc-list .panel-item-main')[9].click();
1729
- }""")
1730
- page.evaluate("window.__retrySection()")
1731
- page.wait_for_timeout(100)
1732
- page.evaluate("window.__retrySection()")
1733
- page.locator("#chapter-10").wait_for(timeout=5000)
1734
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1735
- self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2)
1736
- self.assertGreater(page.evaluate("window.__neighborFailures"), 0)
1737
- self.assertEqual(page.locator(".reader-error").count(), 0)
1738
- self.assertEqual(errors, [])
1739
- context.close()
1740
 
1741
- def test_foliate_duplicate_toc_navigation_shares_section_load(self):
1742
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1743
- page = context.new_page()
1744
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1745
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1746
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/deduplicate.epub"
1747
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Deduplicate", wait_until="domcontentloaded")
1748
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1749
- page.evaluate("""() => {
1750
- const section = document.querySelector('foliate-view').book.sections.filter(item => item.linear !== 'no')[10];
1751
- const original = section.createDocument.bind(section); window.__sectionCreates = 0;
1752
- section.createDocument = () => { window.__sectionCreates += 1; return new Promise((resolve, reject) => setTimeout(() => original().then(resolve, reject), 200)); };
1753
- document.querySelectorAll('#toc-list .panel-item-main')[9].click();
1754
- document.querySelectorAll('#toc-list .panel-item-main')[9].click();
1755
- }""")
1756
- page.locator("#chapter-10").wait_for(timeout=5000)
1757
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1758
- self.assertEqual(page.evaluate("window.__sectionCreates"), 1)
1759
- self.assertEqual(page.locator(".foliate-continuous article[data-section='10']").count(), 1)
1760
- self.assertTrue(page.locator("#toc-list .toc-item").nth(9).evaluate("item => item.classList.contains('is-current')"))
1761
- context.close()
1762
 
1763
- def test_foliate_chapter_buttons_use_continuous_reader_navigation(self):
1764
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1765
- page = context.new_page()
1766
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1767
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1768
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/chapter-buttons.epub"
1769
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Buttons", wait_until="domcontentloaded")
1770
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1771
- open_reader_panel(page)
1772
- page.locator("#toc-list .panel-item-main").nth(9).click()
1773
- page.locator("#chapter-10").wait_for(timeout=5000)
1774
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1775
- open_reader_panel(page)
1776
- page.locator(".reader-chapter-next").click()
1777
- page.locator("#chapter-11").wait_for(timeout=5000)
1778
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(11)').classList.contains('is-current')")
1779
- self.assertAlmostEqual(page.locator("#chapter-11").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2)
1780
- self.assertTrue(page.locator("#toc-list .toc-item").nth(10).evaluate("item => item.classList.contains('is-current')"))
1781
- context.close()
1782
 
1783
- def test_foliate_toc_retains_groups_and_chapter_buttons_skip_them(self):
1784
- with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive:
1785
- files = {name: archive.read(name) for name in archive.namelist()}
1786
- files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace(
1787
- b'<ol><li><a', '<ol><li><span>第一卷</span><ol><li><a'.encode()
1788
- ).replace(b'</li><li><a', '</li></ol></li><li><span>第二卷</span><ol><li><a'.encode()).replace(
1789
- b'</ol></nav>', b'</ol></li></ol></nav>')
1790
- self.page.unroute('**/api/reader-content**')
1791
- self.page.route('**/api/reader-content**', lambda route: route.fulfill(
1792
- status=200, content_type='application/epub+zip', body=zip_bytes(files)))
1793
- source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/groups.epub'
1794
- self.page.goto(f'{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe="")}&ext=epub', wait_until='domcontentloaded')
1795
- self.page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 4")
1796
- open_reader_panel(self.page)
1797
- self.assertEqual(self.page.locator('#toc-list [role=heading]').all_text_contents(), ['第一卷', '第二卷'])
1798
- self.assertEqual(self.page.locator('#toc-list [role=link]').all_text_contents(), ['第一章', '第二章'])
1799
- self.assertEqual(self.page.locator('#toc-list .toc-group [tabindex]').count(), 0)
1800
- self.page.locator('#toc-list [role=link]').first.click()
1801
- self.page.wait_for_function("() => document.querySelector('[data-toc-index=\"1\"]').classList.contains('is-current')")
1802
- self.page.wait_for_function("() => document.querySelector('#history').getAttribute('aria-expanded') === 'false'")
1803
- open_reader_panel(self.page)
1804
- self.page.locator('.reader-chapter-next').click()
1805
- self.page.wait_for_function("() => document.querySelector('[data-toc-index=\"3\"]').classList.contains('is-current')")
1806
- self.assertAlmostEqual(self.page.locator('#two').evaluate(
1807
- "e => e.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=2)
1808
-
1809
- def test_chm_rebuilt_spine_ignores_previous_asset_positions(self):
1810
- with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive:
1811
- files = {name: archive.read(name) for name in archive.namelist()}
1812
- files['OEBPS/content.opf'] = files['OEBPS/content.opf'].replace(
1813
- b'<itemref idref="one"/><itemref idref="two"/>', b'<itemref idref="two"/><itemref idref="one"/>')
1814
- root = 'objects/aa/' + 'a' * 64 + '/'
1815
- files['META-INF/reader-chm.json'] = json.dumps({'version': 1,
1816
- 'previous_path': root + 'calibre-chm-epub-v2/document.epub',
1817
- 'previous_sections': ['OEBPS/nav.xhtml', 'OEBPS/chapter-1.xhtml', 'OEBPS/chapter-2.xhtml']})
1818
- self.page.route('**/static/reader/core/reader-store.js', lambda route: route.fulfill(
1819
- status=200, content_type='text/javascript', body=STORE_SCRIPT.replace(
1820
- 'get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300))',
1821
- "get: url => Promise.resolve(url.includes('calibre-chm-epub-v2') ? {foliateSection:2, foliateOffset:100, foliateTocIndex:1} : null)")))
1822
- self.page.route('**/api/reader-content**', lambda route: route.fulfill(
1823
- status=200, content_type='application/epub+zip', body=zip_bytes(files)))
1824
- source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/manual-chm-navigation-v2/document.epub'
1825
- self.page.goto(f'{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe="")}&ext=epub', wait_until='domcontentloaded')
1826
- self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
1827
- self.page.wait_for_function("() => window.__savedReaderProgress?.foliateSection === 0")
1828
- previous = source.replace('manual-chm-navigation-v2', 'calibre-chm-epub-v2')
1829
- self.page.evaluate("url => VoiceOfMLReaderStore.putBookmark({id:'old-chm-mark',url,foliateSection:1,foliateOffset:150,label:'Old chapter one',createdAt:1})", previous)
1830
- open_reader_panel(self.page)
1831
- self.page.locator('#bookmarks-tab').click()
1832
- self.assertEqual(self.page.locator('#bookmarks-list .panel-item-main', has_text='Old chapter one').count(), 0)
1833
- self.assertIn('manual-chm-navigation-v2', urllib.parse.unquote(self.page.url))
1834
 
1835
- def test_foliate_scroll_updates_toc_on_animation_frame(self):
1836
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1837
- page = context.new_page()
1838
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1839
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1840
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/scroll-toc.epub"
1841
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=ScrollToc", wait_until="domcontentloaded")
1842
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1843
- open_reader_panel(page)
1844
- page.locator("#toc-list .panel-item-main").nth(9).click()
1845
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1846
- page.locator('.foliate-continuous article[data-section="11"] #chapter-11').wait_for(state='attached')
1847
- 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')); }""")
1848
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(11)').classList.contains('is-current')", timeout=1000)
1849
- context.close()
1850
 
1851
- def test_foliate_resize_keeps_current_text_anchor(self):
1852
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1853
- page = context.new_page()
1854
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1855
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1856
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/scroll-anchor.epub"
1857
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Anchor", wait_until="domcontentloaded")
1858
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1859
- open_reader_panel(page)
1860
- page.locator("#toc-list .panel-item-main").nth(9).click()
1861
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1862
- page.evaluate("""() => { const viewport = document.querySelector('#viewport'); viewport.style.overflowAnchor = 'none'; viewport.dispatchEvent(new Event('scroll')); }""")
1863
- page.wait_for_timeout(50)
1864
- before = page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top")
1865
- 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); }""")
1866
- 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)
1867
- context.close()
1868
 
1869
- def test_foliate_virtualizes_distant_sections_and_reloads_them(self):
1870
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1871
- page = context.new_page()
1872
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1873
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1874
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/virtual.epub"
1875
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Virtual", wait_until="domcontentloaded")
1876
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1877
- for index in [1, 3, 5, 7, 9, 11, 13]:
1878
- page.evaluate("i => document.querySelectorAll('#toc-list .panel-item-main')[i].click()", index)
1879
- page.wait_for_function("i => document.querySelectorAll('#toc-list .toc-item')[i].classList.contains('is-current')", arg=index)
1880
- page.wait_for_timeout(100)
1881
- self.assertLessEqual(page.locator(".foliate-continuous article[data-section]:not(.foliate-section-placeholder)").count(), 12)
1882
- self.assertGreater(page.locator(".foliate-section-placeholder").count(), 0)
1883
- sections = page.locator(".foliate-continuous article[data-section]").evaluate_all("items => items.map(item => Number(item.dataset.section))")
1884
- self.assertEqual(sections, sorted(set(sections)))
1885
- page.evaluate("() => document.querySelectorAll('#toc-list .panel-item-main')[1].click()")
1886
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(2)').classList.contains('is-current')")
1887
- page.locator(".foliate-continuous article[data-section]:not(.foliate-section-placeholder) #chapter-2").wait_for(timeout=5000)
1888
- page.wait_for_function("() => document.querySelectorAll('.foliate-continuous article[data-section]:not(.foliate-section-placeholder)').length <= 12")
1889
- context.close()
1890
 
1891
- def test_large_foliate_toc_keeps_a_bounded_dom_window(self):
1892
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1893
- page = context.new_page()
1894
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1895
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters(600)))
1896
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large-toc.epub"
1897
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=LargeToc", wait_until="domcontentloaded")
1898
- page.wait_for_function("() => document.querySelector('#toc-list')?.classList.contains('toc-list-virtualized')")
1899
- open_reader_panel(page)
1900
- self.assertLess(page.locator("#toc-list .toc-item").count(), 100)
1901
- page.evaluate("""() => { const panel = document.querySelector('#toc-panel'); panel.scrollTop = 20000; panel.dispatchEvent(new Event('scroll')); }""")
1902
- page.wait_for_function("() => [...document.querySelectorAll('#toc-list .toc-item')].some(row => row.textContent.includes('章节 501'))")
1903
- self.assertLess(page.locator("#toc-list .toc-item").count(), 100)
1904
- page.locator('#toc-list [data-toc-index="500"] .panel-item-main').click()
1905
- page.wait_for_function("() => document.querySelector('#toc-list [data-toc-index=\"500\"]')?.classList.contains('is-current')")
1906
- self.assertEqual(page.locator('#toc-list .is-current').get_attribute('data-toc-index'), '500')
1907
- context.close()
1908
 
1909
- def test_foliate_full_search_uses_continuous_reader_navigation(self):
1910
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1911
- page = context.new_page()
1912
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1913
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1914
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/search.epub"
1915
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Search", wait_until="domcontentloaded")
1916
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1917
- open_reader_panel(page)
1918
- page.locator("#full-search-toggle").click()
1919
- page.locator("#full-search-input").fill("正文 10")
1920
- page.locator("#full-search-results .full-search-result").first.wait_for(timeout=10000)
1921
- page.locator("#full-search-results .full-search-result").first.click()
1922
- page.locator("#chapter-10").wait_for(timeout=5000)
1923
- page.locator(".foliate-continuous .full-search-highlight").wait_for(timeout=5000)
1924
- page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')")
1925
- 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; }"))
1926
- context.close()
1927
 
1928
- def test_foliate_bookmark_restores_continuous_section_position(self):
1929
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1930
- page = context.new_page()
1931
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1932
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1933
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/bookmark.epub"
1934
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Bookmark", wait_until="domcontentloaded")
1935
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1936
- open_reader_panel(page)
1937
- page.locator("#toc-list .panel-item-main").nth(9).click()
1938
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1939
- page.locator("#bookmark-ribbon").click()
1940
- page.locator("#bookmark-add").click()
1941
- page.wait_for_function("() => window.__readerBookmarks.length === 1")
1942
- bookmark = page.evaluate("window.__readerBookmarks[0]")
1943
- self.assertEqual(bookmark.get("foliateSection"), 10)
1944
- page.locator("#viewport").evaluate("element => { element.scrollTop = 0; element.dispatchEvent(new Event('scroll')); }")
1945
- open_reader_panel(page)
1946
- page.locator("#bookmarks-tab").click()
1947
- page.locator("#bookmarks-list .panel-item-main").click()
1948
- page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')")
1949
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1950
- self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3)
1951
- context.close()
1952
 
1953
- def test_foliate_progress_slider_uses_continuous_viewport(self):
1954
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1955
- page = context.new_page()
1956
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1957
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1958
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/progress.epub"
1959
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Progress", wait_until="domcontentloaded")
1960
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1961
- open_reader_panel(page)
1962
- page.locator("#toc-list .panel-item-main").nth(3).click()
1963
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(4)').classList.contains('is-current')")
1964
- open_reader_panel(page)
1965
- page.locator(".reader-progress-range").dispatch_event("pointerdown")
1966
- # Seek inside section 12, away from its fractional-pixel top boundary.
1967
- page.locator(".reader-progress-range").fill("81")
1968
- page.locator(".reader-progress-range").dispatch_event("pointerup")
1969
- 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; }")
1970
- self.assertAlmostEqual(float(page.locator(".reader-progress-percent").text_content().rstrip("%")), 81, delta=7)
1971
- page.locator('.foliate-section-placeholder').first.evaluate("node => node.style.setProperty('--foliate-placeholder-height', `${node.getBoundingClientRect().height + 600}px`)")
1972
- page.locator(".reader-progress-undo").click()
1973
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(4)').classList.contains('is-current')")
1974
- self.assertAlmostEqual(page.locator("#chapter-4").evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3)
1975
- self.assertTrue(page.locator(".reader-progress-undo").is_hidden())
1976
- page.wait_for_function("() => window.__savedReaderProgress?.foliateSection === 4")
1977
- context.close()
1978
 
1979
- def test_foliate_history_saves_structured_section_position(self):
1980
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1981
- page = context.new_page()
1982
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1983
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
1984
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/history.epub"
1985
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=History", wait_until="domcontentloaded")
1986
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
1987
- open_reader_panel(page)
1988
- page.locator("#toc-list .panel-item-main").nth(9).click()
1989
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)').classList.contains('is-current')")
1990
- page.evaluate("window.dispatchEvent(new Event('pagehide'))")
1991
- page.wait_for_function("() => window.__savedReaderProgress && window.__savedReaderProgress.foliateSection === 10")
1992
- self.assertEqual(page.evaluate("window.__savedReaderProgress.foliateTocIndex"), 9)
1993
- context.close()
1994
 
1995
- def test_foliate_history_restores_structured_section_position(self):
1996
- context = self.browser.new_context(viewport={"width": 390, "height": 844})
1997
- page = context.new_page()
1998
- restored_store = STORE_SCRIPT.replace("get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),", "get: () => Promise.resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9, zoom: 1}),")
1999
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=restored_store))
2000
- page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/epub+zip", body=epub_with_many_chapters()))
2001
- source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/restore.epub"
2002
- page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Restore", wait_until="domcontentloaded")
2003
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(10)')?.classList.contains('is-current')", timeout=10000)
2004
- self.assertAlmostEqual(page.locator("#chapter-10").evaluate("element => element.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3)
2005
- delayed_store = restored_store.replace(
2006
- "get: () => Promise.resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9, zoom: 1}),",
2007
- "get: () => new Promise(resolve => { window.__releaseHistory = () => resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9, zoom: 1}); }),",
2008
- )
2009
- page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=delayed_store))
2010
- page.reload(wait_until="domcontentloaded")
2011
- page.wait_for_function("() => document.querySelectorAll('#toc-list .toc-item').length === 14")
2012
- open_reader_panel(page)
2013
- page.locator("#toc-list .panel-item-main").nth(1).click()
2014
- page.wait_for_function("() => document.querySelector('#toc-list .toc-item:nth-child(2)').classList.contains('is-current')")
2015
- page.evaluate("window.__releaseHistory()")
2016
- page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
2017
- page.wait_for_function("() => window.__savedReaderProgress?.foliateSection === 2")
2018
- self.assertAlmostEqual(page.locator("#chapter-2").evaluate("node => node.getBoundingClientRect().top - document.querySelector('#viewport').getBoundingClientRect().top"), 8, delta=3)
2019
- context.close()
2020
 
2021
  def test_reader_store_preserves_old_history_and_keeps_current_bookmarks(self):
2022
  context = self.browser.new_context(viewport={"width": 390, "height": 844})
 
1558
  self.assertIn("第二章", second.inner_text())
1559
  self.assertEqual(unexpected_requests, [])
1560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1565
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1572
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1575
 
1576
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1577
 
1578
  def test_reader_store_preserves_old_history_and_keeps_current_bookmarks(self):
1579
  context = self.browser.new_context(viewport={"width": 390, "height": 844})
tests/performance/test_reader_toc_latency.py CHANGED
@@ -1,25 +1,54 @@
1
- """Focused native EPUB TOC demand acceptance, using the shared two-site server."""
2
  import unittest
3
- from urllib.parse import urlencode
4
 
5
  from tests.reader.browser import test_reader_pdf_followup as support
6
- from tests.performance.test_reader_performance import epub_with_many_chapters
7
 
8
 
9
  class ReaderTocLatencyTests(unittest.TestCase):
10
  setUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__)
11
  setUp = support.PdfFollowupTests.setUp
12
 
13
- def open_toc_book(self):
14
- self.page.route('**/api/reader-content**',lambda route:route.fulfill(
15
- content_type='application/epub+zip',body=epub_with_many_chapters(),
16
- headers={'Access-Control-Allow-Origin':'*'}))
17
- self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(
18
- url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc-hint.epub',ext='epub')))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
20
  self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
21
  self.page.wait_for_function("()=>document.querySelector('#history-panel').classList.contains('is-open')", timeout=2500)
22
 
 
 
 
 
 
 
 
 
 
23
  def expose_toc(self):
24
  def instrument(route):
25
  response = route.fetch()
@@ -171,51 +200,44 @@ class ReaderTocLatencyTests(unittest.TestCase):
171
  self.assertTrue(self.page.locator('#history-panel').evaluate('node=>node.hidden'))
172
 
173
  def test_unrelated_text_selection_does_not_disable_sidebar_navigation(self):
174
- self.page.route('**/api/reader-content**',lambda route:route.fulfill(
175
- content_type='application/epub+zip',body=epub_with_many_chapters(),
176
- headers={'Access-Control-Allow-Origin':'*'}))
177
- self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(
178
- url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc-selection.epub',ext='epub')))
179
- self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
180
- for index,number in [(9,10),(4,5)]:
181
- self.page.evaluate('''index=>{
182
- const range=document.createRange();range.selectNodeContents(document.querySelector('#title'));
183
- getSelection().removeAllRanges();getSelection().addRange(range);
184
- document.querySelectorAll('#toc-list .panel-item-main')[index].click();
185
- }''',index)
186
- self.page.wait_for_function('''number=>{
187
- const a=document.querySelector('article[data-section="'+number+'"]'),target=a?.shadowRoot?.querySelector('#chapter-'+number);
188
- return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3;
189
- }''',arg=number,timeout=1500)
190
 
191
  def test_sidebar_and_book_links_do_not_wait_for_unrelated_prefetch(self):
192
- self.page.route('**/api/reader-content**',lambda route:route.fulfill(
193
- content_type='application/epub+zip',body=epub_with_many_chapters(),
194
- headers={'Access-Control-Allow-Origin':'*'}))
195
- self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(
196
- url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/toc-latency.epub',ext='epub')))
197
- self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
198
- self.page.evaluate('''()=>{
199
- const sections=document.querySelector('foliate-view').book.sections.filter(s=>s.linear!=='no');
200
- for(const index of [9,11]){const original=sections[index].createDocument.bind(sections[index]);
201
- sections[index].createDocument=()=>new Promise(resolve=>{
202
- (window.__heldNeighbors||=[]).push(()=>original().then(resolve));});}
203
- document.querySelectorAll('#toc-list .panel-item-main')[9].click();
204
- }''')
205
- self.page.wait_for_function('''()=>{
206
- const a=document.querySelector('article[data-section="10"]'),target=a?.shadowRoot?.querySelector('#chapter-10');
207
- return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3;
208
- }''',timeout=1500)
209
- self.page.evaluate('''()=>{
210
- const root=document.querySelector('article[data-section="10"]').shadowRoot;
211
- const link=document.createElement('a');link.href='chapter-8.xhtml#chapter-8';link.textContent='Book contents';
212
- root.querySelector('#chapter-10').append(link);link.click();
213
- }''')
214
- self.page.wait_for_function('''()=>{
215
- const a=document.querySelector('article[data-section="8"]'),target=a?.shadowRoot?.querySelector('#chapter-8');
216
- return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3;
217
- }''',timeout=1500)
218
- self.page.evaluate('()=>{for(const release of window.__heldNeighbors||[])release();}')
219
  self.page.wait_for_timeout(250)
220
  self.assertLess(abs(self.page.locator('#chapter-8').evaluate(
221
- "e=>e.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8")),3)
 
1
+ """TOC UI and chapter-bundle navigation latency, using the shared two-site server."""
2
  import unittest
3
+ from urllib.parse import parse_qs, urlencode, urlsplit
4
 
5
  from tests.reader.browser import test_reader_pdf_followup as support
6
+ from tests.reader.browser.test_reader_toc_navigation import chapter_body, chapter_manifest
7
 
8
 
9
  class ReaderTocLatencyTests(unittest.TestCase):
10
  setUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__)
11
  setUp = support.PdfFollowupTests.setUp
12
 
13
+ def open_toc_book(self, held_chapters=None):
14
+ manifest = chapter_manifest(14)
15
+ for entry in manifest['toc']:
16
+ entry['fragment'] = f"chapter-{entry['chapter']}"
17
+
18
+ def resource(route):
19
+ path = parse_qs(urlsplit(route.request.url).query)['path'][0]
20
+ filename = path.rsplit('/', 1)[-1]
21
+ if filename == 'chapter-manifest.json':
22
+ route.fulfill(json=manifest)
23
+ return
24
+ index = int(filename.removeprefix('chapter-').removesuffix('.xhtml'))
25
+ body = chapter_body(index)
26
+ if index == 10:
27
+ body = body.replace('</h1>', '</h1><p><a href="chapter-0008.xhtml#chapter-8">Book contents</a></p>', 1)
28
+ if held_chapters is not None and index in held_chapters:
29
+ held_chapters[index].append((route, body))
30
+ else:
31
+ route.fulfill(content_type='text/html', body=body)
32
+
33
+ self.page.route('**/api/reader-bucket-resource**', resource)
34
+ source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/'
35
+ + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')
36
+ self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' +
37
+ urlencode(dict(url=source, ext='epub-chapters')),
38
+ wait_until='domcontentloaded')
39
  self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
40
  self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
41
  self.page.wait_for_function("()=>document.querySelector('#history-panel').classList.contains('is-open')", timeout=2500)
42
 
43
+ def toc_link(self, chapter):
44
+ return self.page.locator(f'#toc-list [data-toc-index="{chapter - 1}"] .panel-item-main')
45
+
46
+ def wait_for_chapter_landing(self, chapter):
47
+ self.page.wait_for_function('''chapter=>{
48
+ const target=document.querySelector(`.reader-epub-chapter[data-chapter="${chapter}"] #chapter-${chapter}`);
49
+ return target && Math.abs(target.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top)<3;
50
+ }''', arg=chapter, timeout=1500)
51
+
52
  def expose_toc(self):
53
  def instrument(route):
54
  response = route.fetch()
 
200
  self.assertTrue(self.page.locator('#history-panel').evaluate('node=>node.hidden'))
201
 
202
  def test_unrelated_text_selection_does_not_disable_sidebar_navigation(self):
203
+ self.open_toc_book()
204
+ for current, chapter in ((1, 10), (10, 5)):
205
+ if self.page.locator('#history').get_attribute('aria-expanded') != 'true':
206
+ self.page.locator('#history').click()
207
+ selected = self.toc_link(chapter).evaluate('''(link, current)=>{
208
+ const range=document.createRange();
209
+ range.selectNodeContents(document.querySelector(`#chapter-${current}`));
210
+ const selection=getSelection();selection.removeAllRanges();selection.addRange(range);
211
+ const selected=selection.toString();
212
+ link.click();
213
+ return selected;
214
+ }''', current)
215
+ self.assertTrue(selected)
216
+ self.wait_for_chapter_landing(chapter)
 
 
217
 
218
  def test_sidebar_and_book_links_do_not_wait_for_unrelated_prefetch(self):
219
+ # Stall the opening prefetch, then the neighbors of the sidebar destination.
220
+ held = {chapter: [] for chapter in (2, 3, 9, 11)}
221
+ with (
222
+ self.page.expect_request(lambda request: request.url.endswith('chapter-0002.xhtml'), timeout=1500),
223
+ self.page.expect_request(lambda request: request.url.endswith('chapter-0003.xhtml'), timeout=1500),
224
+ ):
225
+ self.open_toc_book(held)
226
+ with (
227
+ self.page.expect_request(lambda request: request.url.endswith('chapter-0009.xhtml'), timeout=1500),
228
+ self.page.expect_request(lambda request: request.url.endswith('chapter-0011.xhtml'), timeout=1500),
229
+ ):
230
+ self.toc_link(10).click()
231
+ self.wait_for_chapter_landing(10)
232
+ self.page.get_by_role('link', name='Book contents', exact=True).click()
233
+ self.wait_for_chapter_landing(8)
234
+
235
+ self.assertTrue(all(held.values()), 'both jumps must run with chapter responses withheld')
236
+ responses = [response for chapter in held.values() for response in chapter]
237
+ held.clear()
238
+ for route, body in responses:
239
+ route.fulfill(content_type='text/html', body=body)
240
+ self.page.locator('.reader-epub-chapter[data-chapter="9"]').wait_for(state='attached', timeout=1500)
 
 
 
 
 
241
  self.page.wait_for_timeout(250)
242
  self.assertLess(abs(self.page.locator('#chapter-8').evaluate(
243
+ "e=>e.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top")), 3)
tests/reader/browser/test_reader_ebook_flow.py CHANGED
@@ -1,11 +1,7 @@
1
- """Shared ebook loading/navigation regressions; actual EPUB engine, bounded fixtures."""
2
- import io
3
- import json
4
  import unittest
5
- import zipfile
6
  from urllib.parse import urlencode, unquote
7
  from tests.reader.browser import test_reader_pdf_followup as support
8
- from tests.performance.test_reader_performance import epub_with_many_chapters
9
 
10
 
11
  class EbookFlowTests(unittest.TestCase):
@@ -53,105 +49,16 @@ class EbookFlowTests(unittest.TestCase):
53
  self.assertEqual(self.page.locator('.reader-error').count(), 0)
54
 
55
  def expose(self):
56
- def instrument_foliate(route):
57
- response = route.fetch()
58
- needle = 'readerContext.foliateSectionLoader.refresh = refresh;'
59
- script = response.text()
60
- self.assertIn(needle, script)
61
- route.fulfill(response=response, body=script.replace(needle,
62
- needle + ' window.__nativeStats=()=>({active:scheduler.activeCount,pending:scheduler.pendingCount});'))
63
- self.page.route('**/static/reader/formats/reader-foliate-format.mjs*', instrument_foliate)
64
  def instrument(route):
65
  response = route.fetch()
66
- script=response.text()
67
- route.fulfill(response=response, body=script+'''
68
- window.__ebook={restore:restoreFoliateBookmarkPosition,capture:captureFoliateBookmarkPosition,
69
- captureChapter:captureChapterPosition,seek:seekFoliateProgress,
70
- begin:beginReaderNavigation,anchor:foliateScrollAnchors,
71
- load:i=>foliateSectionLoader(i),jump:i=>navigateTocEntry(i-1),
72
  chapter:i=>navigationState.tocEntries[i-1].activate(beginReaderNavigation()),
73
  progress:seekProgress,seekTask:()=>epubSeekPromise,
74
- percent:readerProgressPercent,restoreProgress:restoreProgressState,save:saveProgress,
75
- search:fullSearchFoliateMatches,searchGo:navigateFoliateSearchResult,
76
- searchGeneration:()=>readerRuntime.currentGeneration('search'),
77
- toc:activateFoliateTocEntry};
78
  ''')
79
  self.page.route('**/static/reader.js*', instrument)
80
 
81
- def native(self, short=False, image=False):
82
- with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters())) as archive:
83
- files={name:archive.read(name) for name in archive.namelist()}
84
- for name in files:
85
- if name.endswith('.xhtml'):
86
- text=files[name].decode()
87
- if short:text=text.replace('height:1200px','height:20px')
88
- if image:text=text.replace('</body>','<img src="slow.png" width="100" height="100"/></body>')
89
- files[name]=text.encode()
90
- stream=io.BytesIO()
91
- with zipfile.ZipFile(stream,'w',zipfile.ZIP_DEFLATED) as archive:
92
- for name,body in files.items():archive.writestr(name,body)
93
- self.page.route('**/api/reader-content**',lambda route:route.fulfill(content_type='application/epub+zip',body=stream.getvalue(),headers={'Access-Control-Allow-Origin':'*'}))
94
- self.expose()
95
- self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/flow.epub',ext='epub')),wait_until='domcontentloaded')
96
-
97
- def test_native_supplement_navigation_bookmark_and_resources(self):
98
- with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters(count=2))) as archive:
99
- files = {name: archive.read(name) for name in archive.namelist()}
100
- files['OEBPS/content.opf'] = files['OEBPS/content.opf'].replace(
101
- b'</manifest>', b'<item id="extra" href="extra.xhtml" media-type="application/xhtml+xml"/></manifest>'
102
- ).replace(b'</spine>', b'<itemref idref="extra" linear="no"/></spine>')
103
- files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace(
104
- b'</ol>', b'<li><a href="extra.xhtml#note">Supplement</a></li></ol>')
105
- files['OEBPS/chapter-1.xhtml'] = files['OEBPS/chapter-1.xhtml'].replace(
106
- b'</body>', b'<a id="note-link" href="extra.xhtml#note">Note link</a></body>')
107
- files['OEBPS/extra.xhtml'] = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
108
- <h1 id="note">Supplement target</h1><p>uniqueSupplementNeedle</p>
109
- <a id="back" href="chapter-1.xhtml#chapter-1">Back</a>
110
- <img id="safe" src="images/picture.png#view%20one"/>
111
- <img id="unsafe" src="https://evil.invalid/a.png#x"/>
112
- <img id="badfragment" src="images/picture.png#%XX"/>
113
- </body></html>'''
114
- packed = io.BytesIO()
115
- with zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED) as archive:
116
- for name, body in files.items(): archive.writestr(name, body)
117
- self.page.route('**/api/reader-content**', lambda route: route.fulfill(
118
- content_type='application/epub+zip', body=packed.getvalue(), headers={'Access-Control-Allow-Origin':'*'}))
119
- self.expose()
120
- self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(
121
- url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/supplement.epub', ext='epub')))
122
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
123
- self.page.get_by_role('link', name='Supplement', exact=True).wait_for()
124
- self.assertEqual(self.page.locator('article[data-supplement]').count(), 0)
125
- self.page.get_by_role('link', name='Supplement', exact=True).click()
126
- extra = self.page.locator('article[data-supplement]')
127
- extra.wait_for()
128
- self.assertEqual(extra.locator('#note').text_content(), 'Supplement target')
129
- self.assertIn('path=OEBPS%2Fimages%2Fpicture.png#view%20one', extra.locator('#safe').get_attribute('src'))
130
- self.assertIsNone(extra.locator('#unsafe').get_attribute('src'))
131
- self.assertIsNone(extra.locator('#badfragment').get_attribute('src'))
132
- saved = self.page.evaluate('__ebook.capture()')
133
- self.assertLess(saved['foliateSection'], 0)
134
- extra.locator('#back').click()
135
- self.page.wait_for_function("()=>!document.querySelector('article[data-supplement]')")
136
- self.assertTrue(self.page.evaluate('p=>__ebook.restore(p,__ebook.begin())', saved))
137
- self.assertEqual(self.page.evaluate('__ebook.capture().foliateSection'), saved['foliateSection'])
138
- self.assertEqual(self.page.locator('article[data-supplement]').count(), 1)
139
- extra.locator('#back').click()
140
- self.page.wait_for_function("()=>!document.querySelector('article[data-supplement]')")
141
- result = self.page.evaluate("async()=> (await __ebook.search('uniqueSupplementNeedle',__ebook.searchGeneration()))[0]")
142
- self.assertIsNotNone(result)
143
- self.assertTrue(self.page.evaluate('r=>__ebook.searchGo(r,__ebook.begin())', result))
144
- self.assertEqual(self.page.locator('article[data-supplement] mark.full-search-highlight').count(), 1)
145
- self.assertTrue(self.page.evaluate("async()=>{const book=document.querySelector('foliate-view').book;"
146
- "const resolve=book.resolveHref.bind(book);book.resolveHref=async href=>{const t=await resolve('OEBPS/extra.xhtml#note');"
147
- "return t&&{...t,anchor:()=>{throw Error('bad anchor')}}};"
148
- "try{return await __ebook.toc({href:'extra.xhtml#%XX'},__ebook.begin());}"
149
- "finally{book.resolveHref=resolve}}"))
150
- self.page.locator('article[data-supplement] #back').click()
151
- self.page.wait_for_function("()=>!document.querySelector('article[data-supplement]')")
152
- self.page.locator('#note-link').click()
153
- self.page.locator('article[data-supplement] #note').wait_for()
154
-
155
  def test_ebook_prose_stays_in_paper_and_wide_blocks_scroll(self):
156
  body = '''<h1>Ebook layout</h1>
157
  <div id="fixed" style="width:720px;min-width:680px">
@@ -162,20 +69,12 @@ class EbookFlowTests(unittest.TestCase):
162
  <svg id="figure" xmlns="http://www.w3.org/2000/svg" width="900" height="100" viewBox="0 0 900 100"
163
  style="min-width:800px"><rect width="900" height="100" fill="blue"/></svg>
164
  <p id="after">正文仍可阅读</p>''' % ('unbroken' * 55, '0123456789 ' * 50)
165
- with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters(count=1))) as archive:
166
- files = {name:archive.read(name) for name in archive.namelist()}
167
- files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace(b'</body>', body.encode() + b'</body>')
168
- packed = io.BytesIO()
169
- with zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED) as archive:
170
- for name, data in files.items(): archive.writestr(name, data)
171
  source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/' + 'a'*64 + '/1234567890abcdef/chapter-manifest.json'
172
  manifest = {'version':1,'kind':'epub-chapters','chapters':[{'index':1,'path':'chapters/chapter-0001.xhtml','bytes':len(body.encode())}]}
173
- self.page.route('**/api/reader-content**', lambda route:route.fulfill(content_type='application/epub+zip',
174
- body=packed.getvalue(),headers={'Access-Control-Allow-Origin':'*'}))
175
  self.page.route('**/api/reader-bucket-resource**', lambda route:route.fulfill(json=manifest) if 'chapter-manifest' in route.request.url
176
  else route.fulfill(content_type='text/html', body=body,headers={'Access-Control-Allow-Origin':'*'}))
177
  self.page.set_viewport_size({'width':320,'height':750})
178
- for mode, url in [('epub','https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/mobile.epub'), ('epub-chapters',source)]:
179
  with self.subTest(mode=mode):
180
  self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url=url, ext=mode)))
181
  self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
@@ -206,6 +105,40 @@ class EbookFlowTests(unittest.TestCase):
206
  self.assertEqual(self.page.locator('#wide-table caption').text_content(),'Table caption')
207
  self.assertEqual(self.page.locator('#wide-pre').text_content(),'0123456789 ' * 50)
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  def test_ebook_first_content_does_not_import_pdf_hit_projection(self):
210
  requested = []
211
 
@@ -229,154 +162,9 @@ class EbookFlowTests(unittest.TestCase):
229
  heading = self.page.locator('.reader-epub-chapter h1')
230
  self.assertTrue(heading.is_visible())
231
  self.assertEqual(heading.text_content(), 'Visible converted chapter')
232
- self.page.route('**/api/reader-content**', lambda route: route.fulfill(
233
- content_type='application/epub+zip', body=epub_with_many_chapters(count=2),
234
- headers={'Access-Control-Allow-Origin': '*'}))
235
- self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' + urlencode(dict(
236
- url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/flow.epub', ext='epub')))
237
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
238
- self.assertTrue(self.page.locator('.reader-section-body').first.is_visible())
239
  self.assertEqual(requested, [])
240
 
241
- def test_native_first_text_does_not_wait_for_image_body(self):
242
- held=[]
243
- self.page.route('**/api/reader-resource?**',lambda route:held.append(route))
244
- self.native(image=True)
245
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'",timeout=1200)
246
- self.assertTrue(self.page.locator('.reader-section-body').first.text_content())
247
- for route in held:route.abort()
248
-
249
- def test_native_first_chapter_reads_packaged_styles_in_parallel_and_keeps_cascade(self):
250
- with zipfile.ZipFile(io.BytesIO(epub_with_many_chapters(count=1))) as archive:
251
- files = {name: archive.read(name) for name in archive.namelist()}
252
- links = ''.join(f'<link rel="stylesheet" href="style-{i}.css"/>' for i in range(1, 5))
253
- sheets = ''.join(f'<item id="style-{i}" href="style-{i}.css" media-type="text/css"/>' for i in range(1, 5))
254
- files['OEBPS/content.opf'] = files['OEBPS/content.opf'].replace(b'</manifest>', sheets.encode() + b'</manifest>')
255
- files['OEBPS/nav.xhtml'] = files['OEBPS/nav.xhtml'].replace(b'<body>', f'<head>{links}</head><body><p id="cascade-probe">styles</p>'.encode())
256
- for i in range(1, 5):
257
- files[f'OEBPS/style-{i}.css'] = f'#cascade-probe {{letter-spacing:{i}px}}'.encode()
258
- body = io.BytesIO()
259
- with zipfile.ZipFile(body, 'w', zipfile.ZIP_DEFLATED) as archive:
260
- for name, data in files.items(): archive.writestr(name, data)
261
-
262
- self.page.add_init_script('''(() => {
263
- const fetchNative = window.fetch;
264
- const blobNative = Response.prototype.blob;
265
- window.__heldStyles = {};
266
- window.fetch = async (url, ...rest) => {
267
- const response = await fetchNative(url, ...rest);
268
- if (!String(url).startsWith('blob:') || !response.headers.get('content-type')?.includes('text/css')) return response;
269
- const blob = await blobNative.call(response);
270
- const marker = /letter-spacing:(\\d)px/.exec(await blob.text());
271
- if (!marker) return new Response(blob, {headers: response.headers});
272
- await new Promise(resolve => { window.__heldStyles[marker[1]] = resolve; });
273
- return new Response(blob, {headers: response.headers});
274
- };
275
- })()''')
276
- self.page.route('**/api/reader-content**', lambda route: route.fulfill(
277
- content_type='application/epub+zip', body=body.getvalue(), headers={'Access-Control-Allow-Origin':'*'}))
278
- self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(
279
- url='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/style-order.epub',ext='epub')),
280
- wait_until='domcontentloaded')
281
- self.page.wait_for_function("()=>['1','2','3'].every(key=>!!window.__heldStyles[key])")
282
- self.assertFalse(self.page.evaluate("()=>!!window.__heldStyles['4']"))
283
- # Finish out of order. The last sheet in document order must still win.
284
- self.page.evaluate("()=>window.__heldStyles['3']()")
285
- self.page.wait_for_function("()=>!!window.__heldStyles['4']")
286
- self.page.evaluate("()=>{for(const key of ['4','2','1']) window.__heldStyles[key]();}")
287
- self.page.wait_for_function('''()=>{
288
- const probe = document.querySelector('article[data-section="0"]')?.shadowRoot?.querySelector('#cascade-probe');
289
- return probe && getComputedStyle(probe).letterSpacing === '4px';
290
- }''')
291
-
292
- def test_native_restore_and_progress_do_not_wait_for_unrelated_neighbors(self):
293
- self.native()
294
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
295
- self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
296
- self.page.evaluate('''()=>{
297
- const sections=document.querySelector('foliate-view').book.sections.filter(s=>s.linear!=='no');
298
- for(const index of [9,11])sections[index].createDocument=()=>new Promise(()=>{});
299
- window.__result=null;
300
- __ebook.restore({foliateSection:10,foliateOffset:350}).then(value=>__result=value);
301
- }''')
302
- self.page.wait_for_function('()=>window.__result===true',timeout=1500)
303
- self.page.evaluate('''()=>{window.__seekDone=false;__ebook.seek(100*8.2/15,__ebook.begin()).then(()=>__seekDone=true);}''')
304
- self.page.wait_for_function('()=>window.__seekDone',timeout=1500)
305
-
306
- def test_native_position_reads_each_section_once_and_keeps_gap_fallback(self):
307
- self.native()
308
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
309
- result=self.page.evaluate('''()=>{
310
- const host=document.querySelector('.foliate-continuous'), orig=host.className;
311
- host.classList.remove('foliate-continuous');
312
- const stream=document.createElement('div');stream.className='foliate-continuous';document.body.append(stream);
313
- const top=document.querySelector('#viewport').getBoundingClientRect().top+8;
314
- const rows=[0,1,2].map(i=>{
315
- const row=document.createElement('article');row.dataset.section=i;stream.append(row);return row;
316
- });
317
- try {
318
- return [[[-50,-10],[20,30],[45,70]], [[-30,8],[15,25],[35,80]], [[-90,-70],[-65,-35],[-30,-5]]].map(rects=>{
319
- const reads=[0,0,0];
320
- rows.forEach((row,i)=>{row.getBoundingClientRect=()=>{reads[i]++;return {top:top+rects[i][0],bottom:top+rects[i][1]}}});
321
- return [__ebook.capture(),reads];
322
- });
323
- } finally {stream.remove();host.className=orig;}
324
- }''')
325
- self.assertEqual([(v['foliateSection'],v['foliateOffset'],reads) for v,reads in result],
326
- [(1,-20,[1,1,1]),(0,30,[1,0,0]),(2,30,[1,1,1])])
327
-
328
- def test_native_jump_keeps_previous_chapter_reachable_and_position_stable(self):
329
- self.native()
330
- self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
331
- self.page.evaluate('__ebook.jump(13)')
332
- self.page.wait_for_function("()=>!!document.querySelector('article[data-section=\"12\"]:not(.foliate-section-placeholder)')",timeout=1500)
333
- self.page.wait_for_timeout(200)
334
- self.assertLess(abs(self.page.locator('#chapter-13').evaluate('n=>n.getBoundingClientRect().top-document.querySelector("#viewport").getBoundingClientRect().top-8')),3)
335
- self.page.locator('#chapter-12').evaluate('n=>n.scrollIntoView()')
336
- self.page.wait_for_timeout(250)
337
- self.assertTrue(self.page.locator('#chapter-12').is_visible())
338
-
339
- def test_superseded_native_jump_releases_slots_and_ignores_late_section(self):
340
- self.native()
341
- self.page.wait_for_function("()=>document.querySelectorAll('#toc-list .toc-item').length===14")
342
- self.page.evaluate('''()=>{
343
- const sections=document.querySelector('foliate-view').book.sections.filter(s=>s.linear!=='no');
344
- const original=sections[10].createDocument.bind(sections[10]);
345
- sections[10].createDocument=()=>new Promise(resolve=>{window.__releaseOld=()=>original().then(resolve);});
346
- __ebook.jump(10);
347
- }''')
348
- self.page.wait_for_function('()=>!!window.__releaseOld')
349
- self.page.evaluate('__ebook.jump(13)')
350
- self.page.wait_for_function('''()=>{const n=document.querySelector('article[data-section="13"]')?.shadowRoot?.querySelector('#chapter-13');
351
- return n&&Math.abs(n.getBoundingClientRect().top-document.querySelector('#viewport').getBoundingClientRect().top-8)<3;}''',timeout=1500)
352
- self.assertLessEqual(self.page.evaluate('__nativeStats().active'),3)
353
- self.page.evaluate('__releaseOld()')
354
- self.page.wait_for_timeout(250)
355
- self.assertEqual(self.page.locator('article[data-section="10"]:not(.foliate-section-placeholder)').count(),0)
356
 
357
- def test_native_short_chapters_do_not_recursively_decode_whole_book(self):
358
- self.native(short=True)
359
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
360
- self.page.wait_for_timeout(400)
361
- self.assertLessEqual(self.page.locator('article[data-section]:not(.foliate-section-placeholder)').count(),9)
362
- self.assertLessEqual(self.page.evaluate('__nativeStats().active'),3)
363
- self.assertTrue(self.page.evaluate("!!document.querySelector('foliate-view').renderer"))
364
-
365
- def test_anchor_preserves_reading_line_when_previous_chapter_arrives_mid_scroll(self):
366
- self.native()
367
- self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
368
- result=self.page.evaluate('''()=>{
369
- const article=document.querySelector('article[data-section]');
370
- const root=article.shadowRoot.querySelector('.reader-section-body');
371
- root.innerHTML='<p style="height:800px">Before</p><p id="line">Reading line</p><p style="height:1600px">After</p>';
372
- const viewport=document.querySelector('#viewport'),line=root.querySelector('#line');
373
- viewport.scrollTop+=line.getBoundingClientRect().top-viewport.getBoundingClientRect().top-80;
374
- viewport.dispatchEvent(new WheelEvent('wheel',{deltaY:-1}));
375
- const before=line.getBoundingClientRect().top;
376
- __ebook.anchor.preserve(()=>{const previous=document.createElement('div');previous.style.height='700px';article.before(previous);});
377
- return {before,after:line.getBoundingClientRect().top};
378
- }''')
379
- self.assertAlmostEqual(result['before'],result['after'],delta=2)
380
 
381
  def test_converted_position_reads_each_chapter_once_and_preserves_identity(self):
382
  self.expose()
 
1
+ """Shared chapter ebook loading and navigation regressions."""
 
 
2
  import unittest
 
3
  from urllib.parse import urlencode, unquote
4
  from tests.reader.browser import test_reader_pdf_followup as support
 
5
 
6
 
7
  class EbookFlowTests(unittest.TestCase):
 
49
  self.assertEqual(self.page.locator('.reader-error').count(), 0)
50
 
51
  def expose(self):
 
 
 
 
 
 
 
 
52
  def instrument(route):
53
  response = route.fetch()
54
+ route.fulfill(response=response, body=response.text() + '''
55
+ window.__ebook={captureChapter:captureChapterPosition,
 
 
 
 
56
  chapter:i=>navigationState.tocEntries[i-1].activate(beginReaderNavigation()),
57
  progress:seekProgress,seekTask:()=>epubSeekPromise,
58
+ percent:readerProgressPercent,restoreProgress:restoreProgressState,save:saveProgress};
 
 
 
59
  ''')
60
  self.page.route('**/static/reader.js*', instrument)
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def test_ebook_prose_stays_in_paper_and_wide_blocks_scroll(self):
63
  body = '''<h1>Ebook layout</h1>
64
  <div id="fixed" style="width:720px;min-width:680px">
 
69
  <svg id="figure" xmlns="http://www.w3.org/2000/svg" width="900" height="100" viewBox="0 0 900 100"
70
  style="min-width:800px"><rect width="900" height="100" fill="blue"/></svg>
71
  <p id="after">正文仍可阅读</p>''' % ('unbroken' * 55, '0123456789 ' * 50)
 
 
 
 
 
 
72
  source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/' + 'a'*64 + '/1234567890abcdef/chapter-manifest.json'
73
  manifest = {'version':1,'kind':'epub-chapters','chapters':[{'index':1,'path':'chapters/chapter-0001.xhtml','bytes':len(body.encode())}]}
 
 
74
  self.page.route('**/api/reader-bucket-resource**', lambda route:route.fulfill(json=manifest) if 'chapter-manifest' in route.request.url
75
  else route.fulfill(content_type='text/html', body=body,headers={'Access-Control-Allow-Origin':'*'}))
76
  self.page.set_viewport_size({'width':320,'height':750})
77
+ for mode, url in [('epub-chapters',source)]:
78
  with self.subTest(mode=mode):
79
  self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url=url, ext=mode)))
80
  self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
 
105
  self.assertEqual(self.page.locator('#wide-table caption').text_content(),'Table caption')
106
  self.assertEqual(self.page.locator('#wide-pre').text_content(),'0123456789 ' * 50)
107
 
108
+ def test_chapter_xhtml_packaged_css_cascade(self):
109
+ source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/'
110
+ + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')
111
+ # The chapter renderer mounts the sanitized body, not the document head.
112
+ chapter = '''<?xml version="1.0" encoding="utf-8"?>
113
+ <html xmlns="http://www.w3.org/1999/xhtml"><head><title>CSS chapter</title></head>
114
+ <body><h1>CSS chapter</h1>
115
+ <style type="text/css">.book-text { color: rgb(10, 20, 30); letter-spacing: 2px; }
116
+ .book-text.special { color: rgb(40, 50, 60); }</style>
117
+ <style type="text/css">.book-text { color: rgb(70, 80, 90); word-spacing: 4px; }</style>
118
+ <p id="css-base" class="book-text">Base</p>
119
+ <p id="css-specific" class="book-text special">Specific</p>
120
+ <p id="css-inline" class="book-text special" style="color: rgb(100, 110, 120)">Inline</p>
121
+ </body></html>'''
122
+ manifest = {'version': 1, 'kind': 'epub-chapters', 'chapters': [
123
+ {'index': 1, 'path': 'chapters/chapter-0001.xhtml', 'bytes': len(chapter.encode())}]}
124
+ self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(json=manifest)
125
+ if 'chapter-manifest.json' in route.request.url else route.fulfill(
126
+ content_type='application/xhtml+xml', body=chapter, headers={'Access-Control-Allow-Origin': '*'}))
127
+ # Dark mode deliberately overrides book colors; test their cascade in light mode.
128
+ self.page.add_init_script("localStorage.setItem('theme', 'light')")
129
+ self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' + urlencode(
130
+ dict(url=source, ext='epub-chapters')))
131
+ self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready' && "
132
+ "document.documentElement.dataset.theme==='light'")
133
+ for element, color in [('css-base', 'rgb(70, 80, 90)'),
134
+ ('css-specific', 'rgb(40, 50, 60)'),
135
+ ('css-inline', 'rgb(100, 110, 120)')]:
136
+ with self.subTest(element=element):
137
+ node = self.page.locator('.reader-epub-chapter #' + element)
138
+ self.assertTrue(node.is_visible())
139
+ style = node.evaluate('n => {const s = getComputedStyle(n); return [s.color, s.letterSpacing, s.wordSpacing]}')
140
+ self.assertEqual(style, [color, '2px', '4px'])
141
+
142
  def test_ebook_first_content_does_not_import_pdf_hit_projection(self):
143
  requested = []
144
 
 
162
  heading = self.page.locator('.reader-epub-chapter h1')
163
  self.assertTrue(heading.is_visible())
164
  self.assertEqual(heading.text_content(), 'Visible converted chapter')
 
 
 
 
 
 
 
165
  self.assertEqual(requested, [])
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  def test_converted_position_reads_each_chapter_once_and_preserves_identity(self):
170
  self.expose()
tests/reader/browser/test_reader_format_pipeline.py CHANGED
@@ -3,7 +3,6 @@ import unittest
3
  from urllib.parse import urlencode
4
 
5
  from tests.reader.browser import test_reader_pdf_followup as support
6
- from tests.performance.test_reader_performance import epub_with_navigation
7
 
8
 
9
  class ReaderFormatPipelineTests(unittest.TestCase):
@@ -26,13 +25,12 @@ class ReaderFormatPipelineTests(unittest.TestCase):
26
  'marked':'window.marked={parse:t=>"<h1>Heading</h1><p>"+t+"</p>"};',
27
  'purify':'window.DOMPurify={addHook(){},removeHook(){},sanitize:(t,o)=>{if(!o?.RETURN_DOM_FRAGMENT)return t;const n=document.createElement("template");n.innerHTML=t;return n.content;}};',
28
  }
29
- documents=[('md',b'Markdown body','text/plain'),('html',b'<h1>Heading</h1><p>HTML body</p>','text/html'),
30
- ('epub',epub_with_navigation(),'application/epub+zip')]
31
  for ext,body,mime in documents:
32
  with self.subTest(format=ext):
33
  held=[]
34
  def engine(route):held.append(route)
35
- pattern='**/static/foliate-reader/view.js*' if ext=='epub' else '**/static/vendor/*.js'
36
  self.page.route(pattern,engine)
37
  self.page.route('**/api/reader-content**',lambda route,_request,body=body,mime=mime:route.fulfill(
38
  content_type=mime,body=body,headers={'Access-Control-Allow-Origin':'*'}))
@@ -43,13 +41,11 @@ class ReaderFormatPipelineTests(unittest.TestCase):
43
  self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'),'ready')
44
  self.page.unroute(pattern,engine)
45
  for route in held:
46
- if ext=='epub':route.continue_()
47
- else:
48
- name=next(key for key in engines if '/'+key+'.' in route.request.url)
49
- route.fulfill(content_type='text/javascript',body=engines[name])
50
  self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
51
  text=(self.page.frame_locator('.html-frame').locator('body').inner_text() if ext=='html' else
52
- self.page.locator('.reader-section-body').first.inner_text() if ext=='epub' else self.page.locator('#content').inner_text())
53
  self.assertTrue(text.strip())
54
 
55
  def test_swf_body_finishes_while_ruffle_is_held(self):
 
3
  from urllib.parse import urlencode
4
 
5
  from tests.reader.browser import test_reader_pdf_followup as support
 
6
 
7
 
8
  class ReaderFormatPipelineTests(unittest.TestCase):
 
25
  'marked':'window.marked={parse:t=>"<h1>Heading</h1><p>"+t+"</p>"};',
26
  'purify':'window.DOMPurify={addHook(){},removeHook(){},sanitize:(t,o)=>{if(!o?.RETURN_DOM_FRAGMENT)return t;const n=document.createElement("template");n.innerHTML=t;return n.content;}};',
27
  }
28
+ documents=[('md',b'Markdown body','text/plain'),('html',b'<h1>Heading</h1><p>HTML body</p>','text/html')]
 
29
  for ext,body,mime in documents:
30
  with self.subTest(format=ext):
31
  held=[]
32
  def engine(route):held.append(route)
33
+ pattern='**/static/vendor/*.js'
34
  self.page.route(pattern,engine)
35
  self.page.route('**/api/reader-content**',lambda route,_request,body=body,mime=mime:route.fulfill(
36
  content_type=mime,body=body,headers={'Access-Control-Allow-Origin':'*'}))
 
41
  self.assertNotEqual(self.page.locator('html').get_attribute('data-reader-phase'),'ready')
42
  self.page.unroute(pattern,engine)
43
  for route in held:
44
+ name=next(key for key in engines if '/'+key+'.' in route.request.url)
45
+ route.fulfill(content_type='text/javascript',body=engines[name])
 
 
46
  self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
47
  text=(self.page.frame_locator('.html-frame').locator('body').inner_text() if ext=='html' else
48
+ self.page.locator('#content').inner_text())
49
  self.assertTrue(text.strip())
50
 
51
  def test_swf_body_finishes_while_ruffle_is_held(self):
tests/reader/browser/test_reader_refactor.py CHANGED
@@ -9,7 +9,6 @@ import os
9
  import time
10
  import unittest
11
  import urllib.parse
12
- import zipfile
13
  import wave
14
 
15
  from tests.performance import test_reader_performance as support
@@ -144,8 +143,6 @@ class ReaderRefactorTest(unittest.TestCase):
144
 
145
  [chapter](chapter%20one.md)
146
 
147
- [book](book.epub)
148
-
149
  [fragment](chapter%20one.md#section)
150
 
151
  [self](index.md#local)
@@ -181,8 +178,6 @@ class ReaderRefactorTest(unittest.TestCase):
181
  route.fulfill(content_type='text/markdown', body=index)
182
  elif path.endswith('/books/chapter one.md'):
183
  route.fulfill(content_type='text/markdown', body=chapter)
184
- elif path.endswith('/books/book.epub'):
185
- route.fulfill(content_type='application/epub+zip', body=support.minimal_epub())
186
  else:
187
  route.fulfill(status=404, body='missing')
188
  self.page.route('**/api/reader-content**', serve)
@@ -194,13 +189,12 @@ class ReaderRefactorTest(unittest.TestCase):
194
  base = self.markdown_link_fixture()
195
  self.open(self.reader_url('md', name='books/index'))
196
  article = self.page.locator('.reader-markdown')
197
- for label, filename, ext in [('chapter', 'chapter one.md', 'md'), ('book', 'book.epub', 'epub')]:
198
- href = article.get_by_role('link', name=label, exact=True).get_attribute('href')
199
- target = urllib.parse.urlsplit(href)
200
- args = urllib.parse.parse_qs(target.query)
201
- self.assertTrue(target.path.endswith('/static/reader.html'))
202
- self.assertEqual(urllib.parse.unquote(args['url'][0]), base + filename)
203
- self.assertEqual(args['ext'][0], ext)
204
  self.assertEqual(article.get_by_role('link', name='local', exact=True).get_attribute('href'), '#local')
205
  self.assertEqual(article.get_by_role('link', name='self', exact=True).get_attribute('href'), '#local')
206
  self.assertEqual(article.get_by_role('link', name='outside').get_attribute('href'), 'https://example.org/article.md')
@@ -254,17 +248,6 @@ class ReaderRefactorTest(unittest.TestCase):
254
  href = self.page.locator('.reader-markdown').get_by_role('link', name='chapter', exact=True).get_attribute('href')
255
  self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(href).query)['url'][0]), base + 'chapter one.md')
256
 
257
- def test_markdown_epub_link_opens_book_without_downloading(self):
258
- base = self.markdown_link_fixture()
259
- self.open(self.reader_url('md', name='books/index'))
260
- downloads = []
261
- self.page.on('download', lambda download: downloads.append(download))
262
- self.page.locator('.reader-markdown').get_by_role('link', name='book', exact=True).click()
263
- self.page.wait_for_url('**/reader.html?*ext=epub*')
264
- self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
265
- self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(self.page.url).query)['url'][0]), base + 'book.epub')
266
- self.assertEqual(downloads, [])
267
-
268
  def test_markdown_dataset_link_in_search_overlay_uses_parent_navigation(self):
269
  self.markdown_link_fixture()
270
  reader = self.reader_url('md', name='books/index')
@@ -738,22 +721,6 @@ class ReaderRefactorTest(unittest.TestCase):
738
  self.assertEqual(self.page.evaluate('window.__imageWaitProbe()'),
739
  [[0, 1, 'eager'], [0, 0, 'eager'], [0, 0, 'eager'], 'AbortError', 0])
740
 
741
- def test_epub_lazy_image_loads_while_section_is_prepared_off_dom(self):
742
- with zipfile.ZipFile(io.BytesIO(support.minimal_epub())) as archive:
743
- files = {name: archive.read(name) for name in archive.namelist()}
744
- files['OEBPS/chapter.xhtml'] = files['OEBPS/chapter.xhtml'].replace(
745
- b'</body>', b'<img src="picture.webp" loading="lazy" alt="Chapter image" width="64" height="32"/></body>')
746
- files['OEBPS/picture.webp'] = support.IMAGE_FIXTURES['webp'][1]
747
- images = []
748
- self.page.route('**/api/reader-resource?**', lambda route: (
749
- images.append(route.request.url), route.fulfill(content_type='image/webp', body=files['OEBPS/picture.webp'])))
750
- self.serve(support.zip_bytes(files), 'application/epub+zip')
751
- self.open(self.reader_url('epub'))
752
- image = self.page.locator('article[data-section] img').first
753
- self.assertEqual(image.evaluate('node => node.loading'), 'eager')
754
- self.assertGreater(image.evaluate('node => node.naturalWidth'), 0)
755
- self.assertEqual(len(images), 1)
756
-
757
  def test_spreadsheet_cells_take_first_viewport_while_images_are_pending(self):
758
  # Delay only the post-frame image settlement. The sanitized HTML has
759
  # already loaded, so this distinguishes first paint from restore-ready.
@@ -901,25 +868,6 @@ class ReaderRefactorTest(unittest.TestCase):
901
  self.page.locator('.reader-epub-chapter[data-chapter="6"]').wait_for(state="attached")
902
  self.assertNotIn(1, requested)
903
 
904
- def test_saved_foliate_builds_target_section_first(self):
905
- store = support.STORE_SCRIPT.replace(
906
- "get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
907
- "get: () => Promise.resolve({foliateSection: 10, foliateOffset: 0, foliateTocIndex: 9}),",
908
- )
909
- self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(content_type="text/javascript", body=store))
910
- def instrument(route):
911
- response = route.fetch()
912
- script = response.text()
913
- marker = "async function createFoliateSection(section, index, signal, priority) {"
914
- self.assertEqual(script.count(marker), 1, "Foliate section instrumentation boundary changed")
915
- body = script.replace(marker, marker + " (window.__openedSections ||= []).push(index);")
916
- route.fulfill(response=response, body=body)
917
- self.page.route("**/static/reader/formats/reader-foliate-format.mjs*", instrument)
918
- self.serve(support.epub_with_many_chapters(), "application/epub+zip")
919
- self.open(self.reader_url("epub"))
920
- self.assertEqual(self.page.evaluate("window.__openedSections[0]"), 10)
921
- self.assertTrue(self.page.locator('.foliate-continuous article[data-section="10"]').is_visible())
922
-
923
  def test_djvu_recovers_ocr_text_and_searches_valid_index(self):
924
  state = install_native_djvu(self.page, self.origin, ocr=True, fail_page_once=True)
925
  self.open(state["url"])
@@ -1395,271 +1343,6 @@ class ReaderRefactorTest(unittest.TestCase):
1395
  self.assertEqual(self.page.locator("#full-search-page").input_value(), "3")
1396
  self.assertEqual(self.page.locator("#full-search-status").text_content(), "180 个结果")
1397
 
1398
- def test_pending_foliate_result_does_not_close_reopened_search(self):
1399
- self.serve(support.epub_with_many_chapters(3), "application/epub+zip")
1400
- self.open(self.reader_url("epub"))
1401
- self.search("正文")
1402
- self.page.evaluate("""() => {
1403
- const view = document.querySelector('foliate-view');
1404
- const original = view.resolveNavigation.bind(view);
1405
- view.resolveNavigation = cfi => new Promise(resolve => {
1406
- window.__releaseSearchNavigation = () => resolve(original(cfi));
1407
- });
1408
- }""")
1409
- self.page.locator(".full-search-result").first.click()
1410
- self.page.wait_for_function("() => !!window.__releaseSearchNavigation")
1411
- self.page.locator("#history").click()
1412
- self.page.locator("#history").click()
1413
- self.page.locator("#full-search-input").focus()
1414
- self.page.evaluate("window.__releaseSearchNavigation()")
1415
- self.page.locator(".foliate-continuous mark.full-search-highlight").first.wait_for()
1416
- self.assertTrue(self.page.locator("#full-search-input").is_visible())
1417
- self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.classList.contains('is-open')"))
1418
-
1419
- def test_unresolvable_foliate_result_keeps_search_open_for_retry(self):
1420
- self.serve(support.epub_with_many_chapters(3), "application/epub+zip")
1421
- self.open(self.reader_url("epub"))
1422
- self.search("正文")
1423
- self.page.evaluate("""() => {
1424
- const view = document.querySelector('foliate-view');
1425
- window.__resolveSearchResult = view.resolveNavigation.bind(view);
1426
- view.resolveNavigation = async () => null;
1427
- }""")
1428
- self.page.locator(".full-search-result").first.click()
1429
- self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '搜索结果定位失败,请重试'")
1430
- self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.classList.contains('is-open')"))
1431
- self.assertEqual(self.page.locator(".foliate-continuous mark.full-search-highlight").count(), 0)
1432
- self.page.evaluate("document.querySelector('foliate-view').resolveNavigation = window.__resolveSearchResult")
1433
- self.page.locator(".full-search-result").first.click()
1434
- self.page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')")
1435
- self.assertEqual(self.page.locator("#full-search-status").text_content(), "3 个结果")
1436
- self.assertEqual(self.page.locator(".foliate-continuous mark.full-search-highlight").count(), 1)
1437
-
1438
- def test_foliate_navigation_exception_reports_failure_and_retries(self):
1439
- self.serve(support.epub_with_many_chapters(3), "application/epub+zip")
1440
- self.open(self.reader_url("epub"))
1441
- self.search("正文")
1442
- self.page.evaluate("""() => {
1443
- const view = document.querySelector('foliate-view');
1444
- const original = view.resolveNavigation.bind(view);
1445
- view.resolveNavigation = async cfi => {
1446
- view.resolveNavigation = original;
1447
- throw new Error('temporary navigation failure');
1448
- };
1449
- }""")
1450
- self.page.locator(".full-search-result").first.click()
1451
- self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '搜索结果定位失败,请重试'")
1452
- self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.classList.contains('is-open')"))
1453
- self.page.locator(".full-search-result").first.click()
1454
- self.page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')")
1455
- self.assertEqual(self.page.locator("#full-search-status").text_content(), "3 个结果")
1456
-
1457
- def test_stale_foliate_fallback_cannot_highlight_after_navigation(self):
1458
- def hold_fallback(route):
1459
- response = route.fetch()
1460
- needle = ("const nodes = cached ? [] : await fullSearchTextNodes("
1461
- "root, generation, Infinity, null, collect, respectBlocks);")
1462
- script = response.text()
1463
- self.assertIn(needle, script)
1464
- script = script.replace(needle, """if (occurrence !== null && !window.__fallbackHeld) {
1465
- window.__fallbackHeld = true;
1466
- await new Promise(resolve => { window.__releaseFallback = resolve; });
1467
- } """ + needle)
1468
- route.fulfill(response=response, body=script)
1469
- def finish_fallback(route):
1470
- response = route.fetch()
1471
- route.fulfill(response=response, body=response.text().replace(
1472
- "target = matches[0]?.target;", "target = matches[0]?.target; window.__fallbackDone = true;"))
1473
- self.page.route("**/static/reader/search/reader-dom-search.mjs*", hold_fallback)
1474
- self.page.route("**/static/reader/search/reader-search-backends.mjs*", finish_fallback)
1475
- self.serve(support.epub_with_many_chapters(3), "application/epub+zip")
1476
- self.open(self.reader_url("epub"))
1477
- self.search("正文")
1478
- self.page.evaluate("""() => {
1479
- const view = document.querySelector('foliate-view');
1480
- const original = view.resolveNavigation.bind(view);
1481
- view.resolveNavigation = async cfi => ({ ...(await original(cfi)), anchor: null });
1482
- }""")
1483
- self.page.locator(".full-search-result").first.click()
1484
- self.page.wait_for_function("() => !!window.__releaseFallback")
1485
- self.page.evaluate("document.querySelector('#viewport').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))")
1486
- self.page.evaluate("window.__releaseFallback()")
1487
- self.page.wait_for_function("() => !!window.__fallbackDone")
1488
- self.assertEqual(self.page.locator(".foliate-continuous mark.full-search-highlight").count(), 0)
1489
-
1490
- def test_foliate_search_reuses_rows_and_bounds_visited_pages(self):
1491
- with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters(6))) as archive:
1492
- files = {name: archive.read(name) for name in archive.namelist()}
1493
- for number in range(1, 7):
1494
- files[f'OEBPS/chapter-{number}.xhtml'] = (
1495
- '<html xmlns="http://www.w3.org/1999/xhtml"><body>' +
1496
- ''.join(f'<p>needle {number}-{hit}</p>' for hit in range(100)) +
1497
- '</body></html>').encode()
1498
- self.serve(support.zip_bytes(files), "application/epub+zip")
1499
- self.open(self.reader_url("epub"))
1500
- self.page.evaluate("""() => {
1501
- window.__searchProbe = {rows: 0, calls: 0};
1502
- const view = document.querySelector('foliate-view'), search = view.search.bind(view);
1503
- view.search = (...args) => { __searchProbe.calls++; return search(...args); };
1504
- new MutationObserver(records => {
1505
- for (const record of records) __searchProbe.rows += record.addedNodes.length;
1506
- }).observe(document.querySelector('#full-search-results'), {childList: true});
1507
- }""")
1508
- self.search("needle")
1509
- self.assertEqual(self.page.locator("#full-search-status").text_content(), "600 个结果")
1510
- self.assertEqual(self.page.evaluate("__searchProbe.rows"), 50)
1511
-
1512
- def jump(number):
1513
- self.page.locator("#full-search-page").fill(str(number))
1514
- self.page.locator("#full-search-page").dispatch_event("change")
1515
- self.page.wait_for_function("rank => document.querySelector('.full-search-rank')?.textContent === rank",
1516
- arg=f"{(number - 1) * 50 + 1}.")
1517
- return self.page.locator(".full-search-result").all_text_contents()
1518
-
1519
- original = jump(2)
1520
- jump(3)
1521
- before = self.page.evaluate("__searchProbe.calls")
1522
- self.assertEqual(jump(2), original)
1523
- self.assertEqual(self.page.evaluate("__searchProbe.calls"), before)
1524
- for number in (4, 5, 6, 7):
1525
- jump(number)
1526
- before = self.page.evaluate("__searchProbe.calls")
1527
- self.assertEqual(jump(2), original)
1528
- self.assertGreater(self.page.evaluate("__searchProbe.calls"), before)
1529
- self.page.locator("#full-search-input").fill("absent")
1530
- self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '未找到正文匹配'")
1531
- self.page.locator("#full-search-input").fill("needle")
1532
- self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '600 个结果'")
1533
- before = self.page.evaluate("__searchProbe.calls")
1534
- self.assertEqual(jump(2), original)
1535
- self.assertGreater(self.page.evaluate("__searchProbe.calls"), before)
1536
-
1537
- def test_foliate_counting_materializes_only_requested_results(self):
1538
- for name, needle, probe in (
1539
- ("search.js", "const makeExcerpt = (strs, { startIndex, startOffset, endIndex, endOffset }) => {", "__excerptCalls"),
1540
- ("text-walker.js", "const range = document.createRange()", "__rangeCalls"),
1541
- ):
1542
- def instrument(route, _request, needle=needle, probe=probe):
1543
- response = route.fetch()
1544
- self.assertIn(needle, response.text())
1545
- route.fulfill(response=response, body=response.text().replace(needle,
1546
- needle + f"; window.{probe} = (window.{probe} || 0) + 1;"))
1547
- self.page.route(f"**/foliate-reader/{name}", instrument)
1548
- with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters(1))) as archive:
1549
- files = {name: archive.read(name) for name in archive.namelist()}
1550
- files['OEBPS/chapter-1.xhtml'] = (
1551
- '<html xmlns="http://www.w3.org/1999/xhtml"><body>' +
1552
- ''.join(f'<p>needle {hit}</p>' for hit in range(1000)) + '</body></html>'
1553
- ).encode()
1554
- self.serve(support.zip_bytes(files), "application/epub+zip")
1555
- self.open(self.reader_url("epub"))
1556
- self.page.evaluate("window.__excerptCalls = window.__rangeCalls = 0")
1557
- self.search("needle")
1558
- self.assertEqual(self.page.locator("#full-search-status").text_content(), "1000 个结果")
1559
- self.assertEqual(self.page.evaluate("[window.__excerptCalls, window.__rangeCalls]"), [50, 50])
1560
- self.page.locator("#full-search-page").fill("20")
1561
- self.page.locator("#full-search-page").dispatch_event("change")
1562
- self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '951.'")
1563
- self.assertEqual(self.page.evaluate("[window.__excerptCalls, window.__rangeCalls]"), [100, 100])
1564
- self.assertIn("999", self.page.locator(".full-search-result").last.text_content())
1565
- self.page.locator(".full-search-result").last.click()
1566
- self.page.wait_for_function("() => [...document.querySelectorAll('article[data-section]')].some(node => node.shadowRoot?.querySelector('mark')?.parentElement.textContent === 'needle 999')")
1567
-
1568
- def test_foliate_excerpt_preserves_all_inline_match_nodes(self):
1569
- self.serve("Text")
1570
- self.open(self.reader_url())
1571
- base = urllib.parse.urlsplit(self.reader_url()).path.rsplit('/', 1)[0]
1572
- result = self.page.evaluate("""async base => {
1573
- const {search} = await import(base + '/foliate-reader/search.js');
1574
- return ['variant', 'base'].map(sensitivity => {
1575
- const result = [...search(['before ne', 'e', 'dle after'], 'needle',
1576
- {sensitivity, granularity: 'grapheme'})][0];
1577
- return result.excerpt;
1578
- }).concat([...search(['ne', 'ed', 'ne'], 'needne',
1579
- {sensitivity: 'base', granularity: 'grapheme'})][0].excerpt);
1580
- }""", base)
1581
- self.assertEqual(result, [{"pre": "before ", "match": "needle", "post": " after"}] * 2 +
1582
- [{"pre": "", "match": "needne", "post": ""}])
1583
-
1584
- def test_foliate_many_hits_paginate_and_cancel(self):
1585
- with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters(3))) as archive:
1586
- files = {name: archive.read(name) for name in archive.namelist()}
1587
- for number in (1, 2, 3):
1588
- files[f'OEBPS/chapter-{number}.xhtml'] = (
1589
- '<html xmlns="http://www.w3.org/1999/xhtml"><body>' +
1590
- ''.join(f'<p>needle {number}-{hit}</p>' for hit in range(70)) +
1591
- '</body></html>'
1592
- ).encode()
1593
- self.serve(support.zip_bytes(files), "application/epub+zip")
1594
- self.open(self.reader_url("epub"))
1595
- self.search("needle")
1596
- self.assertEqual(self.page.locator("#full-search-status").text_content(), "210 个结果")
1597
- self.assertEqual(self.page.locator(".full-search-result").count(), 50)
1598
- self.assertTrue(self.page.locator("#full-search-cancel").is_hidden())
1599
- self.page.evaluate("""() => {
1600
- window.__cancelPagingChanges = [];
1601
- const cancel = document.querySelector('#full-search-cancel');
1602
- new MutationObserver(() => {
1603
- __cancelPagingChanges.push(cancel.hidden);
1604
- }).observe(document.querySelector('#full-search-cancel'), {
1605
- attributes: true, attributeFilter: ['hidden']
1606
- });
1607
- }""")
1608
- self.page.evaluate("""() => {
1609
- const status = document.querySelector('#full-search-status');
1610
- window.__pagingStatuses = [status.textContent];
1611
- window.__pagingObserver = new MutationObserver(records => {
1612
- for (const record of records) {
1613
- for (const node of record.removedNodes) window.__pagingStatuses.push(node.textContent);
1614
- }
1615
- window.__pagingStatuses.push(status.textContent);
1616
- });
1617
- window.__pagingObserver.observe(status, {childList: true});
1618
- const view = document.querySelector('foliate-view');
1619
- const original = view.search.bind(view);
1620
- view.search = async function* (options) {
1621
- if (options.index != null && !window.__heldResultPage) {
1622
- window.__heldResultPage = true;
1623
- await new Promise(resolve => { window.__releaseResultPage = resolve; });
1624
- }
1625
- yield* original(options);
1626
- };
1627
- }""")
1628
- self.page.locator("#full-search-page-next").click()
1629
- self.page.wait_for_function("() => !!window.__releaseResultPage")
1630
- self.assertTrue(self.page.locator("#full-search-cancel").is_hidden())
1631
- self.page.evaluate("window.__releaseResultPage()")
1632
- self.page.wait_for_function("() => document.querySelector('.full-search-rank')?.textContent === '51.'")
1633
- self.page.locator("#full-search-page").fill("3")
1634
- self.page.locator("#full-search-page").dispatch_event("change")
1635
- self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '3' && document.querySelector('.full-search-result .full-search-rank')?.textContent === '101.'")
1636
- self.assertIn("needle 2-30", self.page.locator(".full-search-result").first.text_content())
1637
- self.assertTrue(self.page.locator("#full-search-cancel").is_hidden())
1638
- self.assertNotIn(False, self.page.evaluate("__cancelPagingChanges"))
1639
- statuses = self.page.evaluate("() => { window.__pagingObserver.disconnect(); return window.__pagingStatuses; }")
1640
- self.assertEqual(set(statuses), {"210 个结果"})
1641
- self.page.locator(".full-search-result").first.click()
1642
- self.page.wait_for_function("() => !document.querySelector('#history-panel').classList.contains('is-open')")
1643
- self.page.locator("#history").click()
1644
- self.page.wait_for_function("() => document.querySelector('#history-panel').classList.contains('is-open') && !document.querySelector('#full-search-view').hidden")
1645
- self.assertEqual(self.page.locator("#full-search-page").input_value(), "3")
1646
- self.page.locator("#full-search-input").fill("missing")
1647
- self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '未找到正文匹配'")
1648
- self.page.evaluate("""() => {
1649
- const sections = document.querySelector('foliate-view').book.sections;
1650
- for (const section of sections) if (section.createDocument) {
1651
- const original = section.createDocument.bind(section);
1652
- section.createDocument = async () => { await new Promise(resolve => setTimeout(resolve, 200)); return original(); };
1653
- }
1654
- }""")
1655
- self.page.locator("#full-search-input").fill("needle")
1656
- self.page.locator("#full-search-cancel").click()
1657
- self.page.wait_for_timeout(700)
1658
- self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")
1659
- self.assertEqual(self.page.locator(".full-search-result").count(), 0)
1660
- self.page.locator("#full-search-retry").click()
1661
- self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '210 个结果'")
1662
-
1663
  def test_pdf_with_unavailable_ocr_index_does_not_fall_back(self):
1664
  self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
1665
  content_type="text/javascript", body=support.PDF_MODULE))
@@ -2820,75 +2503,6 @@ class ReaderRefactorTest(unittest.TestCase):
2820
  self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
2821
  self.assertEqual(self.page.locator('.reader-text').text_content(), text)
2822
 
2823
- def expose_toc_probe(self):
2824
- def instrument(route):
2825
- response = route.fetch()
2826
- route.fulfill(response=response, body=response.text() + '''
2827
- window.__startTocProbe = () => {
2828
- const sourceSections = [{linear:'yes'}, {linear:'no'}, {linear:'yes'}];
2829
- const visibleSections = [sourceSections[0], sourceSections[2], sourceSections[0]];
2830
- const probe = window.__tocProbe = {calls:0, active:0, peak:0, scans:0, held:[]};
2831
- visibleSections.indexOf = section => {probe.scans++; return Array.prototype.indexOf.call(visibleSections, section);};
2832
- let hold = true;
2833
- const children = Array.from({length:85}, (_, n) => ({label:'Chapter ' + n, href:'chapter-' + n + '#anchor%20' + n}));
2834
- children.push({label:'Invalid', href:'invalid'});
2835
- const view = {book:{sections:sourceSections, toc:[{label:'Volume', subitems:children}],
2836
- async resolveHref(href) {
2837
- probe.calls++; probe.active++; probe.peak = Math.max(probe.peak, probe.active);
2838
- try {
2839
- if (hold) await new Promise(resolve => probe.held.push(resolve));
2840
- if (probe.busy) {
2841
- const deadline = performance.now() + 1;
2842
- while (performance.now() < deadline) {}
2843
- }
2844
- if (href === 'invalid') throw Error('bad href');
2845
- const number = Number(href.match(/chapter-(\\d+)/)[1]);
2846
- return {index:number % 3, anchor:() => number};
2847
- } finally {probe.active--;}
2848
- }}, goTo(href) {probe.navigation = href;}};
2849
- probe.release = () => {hold = false; for (const resolve of probe.held.splice(0)) resolve();};
2850
- probe.promise = foliateTocEntries(view, visibleSections).then(entries => {
2851
- entries.find(e => e.href === 'chapter-84#anchor%2084').activate();
2852
- probe.entries = entries.map(e => ({label:e.label, section:e.sectionIndex, fragment:e.fragment,
2853
- anchor:typeof e.anchor === 'function' ? e.anchor() : null}));
2854
- }, error => {probe.error = error.name;});
2855
- };
2856
- ''')
2857
- self.page.route('**/static/reader.js*', instrument)
2858
- self.serve('TOC probe')
2859
- self.open(self.reader_url())
2860
- self.page.evaluate('window.__startTocProbe()')
2861
-
2862
- def test_foliate_toc_bounds_resolution_and_keeps_every_entry_in_order(self):
2863
- self.expose_toc_probe()
2864
- self.page.wait_for_function('() => window.__tocProbe.calls >= 8')
2865
- self.assertEqual(self.page.evaluate('__tocProbe.calls'), 8)
2866
- self.page.evaluate('''__tocProbe.busy = true; __tocProbe.ticks = [];
2867
- const timer = setInterval(() => __tocProbe.ticks.push(__tocProbe.calls), 0);
2868
- __tocProbe.promise.finally(() => clearInterval(timer)); __tocProbe.release();''')
2869
- self.page.evaluate('__tocProbe.promise')
2870
- entries = self.page.evaluate('__tocProbe.entries')
2871
- self.assertEqual(entries[0], {'label':'Volume', 'section':-1, 'fragment':'', 'anchor':None})
2872
- # The non-linear section at spine index 1 is a real destination: Foliate
2873
- # addresses supplements by -spine_index - 1, not by their visible index.
2874
- self.assertEqual(entries[1:-1], [dict(label=f'Chapter {n}', section=(0, -2, 1)[n % 3],
2875
- fragment=f'anchor {n}', anchor=n) for n in range(85)])
2876
- self.assertEqual(entries[-1], {'label':'Invalid', 'section':-1, 'fragment':'', 'anchor':None})
2877
- self.assertEqual(self.page.evaluate('[__tocProbe.peak, __tocProbe.scans, __tocProbe.calls]'), [8, 0, 86])
2878
- self.assertGreaterEqual(len(self.page.evaluate('__tocProbe.ticks')), 2)
2879
- self.assertEqual(self.page.evaluate('__tocProbe.navigation'), 'chapter-84#anchor%2084')
2880
-
2881
- def test_foliate_toc_disposal_stops_queued_resolution_and_late_publication(self):
2882
- self.expose_toc_probe()
2883
- self.page.wait_for_function('() => window.__tocProbe.calls >= 8')
2884
- self.page.evaluate("window.dispatchEvent(new Event('pagehide'))")
2885
- self.page.wait_for_function("() => window.__tocProbe.error === 'AbortError'")
2886
- self.assertEqual(self.page.evaluate('__tocProbe.calls'), 8)
2887
- self.page.evaluate('__tocProbe.release()')
2888
- self.page.wait_for_function('() => __tocProbe.active === 0')
2889
- self.assertFalse(self.page.evaluate('!!__tocProbe.entries'))
2890
- self.assertEqual(self.page.evaluate('__tocProbe.calls'), 8)
2891
-
2892
  def test_text_search_publishes_partial_results_before_full_scan(self):
2893
  self.page.add_init_script("""const native = window.setTimeout.bind(window);
2894
  window.setTimeout = (fn, ms, ...args) => native(fn, ms === 0 ? 20 : ms, ...args);""")
@@ -3182,25 +2796,6 @@ class ReaderRefactorTest(unittest.TestCase):
3182
  }''')
3183
  self.assertEqual(result, [dict(equal=True, unsafe=False, remote=False, styles=False)] * 9)
3184
 
3185
- def test_epub_svg_xlink_control_whitespace_cannot_execute_in_reader_context(self):
3186
- with zipfile.ZipFile(io.BytesIO(support.minimal_epub())) as archive:
3187
- files = {item.filename: archive.read(item.filename) for item in archive.infolist()}
3188
- files["OEBPS/chapter.xhtml"] = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
3189
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
3190
- <a id="probe" xlink:href="java&#x09;script:window.__readerSecurityMarker=17;void(0)">
3191
- <text x="10" y="20">safe label</text>
3192
- </a>
3193
- </svg>
3194
- </body></html>'''
3195
- body = support.zip_bytes({name: value for name, value in files.items() if name != "mimetype"},
3196
- ("mimetype", "application/epub+zip"))
3197
- self.serve(body, "application/epub+zip")
3198
- self.open(self.reader_url("epub", name="svg-xlink-security"))
3199
- probe = self.page.locator("article[data-section] #probe")
3200
- self.assertEqual(probe.get_attribute("xlink:href"), None)
3201
- probe.click()
3202
- self.assertFalse(self.page.evaluate("() => window.__readerSecurityMarker === 17"))
3203
-
3204
  def test_back_tapped_before_reader_module_binds_still_exits(self):
3205
  held = []
3206
  self.page.route("**/static/reader.js*", lambda route: held.append(route))
@@ -3218,32 +2813,6 @@ class ReaderRefactorTest(unittest.TestCase):
3218
  held.pop(0).continue_()
3219
  self.page.wait_for_url(landing, timeout=8000)
3220
 
3221
- def test_epub_prefixed_xlink_and_smil_href_cannot_execute_in_reader_context(self):
3222
- with zipfile.ZipFile(io.BytesIO(support.minimal_epub())) as archive:
3223
- files = {item.filename: archive.read(item.filename) for item in archive.infolist()}
3224
- files["OEBPS/chapter.xhtml"] = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
3225
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink" width="240" height="70">
3226
- <a id="probe" x:href="javascript:window.__readerSecurityMarker=23;void(0)">
3227
- <text x="10" y="20">prefixed label</text>
3228
- </a>
3229
- <a id="animated">
3230
- <set attributeName="href" to="javascript:window.__readerSecurityMarker=29;void(0)"/>
3231
- <text x="10" y="50">animated label</text>
3232
- </a>
3233
- </svg>
3234
- </body></html>'''
3235
- body = support.zip_bytes({name: value for name, value in files.items() if name != "mimetype"},
3236
- ("mimetype", "application/epub+zip"))
3237
- self.serve(body, "application/epub+zip")
3238
- self.open(self.reader_url("epub", name="svg-prefixed-xlink-security"))
3239
- probe = self.page.locator("article[data-section] #probe")
3240
- self.assertIsNone(probe.evaluate("n => n.getAttributeNS('http://www.w3.org/1999/xlink', 'href')"))
3241
- self.assertEqual(self.page.locator("article[data-section] #animated set").count(), 0)
3242
- probe.click()
3243
- self.page.locator("article[data-section] #animated").click()
3244
- self.page.wait_for_timeout(200)
3245
- self.assertIsNone(self.page.evaluate("() => window.__readerSecurityMarker ?? null"))
3246
-
3247
  def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):
3248
  dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
3249
  "/x8AAwMB/6XWbqkAAAAASUVORK5CYII=")
@@ -3279,41 +2848,6 @@ class ReaderRefactorTest(unittest.TestCase):
3279
  self.assertEqual(result, {"policy": True, "violations": ["img-src"]})
3280
  self.assertNotIn("https://img.remote.test/a.png", remote)
3281
 
3282
- def test_epub_css_cannot_load_remote_references_but_keeps_packaged_styles(self):
3283
- css = ("@import url(https://css.remote.test/a.css);\n"
3284
- "@import '\\68ttps://css.remote.test/b.css';\n"
3285
- "p.linked { letter-spacing: 3px; background-image: url(https://img.remote.test/a.png); }\n"
3286
- "p.escaped { background-image: \\75rl(//img.remote.test/b.png); }\n"
3287
- "p.set { background-image: image-set('https://img.remote.test/c.png' 1x); }\n"
3288
- "p.local { background-image: url(dot.png); }\n")
3289
- dot = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/6XWbqkAAAAASUVORK5CYII=")
3290
- body = support.zip_bytes({
3291
- "META-INF/container.xml": '<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>',
3292
- "OEBPS/content.opf": '<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">css-security</dc:identifier><dc:title>CSS</dc:title><dc:language>en</dc:language></metadata><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/><item id="style" href="style.css" media-type="text/css"/><item id="dot" href="dot.png" media-type="image/png"/></manifest><spine><itemref idref="chapter"/></spine></package>',
3293
- "OEBPS/style.css": css,
3294
- "OEBPS/dot.png": dot,
3295
- "OEBPS/chapter.xhtml": '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>CSS</title><link rel="stylesheet" href="style.css"/><style>p.inline { background-image: \\75 rl("https://img.remote.test/d.png"); }</style></head><body><p class="linked">linked</p><p class="escaped">escaped</p><p class="set">set</p><p class="local">local</p><p class="inline">inline</p><p class="attr" style="background-image:url(&quot;https://img.remote.test/e.png&quot;)">attr</p></body></html>',
3296
- }, ("mimetype", "application/epub+zip"))
3297
- remote = []
3298
- self.page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None)
3299
- self.serve(body, "application/epub+zip")
3300
- self.open(self.reader_url("epub", name="css-security"))
3301
- self.page.wait_for_function("""() => {
3302
- const root = document.querySelector('article[data-section]')?.shadowRoot;
3303
- const p = root?.querySelector('p.linked');
3304
- return p && getComputedStyle(p).letterSpacing === '3px';
3305
- }""")
3306
- styles = self.page.evaluate("""() => {
3307
- const root = document.querySelector('article[data-section]').shadowRoot;
3308
- return Object.fromEntries([...root.querySelectorAll('p')].map(p =>
3309
- [p.className, getComputedStyle(p).backgroundImage]));
3310
- }""")
3311
- for name in ("linked", "escaped", "set", "inline", "attr"):
3312
- self.assertEqual(styles[name], "none", name)
3313
- self.assertRegex(styles["local"], r"^url\(\"blob:")
3314
- self.page.wait_for_timeout(300)
3315
- self.assertEqual(remote, [])
3316
-
3317
  def frame_host_reader(self, overlay=False, cross_origin=False):
3318
  # The Reader must decide by its real host whether parent messages are handled.
3319
  reader = self.reader_url(name="framed", path="Test/docs")
@@ -3394,6 +2928,64 @@ class ReaderRefactorTest(unittest.TestCase):
3394
  str(theme == "dark").lower())
3395
  page.close()
3396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3397
  def test_epub_html_and_svg_references_cannot_load_remote_resources(self):
3398
  vectors = ('<p style="background:image-set(\'https://img.remote.test/a.png\' 1x)">a</p>'
3399
  '<p style="background:\\75rl(https://img.remote.test/b.png)">b</p>'
@@ -3407,47 +2999,13 @@ class ReaderRefactorTest(unittest.TestCase):
3407
  '<use href="https://img.remote.test/h.svg#a"/></svg><p id="kept">kept text</p>')
3408
  chapter = ('<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Refs</title></head><body>'
3409
  + vectors + '</body></html>')
3410
- book = support.zip_bytes({
3411
- "META-INF/container.xml": '<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>',
3412
- "OEBPS/content.opf": '<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">refs</dc:identifier><dc:title>Refs</dc:title><dc:language>en</dc:language></metadata><manifest><item id="c" href="c.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="c"/></spine></package>',
3413
- "OEBPS/c.xhtml": chapter,
3414
- }, ("mimetype", "application/epub+zip"))
3415
- prefix = "chapters/ebook/epub/" + "e" * 64 + "/" + "f" * 16 + "/"
3416
- manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
3417
- {"index": 1, "path": "chapters/chapter-0001.xhtml", "title": "Refs",
3418
- "bytes": len(chapter.encode()), "sha256": hashlib.sha256(chapter.encode()).hexdigest()}]}
3419
- def bucket(route):
3420
- path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
3421
- if path == prefix + "chapter-manifest.json":
3422
- route.fulfill(content_type="application/json", body=json.dumps(manifest))
3423
- elif path == prefix + "chapters/chapter-0001.xhtml":
3424
- route.fulfill(content_type="application/xhtml+xml", body=chapter)
3425
- else:
3426
- route.fulfill(status=404, body="missing")
3427
- bucket_url = ("https://voiceofml-search.hf.space/api/reader-bucket-resource?path="
3428
- + urllib.parse.quote(prefix + "chapter-manifest.json", safe=""))
3429
- for mode, url, root in (
3430
- ("foliate", self.reader_url("epub", name="remote-refs"),
3431
- "document.querySelector('article[data-section]')?.shadowRoot"),
3432
- ("chapters", self.reader_url("epub-chapters", url=bucket_url),
3433
- "document.querySelector('.reader-epub-chapter')"),
3434
- ):
3435
- with self.subTest(mode=mode):
3436
- page = self.context.new_page()
3437
- page.set_default_timeout(int(os.environ.get("READER_TEST_TIMEOUT_MS", "6000")))
3438
- page.on("pageerror", lambda error: self.errors.append(str(error)))
3439
- remote = []
3440
- page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None)
3441
- page.route("**/api/reader-content**", lambda route: route.fulfill(
3442
- content_type="application/epub+zip", body=book))
3443
- page.route("https://voiceofml-search.hf.space/api/reader-bucket-resource**", bucket)
3444
- page.goto(url)
3445
- page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
3446
- page.wait_for_function(f"() => !!({root})?.querySelector('#kept')")
3447
- page.wait_for_timeout(400)
3448
- self.assertEqual(remote, [])
3449
- self.assertEqual(page.evaluate(f"() => ({root}).querySelector('#local-use').getAttribute('href')"), "#dot")
3450
- page.close()
3451
 
3452
  def expose_html_contrast(self):
3453
  def instrument(route):
@@ -4000,52 +3558,6 @@ class ReaderRefactorTest(unittest.TestCase):
4000
  saved = self.page.evaluate("source => VoiceOfMLReaderStore.get(source)", source)
4001
  self.assertEqual(saved["chapterIndex"], 1)
4002
 
4003
- def test_foliate_cfi_selects_accented_and_inline_ranges_after_repeated_search(self):
4004
- with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters())) as archive:
4005
- files = {name: archive.read(name) for name in archive.namelist()}
4006
- chapter = next(name for name in files if name.endswith("chapter-1.xhtml"))
4007
- files[chapter] = b'''<?xml version="1.0" encoding="UTF-8"?>
4008
- <html xmlns="http://www.w3.org/1999/xhtml"><head><title>Search</title></head><body>
4009
- <h1>Search</h1><p style="height:1300px">Before</p>
4010
- <p id="accent">caf&#233;</p><p style="height:1300px">Between</p>
4011
- <p id="plain">cafe</p><p id="inline">inter<b>national</b></p><p style="height:1300px">After</p>
4012
- </body></html>'''
4013
- self.serve(support.zip_bytes(files), "application/epub+zip")
4014
- self.open(self.reader_url("epub"))
4015
- self.search("cafe")
4016
- self.assertEqual(self.page.locator(".full-search-result").count(), 2)
4017
- self.page.locator(".full-search-result").first.click()
4018
- self.assertEqual(self.page.locator("#accent .full-search-highlight").text_content(), "caf\u00e9")
4019
- self.page.locator("#history").click()
4020
- self.assertFalse(self.page.locator("#full-search-view").is_hidden())
4021
- self.page.locator(".full-search-result").nth(1).click()
4022
- self.assertEqual(self.page.locator("#plain .full-search-highlight").text_content(), "cafe")
4023
- self.page.locator("#history").click()
4024
- self.assertFalse(self.page.locator("#full-search-view").is_hidden())
4025
- self.page.locator("#full-search-input").fill("international")
4026
- self.page.locator(".full-search-result").click()
4027
- self.page.locator("#inline .full-search-highlight").first.wait_for()
4028
- self.assertEqual("".join(self.page.locator("#inline .full-search-highlight").all_text_contents()), "international")
4029
-
4030
- def test_chm_self_closing_anchors_keep_text_order_and_search_after_many_entries(self):
4031
- with zipfile.ZipFile(io.BytesIO(support.epub_with_legacy_chm_markup())) as archive:
4032
- files = {name: archive.read(name) for name in archive.namelist()}
4033
- # Hundreds of empty XML anchors become nested containers under HTML
4034
- # parsing, which can reorder inline citations near the parser depth cap.
4035
- entries = ''.join(f'<html:a id="entry-{i}"/><html:p>Entry {i}: '
4036
- f'<html:span>Citation {i}</html:span>; End {i}.</html:p>' for i in range(600))
4037
- files['OEBPS/chapter.xhtml'] = (
4038
- '<html:html xmlns:html="http://www.w3.org/1999/xhtml"><html:head><html:meta/>'
4039
- '<html:title>Order</html:title></html:head><html:body>' + entries + '</html:body></html:html>'
4040
- ).encode()
4041
- self.serve(support.zip_bytes(files), "application/epub+zip")
4042
- self.open(self.reader_url("epub"))
4043
- body = self.page.locator('.foliate-continuous .reader-section-body')
4044
- self.assertEqual(body.text_content(), ''.join(f'Entry {i}: Citation {i}; End {i}.' for i in range(600)))
4045
- self.search('Citation 599')
4046
- self.page.locator('.full-search-result').first.click()
4047
- self.assertEqual(self.page.locator('.foliate-continuous .full-search-highlight').text_content(), 'Citation 599')
4048
-
4049
  def test_chapter_resources_allow_siblings_within_manifest_family_only(self):
4050
  for extension in ("epub", "chm"):
4051
  with self.subTest(extension=extension):
 
9
  import time
10
  import unittest
11
  import urllib.parse
 
12
  import wave
13
 
14
  from tests.performance import test_reader_performance as support
 
143
 
144
  [chapter](chapter%20one.md)
145
 
 
 
146
  [fragment](chapter%20one.md#section)
147
 
148
  [self](index.md#local)
 
178
  route.fulfill(content_type='text/markdown', body=index)
179
  elif path.endswith('/books/chapter one.md'):
180
  route.fulfill(content_type='text/markdown', body=chapter)
 
 
181
  else:
182
  route.fulfill(status=404, body='missing')
183
  self.page.route('**/api/reader-content**', serve)
 
189
  base = self.markdown_link_fixture()
190
  self.open(self.reader_url('md', name='books/index'))
191
  article = self.page.locator('.reader-markdown')
192
+ href = article.get_by_role('link', name='chapter', exact=True).get_attribute('href')
193
+ target = urllib.parse.urlsplit(href)
194
+ args = urllib.parse.parse_qs(target.query)
195
+ self.assertTrue(target.path.endswith('/static/reader.html'))
196
+ self.assertEqual(urllib.parse.unquote(args['url'][0]), base + 'chapter one.md')
197
+ self.assertEqual(args['ext'][0], 'md')
 
198
  self.assertEqual(article.get_by_role('link', name='local', exact=True).get_attribute('href'), '#local')
199
  self.assertEqual(article.get_by_role('link', name='self', exact=True).get_attribute('href'), '#local')
200
  self.assertEqual(article.get_by_role('link', name='outside').get_attribute('href'), 'https://example.org/article.md')
 
248
  href = self.page.locator('.reader-markdown').get_by_role('link', name='chapter', exact=True).get_attribute('href')
249
  self.assertEqual(urllib.parse.unquote(urllib.parse.parse_qs(urllib.parse.urlsplit(href).query)['url'][0]), base + 'chapter one.md')
250
 
 
 
 
 
 
 
 
 
 
 
 
251
  def test_markdown_dataset_link_in_search_overlay_uses_parent_navigation(self):
252
  self.markdown_link_fixture()
253
  reader = self.reader_url('md', name='books/index')
 
721
  self.assertEqual(self.page.evaluate('window.__imageWaitProbe()'),
722
  [[0, 1, 'eager'], [0, 0, 'eager'], [0, 0, 'eager'], 'AbortError', 0])
723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724
  def test_spreadsheet_cells_take_first_viewport_while_images_are_pending(self):
725
  # Delay only the post-frame image settlement. The sanitized HTML has
726
  # already loaded, so this distinguishes first paint from restore-ready.
 
868
  self.page.locator('.reader-epub-chapter[data-chapter="6"]').wait_for(state="attached")
869
  self.assertNotIn(1, requested)
870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
871
  def test_djvu_recovers_ocr_text_and_searches_valid_index(self):
872
  state = install_native_djvu(self.page, self.origin, ocr=True, fail_page_once=True)
873
  self.open(state["url"])
 
1343
  self.assertEqual(self.page.locator("#full-search-page").input_value(), "3")
1344
  self.assertEqual(self.page.locator("#full-search-status").text_content(), "180 个结果")
1345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1346
  def test_pdf_with_unavailable_ocr_index_does_not_fall_back(self):
1347
  self.page.route("**/static/vendor/pdf.min.*.mjs", lambda route: route.fulfill(
1348
  content_type="text/javascript", body=support.PDF_MODULE))
 
2503
  self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
2504
  self.assertEqual(self.page.locator('.reader-text').text_content(), text)
2505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2506
  def test_text_search_publishes_partial_results_before_full_scan(self):
2507
  self.page.add_init_script("""const native = window.setTimeout.bind(window);
2508
  window.setTimeout = (fn, ms, ...args) => native(fn, ms === 0 ? 20 : ms, ...args);""")
 
2796
  }''')
2797
  self.assertEqual(result, [dict(equal=True, unsafe=False, remote=False, styles=False)] * 9)
2798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2799
  def test_back_tapped_before_reader_module_binds_still_exits(self):
2800
  held = []
2801
  self.page.route("**/static/reader.js*", lambda route: held.append(route))
 
2813
  held.pop(0).continue_()
2814
  self.page.wait_for_url(landing, timeout=8000)
2815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2816
  def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):
2817
  dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
2818
  "/x8AAwMB/6XWbqkAAAAASUVORK5CYII=")
 
2848
  self.assertEqual(result, {"policy": True, "violations": ["img-src"]})
2849
  self.assertNotIn("https://img.remote.test/a.png", remote)
2850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2851
  def frame_host_reader(self, overlay=False, cross_origin=False):
2852
  # The Reader must decide by its real host whether parent messages are handled.
2853
  reader = self.reader_url(name="framed", path="Test/docs")
 
2928
  str(theme == "dark").lower())
2929
  page.close()
2930
 
2931
+ def open_security_chapter(self, chapter):
2932
+ prefix = "chapters/ebook/epub/" + "e" * 64 + "/" + "f" * 16 + "/"
2933
+ manifest_path = prefix + "chapter-manifest.json"
2934
+ chapter_path = "chapters/chapter-0001.xhtml"
2935
+ manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
2936
+ {"index": 1, "path": chapter_path, "bytes": len(chapter),
2937
+ "sha256": hashlib.sha256(chapter).hexdigest()}]}
2938
+
2939
+ def bucket(route):
2940
+ path = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["path"][0]
2941
+ if path == manifest_path:
2942
+ route.fulfill(json=manifest)
2943
+ elif path == prefix + chapter_path:
2944
+ route.fulfill(content_type="application/xhtml+xml", body=chapter)
2945
+ else:
2946
+ route.fulfill(status=404)
2947
+
2948
+ self.page.route("**/api/reader-bucket-resource?**", bucket)
2949
+ source = ("https://voiceofml-search.hf.space/api/reader-bucket-resource?" +
2950
+ urllib.parse.urlencode({"path": manifest_path}))
2951
+ self.open(self.reader_url("epub-chapters", url=source))
2952
+ return self.page.locator(".reader-epub-chapter")
2953
+
2954
+ def test_chapter_svg_xlink_control_whitespace_cannot_execute_in_reader_context(self):
2955
+ chapter = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
2956
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
2957
+ <a id="probe" xlink:href="java&#x09;script:window.__readerSecurityMarker=17;void(0)">
2958
+ <text x="10" y="20">safe label</text>
2959
+ </a>
2960
+ </svg>
2961
+ </body></html>'''
2962
+ chapter_root = self.open_security_chapter(chapter)
2963
+ probe = chapter_root.locator("#probe")
2964
+ self.assertEqual(probe.get_attribute("xlink:href"), None)
2965
+ probe.click()
2966
+ self.assertFalse(self.page.evaluate("() => window.__readerSecurityMarker === 17"))
2967
+
2968
+ def test_chapter_prefixed_xlink_and_smil_href_cannot_execute_in_reader_context(self):
2969
+ chapter = b'''<html xmlns="http://www.w3.org/1999/xhtml"><body>
2970
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink" width="240" height="70">
2971
+ <a id="probe" x:href="javascript:window.__readerSecurityMarker=23;void(0)">
2972
+ <text x="10" y="20">prefixed label</text>
2973
+ </a>
2974
+ <a id="animated">
2975
+ <set attributeName="href" to="javascript:window.__readerSecurityMarker=29;void(0)"/>
2976
+ <text x="10" y="50">animated label</text>
2977
+ </a>
2978
+ </svg>
2979
+ </body></html>'''
2980
+ chapter_root = self.open_security_chapter(chapter)
2981
+ probe = chapter_root.locator("#probe")
2982
+ self.assertIsNone(probe.evaluate("n => n.getAttributeNS('http://www.w3.org/1999/xlink', 'href')"))
2983
+ self.assertEqual(chapter_root.locator("#animated set").count(), 0)
2984
+ probe.click()
2985
+ chapter_root.locator("#animated").click()
2986
+ self.page.wait_for_timeout(200)
2987
+ self.assertIsNone(self.page.evaluate("() => window.__readerSecurityMarker ?? null"))
2988
+
2989
  def test_epub_html_and_svg_references_cannot_load_remote_resources(self):
2990
  vectors = ('<p style="background:image-set(\'https://img.remote.test/a.png\' 1x)">a</p>'
2991
  '<p style="background:\\75rl(https://img.remote.test/b.png)">b</p>'
 
2999
  '<use href="https://img.remote.test/h.svg#a"/></svg><p id="kept">kept text</p>')
3000
  chapter = ('<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Refs</title></head><body>'
3001
  + vectors + '</body></html>')
3002
+ remote = []
3003
+ self.page.on("request", lambda request: remote.append(request.url) if ".remote.test" in request.url else None)
3004
+ chapter_root = self.open_security_chapter(chapter.encode())
3005
+ chapter_root.locator("#kept").wait_for(state="attached")
3006
+ self.page.wait_for_timeout(400)
3007
+ self.assertEqual(remote, [])
3008
+ self.assertEqual(chapter_root.locator("#local-use").get_attribute("href"), "#dot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3009
 
3010
  def expose_html_contrast(self):
3011
  def instrument(route):
 
3558
  saved = self.page.evaluate("source => VoiceOfMLReaderStore.get(source)", source)
3559
  self.assertEqual(saved["chapterIndex"], 1)
3560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3561
  def test_chapter_resources_allow_siblings_within_manifest_family_only(self):
3562
  for extension in ("epub", "chm"):
3563
  with self.subTest(extension=extension):