File size: 46,170 Bytes
7c91d7e 58d59b4 7409dc6 dac2ca2 6db4908 82af23b dac2ca2 49a03ba 6db4908 8c62083 6db4908 dac2ca2 49a03ba eeaba06 262c3c2 49a03ba 7c91d7e 49a03ba 50e6523 8c62083 50e6523 8c62083 49a03ba dac2ca2 49a03ba dac2ca2 49a03ba dac2ca2 49a03ba 551ecc9 dac2ca2 551ecc9 dac2ca2 49a03ba 02a27d4 49a03ba 551ecc9 49a03ba 551ecc9 49a03ba dac2ca2 49a03ba 02a27d4 49a03ba dac2ca2 49a03ba 02a27d4 49a03ba 1dc63a4 49a03ba dac2ca2 1dc63a4 49a03ba dac2ca2 49a03ba 02a27d4 49a03ba 02a27d4 49a03ba 1dc63a4 49a03ba dac2ca2 49a03ba 8c62083 dac2ca2 49a03ba 513cab0 8c62083 513cab0 8c62083 513cab0 8c62083 513cab0 dac2ca2 768231f 01ab508 82af23b 01ab508 4e0435b 01ab508 768231f dac2ca2 11af73b 768231f 11af73b b9bb1a9 768231f 82af23b 768231f dac2ca2 49a03ba dac2ca2 768231f 82af23b dac2ca2 82af23b 768231f 49a03ba dac2ca2 49a03ba 6c8fd46 49a03ba 7db8a30 03539ba a940909 03539ba 49a03ba 551ecc9 49a03ba 03539ba a940909 49a03ba 03539ba 86eb73d 49a03ba 03539ba a940909 03539ba 7409dc6 03539ba 49a03ba 03539ba a940909 49a03ba 03539ba 49a03ba 82af23b 01ab508 513cab0 49a03ba 262c3c2 49a03ba 262c3c2 1dc63a4 49a03ba dac2ca2 768231f 8c62083 49a03ba eeaba06 49a03ba eeaba06 49a03ba 262c3c2 eeaba06 8c62083 dac2ca2 eeaba06 1dc63a4 eeaba06 1dc63a4 eeaba06 8c62083 eeaba06 8c62083 eeaba06 49a03ba 86eb73d 49a03ba dac2ca2 49a03ba dac2ca2 49a03ba 551ecc9 49a03ba 86eb73d 49a03ba eeaba06 49a03ba dac2ca2 49a03ba dac2ca2 1dc63a4 82af23b 49a03ba 1dc63a4 49a03ba eeaba06 49a03ba dac2ca2 49a03ba c0a4416 49a03ba c0a4416 dac2ca2 49a03ba 1dc63a4 49a03ba 86eb73d 49a03ba 6db4908 49a03ba 6db4908 1dc63a4 6db4908 49a03ba eeaba06 49a03ba 6db4908 49a03ba 6db4908 49a03ba 8c62083 6db4908 49a03ba dac2ca2 49a03ba 262c3c2 49a03ba 6db4908 49a03ba 6db4908 dac2ca2 6db4908 01ab508 6db4908 8c62083 dac2ca2 49a03ba 58d59b4 dac2ca2 49a03ba 50e6523 49a03ba 50e6523 49a03ba 58d59b4 49a03ba 8c62083 1dc63a4 02a27d4 49a03ba 01ab508 49a03ba 6db4908 01ab508 6db4908 f817d67 6db4908 f817d67 6db4908 f817d67 49a03ba 6db4908 58d59b4 8c62083 6db4908 49a03ba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 | import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs";
import { chapterIndexInRange, matchesChapterManifest } from "../ui/reader-progress.mjs";
/** @param {unknown} value @returns {value is {path: string, bytes: number, sha256: string, [key: string]: unknown}} */
export function isChapterSearchIndex(value) {
if (!value || typeof value !== "object") return false;
return "path" in value && value.path === "epub-search-index.json.gz" &&
"bytes" in value && typeof value.bytes === "number" && Number.isSafeInteger(value.bytes) && value.bytes > 0 &&
"sha256" in value && typeof value.sha256 === "string" && /^[0-9a-f]{64}$/.test(value.sha256);
}
/** @param {unknown} value */
export function chapterOptionalText(value) {
return typeof value === "string" ? value : "";
}
/** Match the validator's bytes/size precedence without poisoning the prefetch sum.
* @param {unknown} chapter */
export function chapterPrefetchSize(chapter) {
try {
const raw = chapter && typeof chapter === "object"
? (("bytes" in chapter ? chapter.bytes : undefined) ?? ("size" in chapter ? chapter.size : undefined) ?? 0)
: (typeof chapter === "number" || typeof chapter === "string" ? chapter : 0);
const size = Number(raw);
return Number.isFinite(size) && size >= 0 ? size : 0;
} catch (_) { return 0; }
}
/** Build one scale for the whole manifest. Sanitized HTML bytes only approximate
* reading length; do not mix byte weights with equal weights or measure fetched text.
* @param {import("../../../typings/reader-chapter-format-strict").Chapter[]} chapters */
export function createChapterProgress(chapters) {
const count = chapters.length, prefix = [0];
let total = 0;
for (const chapter of chapters) {
const raw = chapter.bytes ?? chapter.size;
const weight = typeof raw === "number" || typeof raw === "string" ? Number(raw) : 0;
if (!Number.isSafeInteger(weight) || weight <= 0) break;
total += weight;
prefix.push(total);
}
if (prefix.length !== count + 1) {
for (let i = 1; i <= count; i++) prefix[i] = i;
total = count;
}
return {
/** @param {number} index @param {number} fraction */
at(index, fraction) {
const start = prefix[index - 1], end = prefix[index];
return start === undefined || end === undefined ? 0 : (start + (end - start) * fraction) / total;
},
/** @param {number} fraction */
locate(fraction) {
const target = total * fraction;
let low = 1, high = count;
while (low < high) {
const mid = (low + high) >>> 1;
if (target < /** @type {number} */ (prefix[mid])) high = mid;
else low = mid + 1;
}
const start = /** @type {number} */ (prefix[low - 1]), end = /** @type {number} */ (prefix[low]);
return { chapterIndex: low, fraction: (target - start) / (end - start) };
}
};
}
/** @typedef {import("../../../typings/reader-chapter-format-strict").TocEntry} ChapterTocEntry */
/** @param {unknown} entry @returns {entry is ChapterTocEntry} */
function isChapterTocEntry(entry) {
return typeof entry === "object" && entry !== null &&
"label" in entry && typeof entry.label === "string" &&
"chapterIndex" in entry && typeof entry.chapterIndex === "number" &&
"fragment" in entry && typeof entry.fragment === "string" &&
"depth" in entry && typeof entry.depth === "number" &&
"activate" in entry && typeof entry.activate === "function";
}
/** @param {import("../../../typings/reader-chapter-format-strict").ChapterFormatContext} readerContext */
export function createReaderChapterFormat(readerContext) {
const markerInset = 8;
/** @type {((generation: number) => ((landed: boolean) => void) | null) | null} */
let trackOpeningSeek = null;
// Keep an explicit End seek at the bottom if late chapter content changes
// the scroll range. For a book that fits, this also distinguishes End from Home.
/** @type {{generation: number, limit: number} | null} */
let progressEnd = null;
const releaseProgressEnd = () => { progressEnd = null; };
const isProgressEnd = () => progressEnd !== null && readerContext.isReaderGenerationCurrent("navigation", progressEnd.generation);
/** @param {DOMRect} rect @param {number} marker @param {boolean} last */
function chapterProgressHeight(rect, marker, last) {
if (!last) return rect.height;
const viewport = readerContext.viewport;
// Map the last chapter to the line that can actually reach the marker at the
// scroll limit. Otherwise seeking near the end clamps to the same position.
const remaining = viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop;
return Math.max(0, Math.min(rect.height, marker - rect.top + remaining));
}
/** @param {Response | Promise<Response>} prepared */
async function renderChapterManifest(prepared) {
const response = await prepared;
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const manifestBytes = await VoiceOfMLReaderSecurity.readBytes(response, VoiceOfMLReaderSecurity.LIMITS.manifestBytes);
const manifest = VoiceOfMLReaderSecurity.validateChapterManifest(JSON.parse(new TextDecoder().decode(manifestBytes)));
readerContext.assertReaderActive();
const frame = document.createElement("div");
frame.className = "epub-frame";
frame.style.overflowAnchor = "none";
const layoutStyle = document.createElement("style");
layoutStyle.textContent = EBOOK_LAYOUT_STYLE;
frame.appendChild(layoutStyle);
const openingGeneration = readerContext.readerRuntime.currentGeneration("navigation");
const openingLanding = Promise.withResolvers();
/** @type {Promise<void> | null} */
let pendingOpeningJump = null;
/** @type {((landed: boolean) => void) | null} */
let finishPendingOpeningJump = null;
const cancelOpeningJump = () => finishPendingOpeningJump?.(false);
/** @param {number} generation */
function trackOpeningJump(generation) {
if (chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", generation)) return null;
cancelOpeningJump();
const jump = Promise.withResolvers();
pendingOpeningJump = jump.promise;
const finish = (/** @type {boolean} */ landed) => {
if (pendingOpeningJump !== jump.promise) return;
pendingOpeningJump = null;
finishPendingOpeningJump = null;
stopWatching();
if (landed && readerContext.isReaderGenerationCurrent("navigation", generation)) openingLanding.resolve(undefined);
jump.resolve(undefined);
};
// A superseded jump can no longer land, even if its chapter is still loading.
const runtime = /** @type {ReaderRuntime} */ (readerContext.readerRuntime);
const stopWatching = runtime.events.on("generation", () => {
if (!readerContext.isReaderGenerationCurrent("navigation", generation)) finish(false);
});
finishPendingOpeningJump = finish;
return finish;
}
readerContext.content.appendChild(frame);
const loaded = new Set(), retainedBytes = new Map(),
manifestBase = readerContext.trustedReaderAssetManifestUrl(readerContext.chapterManifestUrl || readerContext.sourceUrl);
const chapterByIndex = new Map(manifest.chapters.map((chapter) => [chapter.index, chapter]));
const chapterPrefetchCount = 6;
const chapterPrefetchMaxCount = 10, chapterPrefetchBytes = 128 * 1024;
let chapterFocusIndex = 1, chapterWindowFrame = 0, chapterWindowReady = false;
let navigationTargetChapter = 0;
/** @type {(() => void) | null} */
let navigationProtectionCleanup = null;
let chapterNavigating = 0;
/** @type {IntersectionObserver | null} */
let chapterPreviousObserver = null;
const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();
if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");
const searchIndex = manifest.search_index;
readerContext.chapterSearchConfiguration =
isChapterSearchIndex(searchIndex)
? {
chapters: manifest.chapters,
index: {
...searchIndex,
url: (() => {
const resolved = readerContext.trustedChapterUrl(searchIndex.path, manifestBase);
if (!resolved) return "";
const target = new URL(resolved, location.href);
const bucketUrl = target.origin === "https://voiceofml-search.hf.space" &&
target.pathname === "/api/reader-bucket-resource"
? target.pathname + target.search : resolved;
return readerContext.readerContentUrl(bucketUrl);
})()
}
}
: null;
/** @type {Map<string, string | null>} */
const resolvedChapterUrls = new Map();
/** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter */
const chapterUrl = (chapter) => {
let url = resolvedChapterUrls.get(chapter.path);
if (url === undefined) {
url = readerContext.trustedChapterUrl(chapter.path, manifestBase);
resolvedChapterUrls.set(chapter.path, url);
}
return url;
};
/** @type {Map<string, import("../../../typings/reader-chapter-format-strict").Chapter> | null} */
let chaptersByUrl = null;
let indexedChapterCount = 0;
/** @param {string} href */
const chapterAtUrl = (href) => {
const byUrl = chaptersByUrl ??= new Map();
const indexed = byUrl.get(href);
if (indexed) return indexed;
// Extend only on demand, in manifest order (not chapter load order),
// so duplicate URLs still resolve to the first chapter.
while (indexedChapterCount < manifest.chapters.length) {
const chapter = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[indexedChapterCount]);
const url = chapterUrl(chapter);
indexedChapterCount++;
if (url === null || byUrl.has(url)) continue;
byUrl.set(url, chapter);
if (url === href) return chapter;
}
return null;
};
/** @param {number} index */
const chapterAt = (index) => chapterByIndex.get(index) || null;
// Reader-owned rows are sorted direct children; don't search through chapter prose.
/** @param {number} index @param {boolean} [skipArticleAtIndex] */
const chapterRowAtOrAfter = (index, skipArticleAtIndex = false) => {
for (const row of /** @type {HTMLCollectionOf<HTMLElement>} */ (frame.children)) {
const rowIndex = Number(row.dataset.chapter);
if (rowIndex > index || (rowIndex === index &&
(!skipArticleAtIndex || row.classList.contains("reader-chapter-sentinel")))) return row;
}
return null;
};
/** @param {string} raw @param {string} base */
const resourceUrl = (raw, base) => {
const value = String(raw || "").trim();
if (!value || value.startsWith("#")) return null;
return readerContext.trustedChapterResourceUrl(value, base, manifestBase);
};
/** @param {HTMLElement} article */
const insertChapter = (article) => {
const row = chapterRowAtOrAfter(Number(article.dataset.chapter));
const marker = row && row.dataset.chapter === article.dataset.chapter ? row : null;
if (marker?.classList.contains("reader-epub-chapter")) return marker;
const insert = () => {
if (marker) {
/** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).unobserve(marker);
/** @type {IntersectionObserver} */ (chapterPreviousObserver).unobserve(marker);
marker.replaceWith(article);
} else frame.insertBefore(article, row);
};
const preservePosition = chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration);
if (preservePosition) readerContext.chapterScrollAnchors.preserve(insert);
else insert();
/** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).observe(article);
if (preservePosition) readerContext.chapterScrollAnchors.observe(article);
return article;
};
/** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter @param {boolean} [previous] */
const ensureSentinel = (chapter, previous = false) => {
if (readerContext.readerAbortController.signal.aborted || loaded.has(chapter.index)) return null;
// Virtualization creates the sentinel before it removes the old article.
const row = chapterRowAtOrAfter(chapter.index, true);
if (row?.dataset.chapter === String(chapter.index)) return row;
const marker = document.createElement("button");
marker.type = "button";
marker.className = "reader-chapter-sentinel";
marker.dataset.chapter = String(chapter.index);
marker.textContent = `加载第 ${chapter.index} 章`;
marker.setAttribute("aria-label", `重试加载第 ${chapter.index} 章`);
marker.addEventListener("click", () => {
marker.disabled = true;
fetchChapter(chapter).catch((error) => {
marker.disabled = false;
console.warn("EPUB chapter could not be loaded", error);
});
});
const insert = () => frame.insertBefore(marker, row);
if (chapterWindowReady || !readerContext.isReaderGenerationCurrent("navigation", openingGeneration))
readerContext.chapterScrollAnchors.preserve(insert);
else insert();
/** @type {IntersectionObserver} */ (previous ? chapterPreviousObserver : readerContext.chapterManifestObserver).observe(marker);
return marker;
};
/** @param {string} fragment */
const decodeChapterFragment = fragment => {
const id = fragment.replace(/^#/, "");
try { return decodeURIComponent(id); } catch (_) { return id; }
};
/** @param {Element} article @param {string} fragment */
const chapterTarget = (article, fragment) =>
!fragment || article.id === fragment ? article :
article.querySelector(`[id="${CSS.escape(fragment)}"], [name="${CSS.escape(fragment)}"]`);
/** @param {HTMLElement} article @param {ChapterTocEntry[]} entries */
const bindChapterTocTargets = (article, entries) => {
const batchThreshold = 16;
if (entries.length < batchThreshold) {
for (const entry of entries) entry.target = chapterTarget(article, decodeChapterFragment(entry.fragment));
return;
}
/** @type {Map<string, Element | null>} */
const targets = new Map();
const fragments = entries.map(entry => decodeChapterFragment(entry.fragment));
for (const [index, entry] of entries.entries()) {
const fragment = fragments[index] || "";
if (!fragment || fragment === article.id) entry.target = article;
// With /u, the surrogate range matches only unpaired code units.
// Keep the selector path for these and NUL, which CSS may replace.
else if (/[\u0000\uD800-\uDFFF]/u.test(fragment)) entry.target = chapterTarget(article, fragment);
else targets.set(fragment, null);
}
if (!targets.size) return;
if (targets.size < batchThreshold) {
for (const fragment of targets.keys()) targets.set(fragment, chapterTarget(article, fragment));
} else {
// Like the selector list, the first exact ID or name in document
// order wins, even when a name precedes a matching ID.
let remaining = targets.size;
for (const node of article.querySelectorAll("[id], [name]")) {
for (const value of [node.getAttribute("id"), node.getAttribute("name")]) {
if (value !== null && targets.get(value) === null) {
targets.set(value, node);
remaining--;
}
}
if (!remaining) break;
}
}
for (const [index, entry] of entries.entries()) {
const target = targets.get(fragments[index] || "");
if (target !== undefined) entry.target = target;
}
};
/** @param {string | null} value */
const normalizeTocLabel = value => String(value || "").replace(/\s+/gu, "").toLowerCase();
// Old merged CHM bundles can contain missing or stale TOC fragments.
// Repair only a unique exact label pointing to an unambiguous generated
// page in the same chapter, and never replace a working explicit anchor.
/** @param {HTMLElement} article @param {ChapterTocEntry[]} entries */
const repairMergedChmToc = (article, entries) => {
if (!entries.length) return;
const idCounts = new Map();
for (const node of article.querySelectorAll("[id], [name]"))
for (const id of new Set([node.id, node.getAttribute("name")]))
if (id) idCounts.set(id, (idCounts.get(id) || 0) + 1);
const missing = entries.filter(entry => {
if (!normalizeTocLabel(entry.label)) return false;
const fragment = decodeChapterFragment(entry.fragment);
if (!fragment) return true;
if (fragment === article.id || idCounts.has(fragment)) return false;
// Keep parity with the selector fallback for CSS-escaped edge cases.
return !/[\u0000\uD800-\uDFFF]/u.test(fragment) || !chapterTarget(article, fragment);
});
if (!missing.length) return;
const wanted = new Set(missing.map(entry => normalizeTocLabel(entry.label)));
const targets = new Map();
for (const link of article.querySelectorAll('a[href^="#chm-page-"]')) {
const label = normalizeTocLabel(link.textContent);
if (!wanted.has(label)) continue;
const fragment = /** @type {string} */ (link.getAttribute("href")).slice(1);
if (!/^chm-page-\d+$/.test(fragment)) continue;
if (!targets.has(label)) targets.set(label, new Set());
targets.get(label).add(fragment);
}
for (const entry of missing) {
const candidates = targets.get(normalizeTocLabel(entry.label));
if (candidates?.size !== 1) continue;
const fragment = candidates.values().next().value;
// The census already proves that exactly one descendant has this
// generated ID or name. Binding still chooses the target separately.
if (idCounts.get(fragment) === 1) entry.fragment = fragment;
}
};
// Only the normalized array produced for this manifest has stable chapter
// membership. Keep the scan for replacements and don't retain old arrays.
/** @type {WeakMap<unknown[], Map<number, ChapterTocEntry[]>>} */
const chapterTocIndex = new WeakMap();
/** @param {number} index */
const chapterTocEntries = index => {
const entries = readerContext.navigationState.tocEntries;
const byChapter = chapterTocIndex.get(entries);
return byChapter ? byChapter.get(index) || [] : entries.filter(
/** @returns {entry is ChapterTocEntry} */
entry => isChapterTocEntry(entry) && entry.chapterIndex === index);
};
const setChapterToc = () => {
const entries = (manifest.toc ?? manifest.chapters.map((item) => ({
title: ("title" in item && chapterOptionalText(item.title)) || `章节 ${item.index}`, chapter: item.index, depth: 0, fragment: ""
}))).map((item) => ({
label: item.title,
chapterIndex: item.chapter,
fragment: item.fragment,
depth: item.depth,
activate: (/** @type {number} */ generation) => activateChapter(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[item.chapter - 1]), generation, item.fragment)
}));
const normalized = readerContext.setToc(entries);
const current = readerContext.navigationState.tocEntries;
/** @type {Map<number, ChapterTocEntry[]> | null} */
const byChapter = current === normalized ? new Map() : null;
for (const entry of current.filter(isChapterTocEntry)) {
entry.activate = generation => activateChapter(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(entry.chapterIndex)), generation, entry);
if (!byChapter) continue;
const bucket = byChapter.get(entry.chapterIndex);
if (bucket) bucket.push(entry);
else byChapter.set(entry.chapterIndex, [entry]);
}
if (byChapter) chapterTocIndex.set(current, byChapter);
};
const chapterScheduler = VoiceOfMLReaderChapters.createChapterScheduler({
create: async (index, signal, priority) => {
const chapter = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(index));
readerContext.assertReaderActive();
const url = chapterUrl(chapter);
if (!url) throw new Error("EPUB_INVALID_PATH");
const result = await readerContext.fetchReaderUrl(url, { signal, priority }, {retryBucket:true});
if (!result.ok) throw new Error(`HTTP ${result.status}`);
const bytes = await VoiceOfMLReaderSecurity.readBytes(
result,
VoiceOfMLReaderSecurity.LIMITS.chapterBytes,
chapterBudget
);
let inserted = false;
try {
readerContext.assertReaderActive();
signal.throwIfAborted();
const doc = readerContext.parseChapterDocument(new TextDecoder().decode(bytes));
// Sanitization already visited the entire document. Only these nodes
// can need URL rewriting. Match namespaced SVG hrefs as well as
// literal xlink:href attributes in legacy HTML.
const elements = doc.querySelectorAll("[src], [*|href], [poster], [xlink\\:href], [srcset]");
let rewritten = 0, deadline = performance.now() + 8;
// Call only after a batch reaches the deadline; keep the abort checks
// on both sides of the actual task yield.
const yieldChapterWork = async () => {
signal.throwIfAborted();
readerContext.assertReaderActive();
await new Promise(resolve => setTimeout(resolve, 0));
signal.throwIfAborted();
readerContext.assertReaderActive();
deadline = performance.now() + 8;
};
for (const element of elements) {
for (const name of ["src", "href", "poster", "xlink:href"])
if (element.hasAttribute(name)) {
const value = element.getAttribute(name) || "";
if (name === "href" && element.localName === "a" &&
readerContext.trustedChapterReferenceUrl(value, url, manifestBase)) continue;
const resolved = resourceUrl(value, url);
if (resolved) element.setAttribute(name, resolved);
else if (!(name === "href" && value.startsWith("#"))) element.removeAttribute(name);
}
if (element.hasAttribute("srcset")) element.removeAttribute("srcset");
if (++rewritten % 256 === 0 && rewritten < elements.length && performance.now() >= deadline)
await yieldChapterWork();
}
signal.throwIfAborted();
readerContext.assertReaderActive();
const article = /** @type {HTMLElement & {_chapterSearchHead?: Node | null}} */ (document.createElement("article"));
article.className = "reader-markdown reader-epub-chapter";
article.dataset.chapter = String(chapter.index);
if (doc.body?.id) article.id = doc.body.id;
// The parser has already normalized and sanitized this HTML document.
// Import nodes directly rather than serializing and parsing the body again.
const children = doc.body?.childNodes;
let imported = 0;
if (children) for (const child of children) {
article.appendChild(document.importNode(child, true));
if (++imported % 256 === 0 && imported < children.length && performance.now() >= deadline)
await yieldChapterWork();
}
wrapEbookTables(article);
const images = article.querySelectorAll("img");
let prepared = 0;
for (const image of images) {
image.loading = priority === "high" ? "eager" : "lazy";
image.fetchPriority = priority;
image.decoding = "async";
if (++prepared % 256 === 0 && prepared < images.length && performance.now() >= deadline)
await yieldChapterWork();
}
// The generated text index includes head text (e.g. the chapter title).
article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;
signal.throwIfAborted();
readerContext.assertReaderActive();
insertChapter(article);
loaded.add(chapter.index);
retainedBytes.set(chapter.index, bytes.byteLength);
inserted = true;
const toc = chapterTocEntries(chapter.index);
if ("source_path" in chapter && /(?:^|\/)chm-fallback\.html$/.test(String(chapter.source_path)))
repairMergedChmToc(article, toc);
bindChapterTocTargets(article, toc);
const next = chapterAt(chapter.index + 1);
if (next) ensureSentinel(next);
const previous = chapterAt(chapter.index - 1);
if (previous) ensureSentinel(previous, true);
scheduleChapterWindow();
} catch (error) {
if (!inserted) chapterBudget.release(bytes.byteLength);
throw error;
}
}
});
/** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter @param {boolean} [exclusive] */
const fetchChapter = (chapter, exclusive = false) => {
readerContext.assertReaderActive();
if (loaded.has(chapter.index)) return Promise.resolve();
return chapterScheduler.load(chapter.index, true, exclusive).then(() => {
readerContext.chapterScrollAnchors.whenIdle(trimChapterWindow);
}).catch(error => {
if (error.name !== "AbortError" && !readerContext.readerAbortController.signal.aborted) {
const marker = ensureSentinel(chapter);
marker?.classList.add("reader-chapter-load-error");
marker?.removeAttribute("aria-hidden");
}
throw error;
});
};
/** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter @param {number} generation @param {string | {fragment?: string}} destination */
const activateChapter = async (chapter, generation, destination = "") => {
const finishOpeningJump = trackOpeningJump(generation);
let landed = false;
chapterFocusIndex = chapter.index;
navigationProtectionCleanup?.();
navigationTargetChapter = chapter.index;
chapterNavigating++;
let landingProtected = false;
try {
await fetchChapter(chapter, chapterWindowReady);
if (!readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
const node = frame.querySelector(`.reader-epub-chapter[data-chapter="${chapter.index}"]`);
const id = decodeChapterFragment(typeof destination === "string" ? destination : destination.fragment || "");
const anchor = chapterTarget(/** @type {Element} */ (node), id);
if (!anchor) throw new Error("EPUB_MISSING_ANCHOR");
readerContext.chapterScrollAnchors.invalidate();
// Measure the anchor instead of using scrollIntoView: the demanded landing line is
// this viewport's top edge, and scrollIntoView can also move ancestor scrollers.
readerContext.alignReaderDestination(anchor);
readerContext.chapterScrollAnchors.remember();
// Chapter images and lazy placeholders keep changing height after the jump; hold
// the anchor on the landing line until the layout settles.
readerContext.holdReaderDestination(anchor);
// Keep the demanded chapter out of the trim queue while its landing
// stabilizes. Scroll-anchoring and delayed images can otherwise mark a
// previous chapter as current and remove the destination mid-jump.
let timer = 0;
const unlock = () => {
clearTimeout(timer);
for (const name of ["wheel", "touchstart", "pointerdown", "keydown"])
readerContext.viewport.removeEventListener(name, unlock);
if (navigationTargetChapter === chapter.index) navigationTargetChapter = 0;
if (navigationProtectionCleanup === unlock) navigationProtectionCleanup = null;
};
navigationProtectionCleanup = unlock;
landingProtected = true;
for (const name of ["wheel", "touchstart", "pointerdown", "keydown"])
readerContext.viewport.addEventListener(name, unlock, { once: true, passive: true });
timer = setTimeout(unlock, 16000);
readerContext.syncHeadingLocation();
readerContext.updateProgressTools();
readerContext.scheduleSave();
landed = true;
return true;
} finally {
finishOpeningJump?.(landed);
chapterNavigating--;
if (!landingProtected && navigationTargetChapter === chapter.index && !navigationProtectionCleanup)
navigationTargetChapter = 0;
scheduleChapterWindow();
}
};
frame.addEventListener("click", async (event) => {
const link = /** @type {Element} */ (event.target).closest?.("a[href]");
const article = /** @type {HTMLElement | null | undefined} */ (link?.closest(".reader-epub-chapter"));
if (
!link || !article ||
event.button !== 0 ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.altKey
)
return;
const current = chapterAt(Number(article.dataset.chapter));
const destination = readerContext.trustedChapterReferenceUrl(link.getAttribute("href"), chapterUrl(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (current)), manifestBase);
const fragment = destination?.fragment || "";
const chapter = destination && chapterAtUrl(new URL(destination.url).href);
if (!chapter) {
// A stale or missing book document must not navigate out to an asset 404.
if (/\.(?:xhtml?|html?)(?:$|#)/i.test(link.getAttribute("href") || "")) {
event.preventDefault();
let message = link.nextElementSibling;
if (!message?.classList.contains("reader-chapter-link-error")) {
message = document.createElement("span");
message.className = "reader-chapter-link-error";
message.setAttribute("role", "status");
message.textContent = "(无法定位此书内链接)";
link.after(message);
}
}
return;
}
event.preventDefault();
const generation = readerContext.beginReaderNavigation();
try {
await activateChapter(chapter, generation, fragment);
} catch (error) {
readerContext.reportNavigationError(error, generation);
}
});
const chapterVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({
limit: 12,
getLoaded: () => [.../** @type {NodeListOf<HTMLElement & {_chapterSearchHead?: Node | null}>} */ (frame.querySelectorAll(":scope > .reader-epub-chapter"))],
getIndex: article => Number(article.dataset.chapter),
getHeight: article => article.getBoundingClientRect().height,
canVirtualize: article => {
if (Number(article.dataset.chapter) === navigationTargetChapter) return false;
const rect = article.getBoundingClientRect(), view = readerContext.viewport.getBoundingClientRect();
const selection = window.getSelection();
return (rect.bottom < view.top - 800 || rect.top > view.bottom + 800) &&
!article.contains(document.activeElement) &&
!article.querySelector("mark.full-search-highlight") &&
!(selection && !selection.isCollapsed &&
selection.containsNode(article, true));
},
virtualize: (article, index, height) => {
loaded.delete(index);
const marker = /** @type {HTMLButtonElement} */ (ensureSentinel(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(index))));
const style = getComputedStyle(article);
marker.classList.add("reader-chapter-placeholder");
marker.style.height = `${height}px`;
marker.style.marginTop = style.marginTop;
marker.style.marginBottom = style.marginBottom;
marker.setAttribute("aria-hidden", "true");
/** @type {IntersectionObserver} */ (readerContext.chapterManifestObserver).unobserve(article);
readerContext.chapterScrollAnchors.unobserve(article);
for (const entry of chapterTocEntries(index)) entry.target = null;
for (const image of article.querySelectorAll("img")) image.removeAttribute("src");
article.replaceWith(marker);
article._chapterSearchHead = null;
},
release: index => {
chapterBudget.release(retainedBytes.get(index));
retainedBytes.delete(index);
},
preserve: change => readerContext.chapterScrollAnchors.preserve(change)
});
function trimChapterWindow() {
if (chapterWindowReady && !chapterNavigating) chapterVirtualizer.trim(navigationTargetChapter || chapterFocusIndex);
}
function chapterPrefetchIndices() {
if (document.hidden) return [];
// A fixed opening prefix keeps extra front matter within the DOM retention target.
const forwardCount = Math.max(chapterPrefetchCount, chapterPrefetchMaxCount + 1 - chapterFocusIndex);
const nearby = manifest.chapters.slice(Math.max(0, chapterFocusIndex - 2),
chapterFocusIndex + forwardCount);
const indices = [];
let bytes = 0;
for (const chapter of nearby) {
bytes += chapterPrefetchSize(chapter);
if (chapter.index > chapterFocusIndex + chapterPrefetchCount && bytes > chapterPrefetchBytes) break;
if (!loaded.has(chapter.index)) indices.push(chapter.index);
}
return indices;
}
/** @param {number} top */
function chapterAtViewport(top) {
const marker = top + 80;
/** @type {{row: HTMLElement, top: number} | undefined} */
let next;
for (const row of /** @type {NodeListOf<HTMLElement>} */ (frame.querySelectorAll(":scope > [data-chapter]"))) {
const rect = row.getBoundingClientRect();
if (rect.top <= marker && rect.bottom > marker) return { row, top: rect.top };
if (!next && rect.top > top) next = { row, top: rect.top };
}
return next;
}
function refreshChapterWindow() {
chapterWindowFrame = 0;
if (!chapterWindowReady || readerContext.readerAbortController.signal.aborted) return;
const view = readerContext.viewport.getBoundingClientRect();
const current = chapterAtViewport(view.top);
if (current && !chapterNavigating) chapterFocusIndex = Number(current.row.dataset.chapter);
if (!chapterNavigating && current?.row.classList.contains("reader-chapter-sentinel") &&
current.top < view.bottom)
fetchChapter(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (chapterAt(chapterFocusIndex))).catch(() => {});
if (!chapterNavigating) chapterScheduler.prefetch(chapterPrefetchIndices());
readerContext.chapterScrollAnchors.whenIdle(trimChapterWindow);
}
function scheduleChapterWindow() {
if (!chapterWindowFrame) chapterWindowFrame = requestAnimationFrame(refreshChapterWindow);
}
function handleChapterVisibility() {
if (document.hidden) chapterScheduler.prefetch([]);
else scheduleChapterWindow();
}
readerContext.chapterManifestObserver = new IntersectionObserver(
scheduleChapterWindow,
{ root: readerContext.viewport, rootMargin: "800px 0px" }
);
chapterPreviousObserver = new IntersectionObserver((entries) => {
if (!chapterWindowReady || chapterNavigating || readerContext.readerAbortController.signal.aborted) return;
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const chapter = chapterAt(Number(/** @type {HTMLElement} */ (entry.target).dataset.chapter));
if (chapter) fetchChapter(chapter).catch(() => {});
}
}, { root: readerContext.viewport });
const viewport = readerContext.viewport;
const progressScroll = () => {
if (progressEnd && viewport.scrollHeight - viewport.clientHeight === progressEnd.limit &&
progressEnd.limit - viewport.scrollTop > 1) releaseProgressEnd();
scheduleChapterWindow();
};
const cancelProgressEnd = () => {
if (!isProgressEnd()) return;
releaseProgressEnd();
if (viewport.scrollHeight === viewport.clientHeight) readerContext.updateProgressTools();
};
const scrollIntents = ["wheel", "touchstart", "pointerdown", "keydown"];
for (const type of scrollIntents) viewport.addEventListener(type, cancelProgressEnd, { passive: true });
viewport.addEventListener("scroll", progressScroll, { passive: true });
window.addEventListener("resize", scheduleChapterWindow);
document.addEventListener("visibilitychange", handleChapterVisibility);
// Chapter arrivals, images and viewport reflow can change the reading marker
// without a scroll event. Refresh the display without loading any content.
const progressLayoutObserver = typeof ResizeObserver === "function"
? new ResizeObserver(() => {
if (progressEnd && isProgressEnd()) {
const limit = viewport.scrollHeight - viewport.clientHeight;
if (limit !== progressEnd.limit || limit - viewport.scrollTop > 1) {
progressEnd.limit = limit;
viewport.scrollTop = limit;
readerContext.chapterScrollAnchors.remember();
}
}
readerContext.updateProgressTools();
}) : null;
progressLayoutObserver?.observe(frame);
progressLayoutObserver?.observe(readerContext.viewport);
let chapterCleaned = false;
readerContext.chapterManifestCleanup = () => {
if (chapterCleaned) return;
chapterCleaned = true;
navigationProtectionCleanup?.();
chapterWindowReady = false;
cancelAnimationFrame(chapterWindowFrame);
viewport.removeEventListener("scroll", progressScroll);
for (const type of scrollIntents) viewport.removeEventListener(type, cancelProgressEnd);
window.removeEventListener("resize", scheduleChapterWindow);
document.removeEventListener("visibilitychange", handleChapterVisibility);
chapterScheduler.dispose();
chapterVirtualizer.dispose();
progressLayoutObserver?.disconnect();
readerContext.chapterManifestObserver?.disconnect();
chapterPreviousObserver?.disconnect();
readerContext.chapterManifestObserver = null;
readerContext.chapterManifestLoader = null;
trackOpeningSeek = null;
cancelOpeningJump();
releaseProgressEnd();
for (const bytes of retainedBytes.values()) chapterBudget.release(bytes);
retainedBytes.clear();
loaded.clear();
};
readerContext.trackReaderResource(readerContext.chapterManifestCleanup);
const chapterManifestLoader = async (/** @type {number} */ index) => {
const chapter = chapterAt(index);
if (!chapter) return null;
chapterFocusIndex = index;
chapterNavigating++;
try { await fetchChapter(chapter, chapterWindowReady); }
finally { chapterNavigating--; }
return /** @type {import("../../../typings/reader-chapter-format-strict").ChapterArticle | null} */ (
frame.querySelector(`.reader-epub-chapter[data-chapter="${index}"]`));
};
const progress = createChapterProgress(manifest.chapters);
chapterManifestLoader.count = manifest.chapters.length;
chapterManifestLoader.progressTarget = progress.locate;
chapterManifestLoader.progressFraction = () => {
const current = readChapterPosition();
if (!current) return 0;
const end = viewport.scrollHeight - viewport.clientHeight;
const atEnd = end === 0 ? isProgressEnd() : viewport.scrollTop > 0 && end - viewport.scrollTop <= 1;
if (atEnd && frame.querySelector(`:scope > :is(.reader-epub-chapter, .reader-chapter-placeholder)[data-chapter="${manifest.chapters.length}"]`))
return 1;
const { position, rect, marker } = current;
const span = chapterProgressHeight(rect, marker, position.chapterIndex === manifest.chapters.length);
const fraction = span > 0 ? Math.max(0, Math.min(1, position.chapterOffset / span)) : 0;
return progress.at(position.chapterIndex, fraction);
};
trackOpeningSeek = trackOpeningJump;
readerContext.chapterManifestLoader = chapterManifestLoader;
setChapterToc();
await readerContext.getInitialReaderRestoration();
const savedChapter = readerContext.readerRestorationEntry?.chapterIndex;
const hasSavedChapter = chapterIndexInRange(savedChapter, manifest.chapters.length);
const initialChapter = hasSavedChapter ? savedChapter - 1 : 0;
const initial = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter]);
chapterFocusIndex = initial.index;
if (initialChapter > 0) ensureSentinel(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter - 1]), true);
try {
const firstChapter = fetchChapter(initial).catch(async error => {
// If an explicit destination is still resolving, give it the chance
// to take ownership before treating an obsolete chapter as fatal.
while (pendingOpeningJump) await pendingOpeningJump;
throw error;
});
chapterScheduler.prefetch(chapterPrefetchIndices());
await readerContext.awaitReader(Promise.race([firstChapter, openingLanding.promise]));
} catch (error) {
if (!hasSavedChapter) throw error;
throw Object.assign(new Error("阅读位置恢复失败,原进度已保留,请重试加载。", { cause: error }), {
code: "READER_RESTORE"
});
}
chapterWindowReady = true;
trackOpeningSeek = null;
cancelOpeningJump();
if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate();
for (const row of frame.children)
if (row.classList.contains("reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(row);
scheduleChapterWindow();
readerContext.assertReaderActive();
readerContext.markReaderContentReady();
readerContext.status.textContent = `EPUB · ${manifest.chapters.length} 章`;
}
function readChapterPosition() {
if (readerContext.capability.mode !== "epub-chapters") return null;
const marker = readerContext.viewport.getBoundingClientRect().top + markerInset;
// A trimmed row retains the measured height of its original chapter.
// Count it for snapshots as well as the slider, but not unloaded sentinels.
const chapters = /** @type {NodeListOf<HTMLElement>} */ (readerContext.content.querySelectorAll(
".epub-frame > :is(.reader-epub-chapter, .reader-chapter-placeholder)"));
let chapter = null, rect = null;
for (const node of chapters) {
chapter = node;
rect = node.getBoundingClientRect();
if (rect.bottom > marker) break;
}
return chapter && rect ? {
position: {
chapterIndex: Number(chapter.dataset.chapter),
chapterManifest: readerContext.chapterManifestUrl || readerContext.sourceUrl,
chapterOffset: marker - rect.top
}, rect, marker
} : null;
}
function captureChapterPosition() {
return readChapterPosition()?.position ?? null;
}
/** @param {import("../../../typings/reader-progress-strict").ProgressState} entry @param {number} generation
* @param {number} [progressFraction] A transient slider target, never stored in a bookmark or history entry. */
async function restoreChapterPosition(entry, generation, progressFraction) {
const loader = readerContext.chapterManifestLoader;
if (!loader || !chapterIndexInRange(entry.chapterIndex, loader.count) ||
!readerContext.isReaderGenerationCurrent("navigation", generation) ||
!matchesChapterManifest(entry.chapterManifest, readerContext.chapterManifestUrl || readerContext.sourceUrl,
readerContext.trustedReaderAssetManifestUrl)) return false;
// Only a deliberate progress seek can replace the startup chapter, not saved-state restoration.
const finishOpeningJump = progressFraction === undefined ? null : trackOpeningSeek?.(generation);
let landed = false;
try {
const chapter = await loader(entry.chapterIndex);
if (!chapter?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
const viewport = readerContext.viewport, last = entry.chapterIndex === loader.count;
releaseProgressEnd();
if (progressFraction === 0 && entry.chapterIndex === 1) viewport.scrollTop = 0;
else if (progressFraction === 1 && last) {
const limit = viewport.scrollHeight - viewport.clientHeight;
progressEnd = { generation, limit };
viewport.scrollTop = limit;
} else {
const rect = chapter.getBoundingClientRect(), marker = viewport.getBoundingClientRect().top + markerInset;
const offset = progressFraction === undefined ? Number(entry.chapterOffset) || 0
: chapterProgressHeight(rect, marker, last) * progressFraction;
viewport.scrollTop += rect.top - marker + offset;
}
readerContext.chapterScrollAnchors.remember();
readerContext.syncHeadingLocation();
readerContext.updateProgressTools();
readerContext.scheduleSave();
landed = true;
return true;
} finally {
finishOpeningJump?.(landed);
}
}
return {
renderChapterManifest,
captureChapterPosition,
restoreChapterPosition
};
}
|