File size: 45,122 Bytes
6c8fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dc63a4
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
 
49a03ba
 
822b94b
49a03ba
 
 
822b94b
 
 
 
 
 
 
49a03ba
 
 
 
822b94b
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
 
 
49a03ba
 
 
dac2ca2
49a03ba
 
 
 
 
 
 
 
 
 
86eb73d
49a03ba
 
 
 
 
86eb73d
49a03ba
 
 
 
 
 
 
 
 
f03af42
 
 
9c77549
 
 
 
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
a2d9f99
 
822b94b
 
49a03ba
 
 
822b94b
49a03ba
a2d9f99
49a03ba
 
 
6c8fd46
 
 
 
 
 
 
 
 
 
49a03ba
 
 
6c8fd46
 
 
 
 
 
 
49a03ba
 
 
 
 
 
 
 
 
dac2ca2
49a03ba
 
 
 
6c8fd46
 
 
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac2ca2
 
49a03ba
dac2ca2
822b94b
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472fce5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
472fce5
49a03ba
 
082debe
a59751e
472fce5
 
 
 
 
86f0df6
472fce5
 
 
 
dac2ca2
a59751e
 
49a03ba
a2d9f99
a59751e
 
 
 
 
 
49a03ba
 
a59751e
49a03ba
 
6c8fd46
 
 
 
 
 
 
 
49a03ba
061d92e
 
49a03ba
 
 
6c8fd46
49a03ba
 
a2d9f99
86eb73d
49a03ba
 
 
 
86eb73d
49a03ba
 
86eb73d
dac2ca2
49a03ba
 
 
 
 
 
 
 
 
 
6c8fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
 
 
 
dac2ca2
49a03ba
 
 
dac2ca2
49a03ba
 
 
 
 
 
d101ec0
 
 
822b94b
d101ec0
 
 
 
 
6c8fd46
d101ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
d101ec0
 
 
 
 
 
 
 
 
49a03ba
 
 
4468c93
 
49a03ba
 
 
 
 
dac2ca2
 
86eb73d
49a03ba
58d59b4
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58d59b4
49a03ba
 
86eb73d
49a03ba
 
 
822b94b
49a03ba
822b94b
49a03ba
 
 
58d59b4
 
49a03ba
58d59b4
49a03ba
 
 
 
 
 
 
 
 
 
 
822b94b
49a03ba
 
 
 
822b94b
49a03ba
 
822b94b
49a03ba
 
86eb73d
49a03ba
86eb73d
49a03ba
86eb73d
 
49a03ba
 
 
 
 
 
 
 
ae3a71a
 
 
 
49a03ba
 
 
 
 
 
 
bef5045
49a03ba
 
 
86eb73d
dac2ca2
49a03ba
86eb73d
49a03ba
 
 
dac2ca2
49a03ba
 
 
 
 
 
6853944
 
 
 
 
 
 
 
 
 
 
49a03ba
 
 
a2d9f99
49a03ba
 
 
472fce5
49a03ba
01ab508
 
 
 
 
 
 
 
 
 
bef5045
49a03ba
 
bef5045
 
49a03ba
 
 
 
 
 
bef5045
49a03ba
 
 
 
 
 
472fce5
 
49a03ba
472fce5
49a03ba
86eb73d
9c77549
dac2ca2
49a03ba
dac2ca2
49a03ba
 
 
6c8fd46
49a03ba
 
 
 
 
 
 
 
 
822b94b
 
49a03ba
822b94b
49a03ba
 
 
 
 
822b94b
 
3d9c6b7
 
 
 
 
 
 
 
 
56b51ea
49a03ba
 
 
 
 
822b94b
 
49a03ba
 
 
 
 
 
 
 
 
822b94b
49a03ba
 
 
 
 
 
822b94b
49a03ba
 
 
 
 
 
 
 
 
 
 
822b94b
49a03ba
822b94b
49a03ba
 
 
0c9b4f9
 
 
 
e9506ad
 
0c9b4f9
 
e9506ad
0c9b4f9
 
 
e9506ad
 
 
 
0c9b4f9
e9506ad
 
 
ae3a71a
 
 
e9506ad
 
 
ae3a71a
822b94b
49a03ba
 
822b94b
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcef7e9
dac2ca2
49a03ba
 
 
 
 
 
 
822b94b
 
49a03ba
 
 
 
 
 
 
67cbd61
9c77549
6c8fd46
49a03ba
67cbd61
9c77549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
9c77549
49a03ba
6c8fd46
 
 
 
 
 
49a03ba
9c77549
67cbd61
49a03ba
 
9c77549
49a03ba
9c77549
49a03ba
 
 
 
 
9c77549
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
 
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
/** @param {HTMLElement} viewport @param {(event: Event) => void} onIntent */
export function bindReaderScrollIntent(viewport, onIntent) {
  /** @type {{id: number, y: number} | null} */
  let touch = null;
  viewport.addEventListener("wheel", (event) => {
    if (event.deltaY && !event.ctrlKey) onIntent(event);
  }, { passive: true });
  viewport.addEventListener("touchstart", (event) => {
    const start = event.touches.length === 1 ? event.touches[0] : null;
    touch = start ? { id: start.identifier, y: start.clientY } : null;
  }, { passive: true });
  viewport.addEventListener("touchmove", (event) => {
    const move = event.touches.length === 1 ? event.touches[0] : null;
    if (touch && move?.identifier === touch.id && Math.abs(move.clientY - touch.y) > 8) {
      touch = null;
      onIntent(event);
    }
  }, { passive: true });
  for (const type of ["touchend", "touchcancel"])
    viewport.addEventListener(type, () => { touch = null; }, { passive: true });
  viewport.addEventListener("pointerdown", (event) => {
    // Body taps and selection starts are not navigation. Keep scrollbar and
    // middle-button autoscroll intent when the browser delivers these events.
    if (event.pointerType !== "mouse") return;
    const x = event.clientX - viewport.getBoundingClientRect().left - viewport.clientLeft;
    if (event.button === 1 || (event.button === 0 && event.target === viewport &&
        viewport.scrollHeight > viewport.clientHeight && (x < 0 || x >= viewport.clientWidth))) onIntent(event);
  }, { passive: true });
}

/** @param {import('../../../typings/reader-bindings-strict').ReaderBindingsContext} readerContext */
export function createReaderBindings(readerContext) {
  function trackStartupOwners() {
    readerContext.readerRuntime.track(readerContext.readerRequestManager);
    readerContext.readerRuntime.track(readerContext.formatAdapters);
    readerContext.readerRuntime.track(window.__VOICE_PDF_PRELOAD__);
    readerContext.readerRuntime.track(window.__VOICE_READER_CHAPTER_PRELOAD__);
  }

  function publishDiagnosticsAndInstallCompatibility() {
    window.VoiceOfMLReaderPdfDiagnostics = readerContext.pdfDiagnostics;
    readerContext.trackReaderResource(() => {
      readerContext.pdfPageTimings.length = 0;
      if (window.VoiceOfMLReaderPdfDiagnostics === readerContext.pdfDiagnostics) delete window.VoiceOfMLReaderPdfDiagnostics;
    });

    // Polyfills for pdf.js: neither helper has a direct
    // caller in first-party code, but both are required by pinned vendor bundles.
    if (!Map.prototype.getOrInsertComputed) {
      Map.prototype.getOrInsertComputed = function (key, callback) {
        if (this.has(key)) return this.get(key);
        const value = callback(key);
        this.set(key, value);
        return value;
      };
    }
    if (!Math.sumPrecise) {
      Math.sumPrecise = function (values) {
        let sum = 0;
        let correction = 0;
        for (const value of values) {
          const next = sum + value;
          correction += Math.abs(sum) >= Math.abs(value) ? sum - next + value : value - next + sum;
          sum = next;
        }
        return sum + correction;
      };
    }
  }

  function readSelectedSourceSession() {
    try {
      const value = /** @type {unknown} */ (JSON.parse(sessionStorage.getItem(`reader-source:${readerContext.readerId}`) || "null"));
      readerContext.localReaderData = value && typeof value === "object" && !Array.isArray(value) ? /** @type {Record<string, unknown>} */ (value) : null;
      if (readerContext.localReaderData) sessionStorage.removeItem(`reader-source:${readerContext.readerId}`);
    } catch (_) {}
    return readerContext.localReaderData;
  }

  function applySourceSessionAndCachedMetadata() {
    const source = readerContext.localReaderData;
    if (source && typeof source === "object") {
      if ("title" in source && source.title) readerContext.params.set("title", String(source.title));
      if ("repo" in source && source.repo) {
        const folder = "folder" in source ? source.folder : null;
        readerContext.params.set("path", [source.repo, ...(Array.isArray(folder) || typeof folder === "string" ? folder : [])].join("/"));
      }
    }
    try {
      const cached = sessionStorage.getItem(`reader-resolve:${readerContext.readerId}`);
      if (cached) {
        const value = /** @type {unknown} */ (JSON.parse(cached));
        readerContext.cachedReaderData = value && typeof value === "object" && !Array.isArray(value) ? /** @type {Record<string, unknown>} */ (value) : null;
        readerContext.resolvedReaderData = readerContext.cachedReaderData;
        sessionStorage.removeItem(`reader-resolve:${readerContext.readerId}`);
      }
    } catch (_) {}
  }

  function publishSourceAndSubscribeToStore() {
    readerContext.readerRuntime.update("source", {
      id: readerContext.readerId,
      url: readerContext.sourceUrl,
      contentUrl: readerContext.contentUrl,
      downloadUrl: readerContext.downloadUrl,
      extension: readerContext.extension,
      metadata: readerContext.resolvedReaderData
    });
    readerContext.readerRuntime.events.on("phase", (detail) => {
      if (detail && typeof detail === "object" && "phase" in detail && typeof detail.phase === "string")
        document.documentElement.dataset.readerPhase = detail.phase;
    });
    readerContext.readerRuntime.track(
      VoiceOfMLReaderStore.subscribe?.((change) => {
        if (!change?.remote || typeof change.type !== "string" || readerContext.readerLifecycle.disposed) return;
        if (
          change.type === "history-clear" ||
          (change.type === "history-remove" && change.url === readerContext.sourceUrl)
        ) {
          readerContext.historySuppressed = true;
          readerContext.readerRuntime.cancel(readerContext.saveTimer);
          readerContext.saveTimer = readerContext.saveDeadline = 0;
        }
        if (
          ["history", "history-clear", "history-remove"].includes(change.type) &&
          !/** @type {HTMLElement} */ (document.querySelector("#history-panel")).hidden
        )
          readerContext.renderHistory();
        if (
          ["bookmark", "bookmark-remove"].includes(change.type) &&
          (readerContext.panelState.showingAllBookmarks || !change.url || change.url === readerContext.sourceUrl) &&
          !/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden
        )
          readerContext.renderBookmarks();
      })
    );

    readerContext.setReaderPhase("startup");
  }

  function initializePanelAccessibility() {
    document.querySelectorAll('.reader-toolbar svg, #history-panel > header svg').forEach(node => {
      node.setAttribute('aria-hidden', 'true'); node.setAttribute('focusable', 'false');
    });
    document.querySelector(".reader-skip-link")?.addEventListener("click", (event) => {
      event.preventDefault();
      readerContext.setReaderPanelOpen(false);
      readerContext.viewport.focus({ preventScroll: true });
    });
  }

  function mountInitialLoadingFeedback() {
    readerContext.loadingIndicator.className = "reader-loading-indicator";
    readerContext.loadingIndicator.setAttribute("role", "status");
    readerContext.loadingIndicator.innerHTML =
      '<span class="reader-loading-spinner" aria-hidden="true"></span><span>正在加载正文...</span>';
    readerContext.content.appendChild(readerContext.loadingIndicator);
    readerContext.content.dataset.mode = readerContext.capability.mode || "unsupported";
  }

  function initializeDocumentTitle() {
    let savedZoom = null;
    try { savedZoom = localStorage.getItem("reader-zoom"); } catch (_) {}
    const source = readerContext.localReaderData;
    const localTitle = source && typeof source === "object" && "title" in source ? source.title : null;
    readerContext.updateDocumentState({
      title:
        String(
          readerContext.params.get("title") || localTitle || readerContext.sourceName
        ).trim() || readerContext.sourceName,
      zoom: Math.min(4, Math.max(0.25, Number(savedZoom || 100) / 100))
    });
  }

  let ownsReloadedOverlayEntry = false;

  /** @param {URL} url */
  function isSearchReturn(url) {
    // Space uses the root and single-segment repository routes.
    const parts = url.pathname.split("/").filter(Boolean);
    return url.origin === location.origin && !url.username && !url.password &&
      parts.length <= 1 && !["static", "api", "reader", "reader.html"].includes(parts[0] ?? "");
  }

  function restoreReturnNavigation() {
    try {
      const state = history.state;
      const entryUrl = state?.voiceReaderOverlay && typeof state.readerUrl === "string" ? state.readerUrl : "";
      let stateUrl = entryUrl ? new URL(entryUrl, location.origin) : null;
      if (!stateUrl) {
        const saved = JSON.parse(sessionStorage.getItem("reader-navigation-current") || "null");
        if (saved?.shareUrl === location.href && saved.readerUrl)
          stateUrl = new URL(saved.readerUrl, location.origin);
      }
      const cleanStateUrl = stateUrl && new URL(stateUrl.href);
      if (cleanStateUrl) {
        cleanStateUrl.searchParams.delete("return");
        cleanStateUrl.searchParams.delete("nav");
      }
      if (
        stateUrl &&
        stateUrl.origin === location.origin &&
        stateUrl.pathname === "/static/reader.html" &&
        /** @type {URL} */ (cleanStateUrl).href === location.href
      ) {
        if (!readerContext.returnUrl) readerContext.returnUrl = stateUrl.searchParams.get("return") || "";
        if (!readerContext.returnNavigationToken) readerContext.returnNavigationToken = stateUrl.searchParams.get("nav") || "";
        readerContext.returnNeedsReload = true;
        // Session-only restoration (e.g. a copied tab) cannot prove the
        // browser has a prior search entry. Keep the replace fallback there.
        ownsReloadedOverlayEntry = !!entryUrl && window === window.top && typeof state.searchUrl === "string" &&
          isSearchReturn(new URL(state.searchUrl, location.origin));
      }
    } catch (_) {}
  }

  function validateReturnHistory() {
    try {
      const target = new URL(readerContext.returnUrl, location.origin);
      const storedReturnUrl = readerContext.returnHistoryKey ? sessionStorage.getItem(readerContext.returnHistoryKey) : "";
      readerContext.canReturnWithHistory = !!readerContext.returnHistoryKey && storedReturnUrl === target.href;
    } catch (_) {}
  }

  function ownChapterSearchClient() {
    readerContext.trackReaderResource(() => {
      readerContext.chapterSearchClient?.dispose();
      readerContext.chapterSearchClient = null;
    });
  }

  function ownIndependentPdfResources() {
    readerContext.trackReaderResource(() => {
      readerContext.pdfV3Repository?.dispose(); readerContext.pdfTextLayerRepository?.dispose();
    });
  }

  function ownPdfBookSearchClient() {
    readerContext.trackReaderResource(() => {
      readerContext.pdfBookSearchClient?.dispose();
      readerContext.pdfBookSearchClient = null;
      clearTimeout(readerContext.pdfBookSearchPrefetchTimer);
      readerContext.pdfBookSearchPrefetchTimer = 0;
      readerContext.pdfBookSearchPrefetchPromise = null;
    });
  }

  function ownPdfPrefetchAndQueues() {
    readerContext.trackReaderResource(readerContext.clearPdfManifestPrefetches);
    readerContext.trackReaderResource(() => {
      for (const waiter of readerContext.pdfRenderWaiters.splice(0)) waiter.reject(readerContext.readerAbortError());
      for (const waiter of readerContext.pdfTextWaiters.splice(0)) waiter.reject(readerContext.readerAbortError());
    });
  }

  function initializeGenerations() {
    for (const generationName of ["navigation", "search", "bookmarks", "history", "pdf"])
      readerContext.nextReaderGeneration(generationName);
  }

  function mountMediaPanel() {
    readerContext.mediaTab.id = "media-tab";
    readerContext.mediaTab.type = "button";
    readerContext.mediaTab.role = "tab";
    readerContext.mediaTab.dataset.panel = "media";
    readerContext.mediaTab.textContent = "播放";
    readerContext.mediaPanel.id = "media-panel";
    readerContext.mediaPanel.className = "reader-panel-view";
    readerContext.mediaPanel.dataset.panelView = "media";
    readerContext.mediaPanel.hidden = true;
    readerContext.mediaPanel.innerHTML =
      '<div class="media-panel-content"><strong>播放状态</strong><span class="media-panel-time">尚未播放</span><button class="text-action media-panel-bookmark" type="button">在当前时间添加书签</button></div>';
    /** @type {Element} */ (document.querySelector(".reader-panel-tabs")).prepend(readerContext.mediaTab);
    /** @type {Element} */ (document.querySelector("#history-panel"))
      .insertBefore(readerContext.mediaPanel, document.querySelector("#toc-panel"));
    /** @type {Element} */ (readerContext.mediaPanel.querySelector(".media-panel-bookmark"))
      .addEventListener("click", (event) => readerContext.openBookmarkPopover(event.currentTarget instanceof HTMLElement ? event.currentTarget : undefined));
    readerContext.mediaTab.setAttribute("aria-controls", "media-panel");
    readerContext.mediaTab.setAttribute("aria-selected", "false");
    readerContext.mediaPanel.setAttribute("role", "tabpanel");
    readerContext.mediaPanel.setAttribute("aria-labelledby", "media-tab");
  }

  function restoreAndBindPageInversion() {
    try { readerContext.pageInverted = localStorage.getItem("reader-page-inversion") === "true"; } catch (_) {}

    readerContext.pageInvertToggle.addEventListener("click", () => {
      readerContext.pageInverted = !readerContext.pageInverted;
      readerContext.applyPageInversion(true);
    });
    readerContext.applyPageInversion();
  }

  /** @param {string | null} theme @param {boolean} [resume] */
  function syncReaderTheme(theme, resume = false) {
    const next = theme === "light" ? "light" : "dark";
    if (next !== readerContext.readerTheme || (resume && document.documentElement.classList.contains("theme-transition"))) {
      readerContext.applyReaderTheme(next, false, false);
    }
  }

  /** @param {boolean} [resume] */
  function syncStoredReaderTheme(resume = false) {
    try { syncReaderTheme(localStorage.getItem("theme"), resume); } catch (_) {}
  }

  function activeReaderTheme() {
    // The Search shell also owns the first frame of embedded Readers when
    // storage is unavailable or the preference changes during module loading.
    try {
      if (window.parent !== window) {
        const theme = window.parent.document.documentElement.dataset.theme;
        if (theme === "light" || theme === "dark") return theme;
      }
    } catch (_) {}
    try { return localStorage.getItem("theme") === "light" ? "light" : "dark"; }
    catch (_) { return readerContext.readerTheme; }
  }

  function restoreReaderThemeAndBindReturn() {
    readerContext.applyReaderTheme(activeReaderTheme(), false, false);

    readerContext.readerPath.addEventListener("click", readerContext.navigateReaderFolder);
    document.querySelector("#reader-panel-path")?.addEventListener("click", readerContext.navigateReaderFolder);
    let closing = false;
    window.addEventListener("pageshow", event => {
      if (!event.persisted) return;
      closing = false;
      syncStoredReaderTheme(true);
    });
    // A parked speech iframe is shown again without a document navigation.
    window.addEventListener("voice-reader-overlay-resume", () => {
      closing = false;
      syncReaderTheme(activeReaderTheme(), true);
    });
    /** @type {Element} */ (document.querySelector("#back")).addEventListener("click", async () => {
      if (closing) return;
      closing = true;
      clearTimeout(readerContext.saveTimer);
      if (readerContext.isReaderOverlayFrame()) {
        const progress = readerContext.captureProgressEntry();
        if (progress) {
          readerContext.lastSavedProgress = JSON.stringify(progress);
          progress.closeTime = Date.now();
        }
        window.parent.postMessage({ type: "voice-reader-close", progress }, location.origin);
        return;
      }
      await Promise.race([readerContext.saveProgress(), new Promise((resolve) => setTimeout(resolve, 300))]);
      try {
        const target = new URL(readerContext.returnUrl, location.origin);
        if (isSearchReturn(target)) {
          if (ownsReloadedOverlayEntry && readerContext.canReturnWithHistory && history.length > 1) {
            // The trusted popstate loads the arrived search document. Keep the
            // session handoff and the Reader entry for native Forward.
            history.back();
            return;
          }
          readerContext.clearReturnNavigation();
          if (readerContext.returnNeedsReload) location.replace(target.href);
          else if (readerContext.canReturnWithHistory && history.length > 1) history.back();
          else location.assign(target.href);
          return;
        }
      } catch (_) {}
      readerContext.clearReturnNavigation();
      location.assign("/");
    });
    // Replay a Back tap made before this handler was bound.
    if (window.__VOICE_READER_EARLY_BACK__?.()) /** @type {HTMLButtonElement} */ (document.querySelector("#back")).click();
  }

  function bindZoomAndPageControls() {
    readerContext.setZoom(readerContext.documentState.zoom * 100, false);
    for (const [id, delta] of /** @type {[string, number][]} */ ([
      ["#zoom-out", -10],
      ["#zoom-in", 10]
    ])) {
      /** @type {Element} */ (document.querySelector(id)).addEventListener("click", () => {
        readerContext.setZoom(Number(readerContext.zoomInput.value) + delta);
      });
    }
    readerContext.zoomInput.addEventListener("change", () => readerContext.setZoom(readerContext.zoomInput.value));
    readerContext.zoomInput.addEventListener("keydown", (event) => {
      if (event.key === "Enter") {
        readerContext.setZoom(readerContext.zoomInput.value);
        readerContext.zoomInput.blur();
      }
    });
    const pageInput = readerContext.pageInput;
    let edited = false, commit = 0, pending = false;
    const syncPageInput = () => { pageInput.value = String(readerContext.documentState.page); };
    const commitPageInput = () => {
      if (!edited) {
        if (!pending) syncPageInput();
        return;
      }
      edited = false;
      const typed = pageInput.valueAsNumber;
      if (!readerContext.documentState.pageCount || !Number.isFinite(typed)) {
        syncPageInput();
        return;
      }
      const request = ++commit;
      pending = true;
      void readerContext.goToPage(typed).then(() => {
        if (request !== commit) return;
        pending = false;
        if (!edited) syncPageInput();
      });
    };
    pageInput.addEventListener("input", () => { edited = true; });
    pageInput.addEventListener("change", commitPageInput);
    pageInput.addEventListener("blur", commitPageInput);
    pageInput.addEventListener("keydown", (event) => {
      if (event.key === "Enter" && !event.isComposing) {
        event.preventDefault();
        commitPageInput();
        pageInput.blur();
      }
    });

    document.addEventListener("keydown", readerContext.handleReaderKeydown);
    /** @type {Element} */ (document.querySelector("#page-prev"))
      .addEventListener("click", () =>
        readerContext.documentState.pageCount ? readerContext.goToPage(readerContext.documentState.page - 1) : readerContext.turnViewport(-1)
      );
    /** @type {Element} */ (document.querySelector("#page-next"))
      .addEventListener("click", () =>
        readerContext.documentState.pageCount ? readerContext.goToPage(readerContext.documentState.page + 1) : readerContext.turnViewport(1)
      );
  }

  function bindReaderUiHistory() {
    if (window !== window.top) return;
    const readerUrl = location.href;
    let loadingSearch = false;
    /** @param {PopStateEvent} event */
    const restoreSearchDocument = (event) => {
      if (!event.isTrusted || loadingSearch || readerContext.readerLifecycle.disposed) return;
      // Reloading an overlay URL creates a standalone Reader document which can
      // still own the preceding same-document search entries. Back changes the
      // URL/state first; load THAT document without another traversal or rewrite.
      if (!isSearchReturn(new URL(location.href))) return;
      loadingSearch = true;
      try {
        sessionStorage.removeItem("reader-navigation-restore");
        const saved = JSON.parse(sessionStorage.getItem("reader-navigation-current") || "null");
        if (saved?.shareUrl === readerUrl && saved.readerUrl) {
          const source = new URL(saved.readerUrl, location.origin);
          const returnUrl = source.searchParams.get("return");
          const token = source.searchParams.get("nav");
          if (source.origin === location.origin && returnUrl === location.href && token &&
              sessionStorage.getItem(`reader-return:${token}`) === returnUrl) {
            // The host saves focus/scroll before mounting. The app consumes this
            // handoff after loading results; it is not a history-entry identity.
            sessionStorage.setItem("reader-navigation-restore", JSON.stringify({
              readerUrl: saved.readerUrl, returnUrl
            }));
          }
        }
      } catch (_) {}
      location.reload();
    };
    /** @param {PageTransitionEvent} event */
    const resume = (event) => { if (event.persisted) loadingSearch = false; };
    window.addEventListener("popstate", restoreSearchDocument);
    window.addEventListener("pageshow", resume);
    // A failed book load stops book work but leaves this document's error UI
    // alive. Keep browser navigation until the document/runtime is disposed.
    readerContext.readerRuntime.track(() => {
      window.removeEventListener("popstate", restoreSearchDocument);
      window.removeEventListener("pageshow", resume);
    });
  }

  function bindPanelBookmarkAndLifecycleControls() {
    document.addEventListener("click", readerContext.handleReaderOutsideClick);
    readerContext.trackReaderResource(() => document.removeEventListener("click", readerContext.handleReaderOutsideClick));
    readerContext.trackReaderResource(() => { readerContext.headingLocationCache?.dispose(); readerContext.headingLocationCache = null; });

    // Bookmark dialog owns focus and temporarily makes only its siblings inert.

    readerContext.bookmarkRibbon.addEventListener("click", () => readerContext.openBookmarkPopover(readerContext.bookmarkRibbon));
    /** @type {Element} */ (document.querySelector("#bookmark-cancel")).addEventListener("click", readerContext.closeBookmarkPopover);
    /** @type {Element} */ (document.querySelector("#bookmark-add")).addEventListener("click", async (event) => {
      const button = /** @type {HTMLButtonElement} */ (event.currentTarget),
        editing = readerContext.panelState.editingBookmark;
      const saveGeneration = readerContext.nextReaderGeneration("bookmark-dialog");
      const ownsDialog = () => readerContext.isReaderGenerationCurrent("bookmark-dialog", saveGeneration);
      const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();
      const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,
        excerpt = readerContext.bookmarkExcerptInput.value.trim();
      button.disabled = true;
      try {
        await VoiceOfMLReaderStore.putBookmark(
          editing
            ? { ...editing, label, excerpt }
            : {
                ...snapshot,
                id: `${readerContext.sourceUrl}\0${snapshot.locator}`,
                url: readerContext.sourceUrl,
                title: readerContext.documentState.title,
                extension: readerContext.extension,
                readerUrl: readerContext.currentReaderUrl().href,
                label,
                excerpt,
                createdAt: Date.now()
              }
        );
        if (!ownsDialog()) return;
        const invoker = readerContext.bookmarkInvoker;
        readerContext.closeBookmarkPopover();
        if (!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden) {
          await readerContext.renderBookmarks();
          if (editing && invoker && !invoker.isConnected && document.activeElement === document.body)
            (
              /** @type {HTMLElement} */ (document.querySelector(
                `#bookmarks-list [data-bookmark-id="${CSS.escape(editing.id)}"] .panel-item-edit`
              )) || readerContext.bookmarksAllButton
            ).focus();
        }
      } catch (_) {
        if (ownsDialog())
          /** @type {Element} */ (document.querySelector("#bookmark-prompt")).textContent = "书签保存失败,请重试。";
      } finally {
        if (ownsDialog()) button.disabled = false;
      }
    });
    readerContext.bookmarkPopover.addEventListener("keydown", (event) => {
      if (event.key === "Escape") {
        event.preventDefault();
        readerContext.closeBookmarkPopover();
        return;
      }
      if (event.key !== "Tab") return;
      const controls = [
        ...readerContext.bookmarkPopover.querySelectorAll("input,textarea,select,button,a[href],[tabindex]")
      ].filter((node) => !/** @type {HTMLButtonElement} */ (node).disabled && /** @type {HTMLElement} */ (node).tabIndex >= 0 && node.getClientRects().length);
      const first = controls[0],
        last = controls[controls.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        /** @type {HTMLElement} */ (last).focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        /** @type {HTMLElement} */ (first).focus();
      }
    });
    for (const button of /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll(".reader-panel-tabs button")))
      button.addEventListener("click", () => readerContext.selectPanel(button.dataset.panel));
    /** @type {HTMLElement} */ (document.querySelector(".reader-panel-tabs")).addEventListener("keydown", (event) => {
      if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
      const tabs = [.../** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll(".reader-panel-tabs button:not([hidden])"))],
        current = tabs.findIndex(tab => tab === document.activeElement);
      if (current < 0) return;
      event.preventDefault();
      const next =
        event.key === "Home"
          ? 0
          : event.key === "End"
            ? tabs.length - 1
            : (current + (event.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length;
      const target = tabs[next];
      if (!target) return;
      readerContext.selectPanel(target.dataset.panel);
      target.focus();
    });
    readerContext.bookmarksAllButton.addEventListener("click", () => {
      readerContext.updatePanelState({ showingAllBookmarks: !readerContext.panelState.showingAllBookmarks });
      readerContext.bookmarksAllButton.textContent = readerContext.panelState.showingAllBookmarks ? "本书书签" : "全部书签";
      readerContext.bookmarksAllButton.setAttribute("aria-pressed", String(readerContext.panelState.showingAllBookmarks));
      readerContext.renderBookmarks();
    });
    for (const button of /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll(".panel-search-toggle")))
      button.addEventListener("click", () =>
        readerContext.setPanelSearchOpen(button, button.getAttribute("aria-expanded") !== "true")
      );
    for (const input of /** @type {NodeListOf<HTMLInputElement>} */ (document.querySelectorAll(".panel-search"))) {
      const view = /** @type {Element} */ (input.closest(".reader-panel-view"));
      input.addEventListener("input", (event) => {
        if (!/** @type {InputEvent} */ (event).isComposing) readerContext.filterPanel(view);
      });
      input.addEventListener("compositionend", () => readerContext.filterPanel(view));
    }
    /** @type {Element} */ (document.querySelector("#history-clear")).addEventListener("click", async () => {
      if (!confirm("清空全部阅读历史?")) return;
      readerContext.historySuppressed = true;
      await readerContext.progressSaveChain;
      await VoiceOfMLReaderStore.clearHistory();
      readerContext.renderHistory();
    });
    // A close snapshot can fail after the iframe has been detached, so report
    // a full history proactively without blocking Reader startup or closing.
    try {
      Promise.resolve(VoiceOfMLReaderStore.isHistoryFull?.()).then((full) => {
        if (!full || readerContext.readerLifecycle.disposed) return;
        return VoiceOfMLReaderStore.get(readerContext.sourceUrl).then((entry) => {
          if (!entry && !readerContext.readerLifecycle.disposed)
            readerContext.progressNotSaved({ name: "ReaderHistoryFullError" });
        });
      }).catch(() => {});
    } catch (_) {}
    readerContext.readerThemeToggle.addEventListener("click", () => {
      const theme = readerContext.readerTheme === "dark" ? "light" : "dark";
      readerContext.applyReaderTheme(theme);
      if (readerContext.isReaderOverlayFrame())
        window.parent.postMessage({ type: "voice-reader-theme", theme }, location.origin);
    });
    window.addEventListener("storage", (event) => {
      if (event.key === "theme" || event.key === null) syncStoredReaderTheme();
    });
    window.addEventListener("voice-reader-capture-progress", event => {
      if (!readerContext.isReaderOverlayFrame()) return;
      const write = (/** @type {CustomEvent} */ (event)).detail;
      if (typeof write !== "function") return;
      const progress = readerContext.captureProgressEntry();
      if (progress) {
        readerContext.lastSavedProgress = JSON.stringify(progress);
        write({ ...progress, closeTime: Date.now() });
      }
    });
    const saveAndDispose = () => {
      readerContext.saveProgress();
      readerContext.disposeReader();
    };
    window.addEventListener("voice-reader-dispose", saveAndDispose);
    window.addEventListener("message", (event) => {
      if (
        event.origin === location.origin &&
        event.source === window.parent &&
        event.data?.type === "voice-reader-abort"
      ) {
        saveAndDispose();
        return;
      }
      if (
        event.origin === location.origin &&
        event.source === window.parent &&
        event.data &&
        event.data.type === "voice-reader-theme-state" &&
        (event.data.theme === "light" || event.data.theme === "dark")
      )
        syncReaderTheme(event.data.theme);
    });
    /** @type {HTMLButtonElement} */ (document.querySelector("#history"))
      .addEventListener("click", (event) =>
        readerContext.setReaderPanelOpen(/** @type {Element} */ (document.querySelector("#history")).getAttribute("aria-expanded") !== "true", false, event.detail === 0)
      );
    /** @type {Element} */ (document.querySelector("#history-close"))
      .addEventListener("click", () => readerContext.setReaderPanelOpen(false, true));
    readerContext.viewport.addEventListener("scroll", readerContext.handleReaderPositionChange, { passive: true });

    bindReaderScrollIntent(readerContext.viewport, () => readerContext.notePdfScrollIntent());
  }

  function bindPdfPointerSelection() {
    readerContext.installReaderTapSelectionClear(readerContext.viewport);
    readerContext.viewport.addEventListener("pointerdown", (event) => {
      if (event.pointerType !== "mouse") {
        readerContext.pdfSelectionPointer = null;
        return;
      }
      const target = event.target instanceof Element ? event.target : null;
      const run = target?.closest(".reader-pdf-text-run");
      const selection = document.getSelection();
      const selectedRun = selection && !selection.isCollapsed && target?.closest(".reader-page")
        ? selection.anchorNode?.parentElement?.closest(".reader-pdf-text-run") : null;
      const origin = run || selectedRun;
      const caret = !event.shiftKey && event.button === 0 ? readerContext.independentTextCaret(document, event.clientX, event.clientY) : null;
      readerContext.pdfSelectionPointer = origin
        ? { id: event.pointerId, x: event.clientX, y: event.clientY, frame: 0,
            page: origin.closest(".reader-page"), anchorNode: caret?.node || (run ? null : selection?.anchorNode || null),
            anchorOffset: caret?.offset ?? (run ? 0 : selection?.anchorOffset ?? 0), caret: run ? caret : null } : null;
    }, { passive: false });
    readerContext.viewport.addEventListener("mousedown", (event) => {
      const caret = readerContext.pdfSelectionPointer?.caret;
      if (!caret || event.button !== 0 || event.shiftKey || event.detail > 1) return;
      // Start independent-text drags at the mapped caret, without native
      // edge auto-scroll. PointerEvent.detail is always zero in Chromium;
      // use MouseEvent.detail so double/triple clicks retain native selection.
      event.preventDefault();
      document.getSelection()?.setBaseAndExtent(caret.node, caret.offset, caret.node, caret.offset);
    }, { passive: false });
    document.addEventListener("pointermove", (event) => {
      const start = readerContext.pdfSelectionPointer;
      if (event.pointerType !== "mouse" || !start || start.id !== event.pointerId ||
          Math.hypot(event.clientX - start.x, event.clientY - start.y) < 6) return;
      const selection = document.getSelection();
      if (!start.anchorNode && selection?.rangeCount && selection.anchorNode && start.page?.contains(selection.anchorNode) &&
          selection.anchorNode.parentElement?.closest(".reader-pdf-text-run")) {
        start.anchorNode = selection.anchorNode;
        start.anchorOffset = selection.anchorOffset;
      }
      if (start.anchorNode) {
        start.endX = event.clientX;
        start.endY = event.clientY;
        if (!start.frame) start.frame = requestAnimationFrame(() => {
          start.frame = 0;
          if (readerContext.pdfSelectionPointer === start)
            readerContext.correctPdfCrossPageSelection(start.endX ?? start.x, start.endY ?? start.y, start);
        });
      }
    }, { passive: true });
    document.addEventListener("pointerup", (event) => {
      const start = readerContext.pdfSelectionPointer;
      readerContext.pdfSelectionPointer = null;
      if (event.pointerType !== "mouse" || !["pdf", "pdf-pages"].includes(/** @type {string} */ (readerContext.capability.mode)) ||
          !start || start.id !== event.pointerId ||
          Math.hypot(event.clientX - start.x, event.clientY - start.y) < 6) return;
      const x = event.clientX, y = event.clientY;
      requestAnimationFrame(() => readerContext.correctPdfCrossPageSelection(x, y, start));
    }, { passive: true });
    document.addEventListener("pointercancel", () => { readerContext.pdfSelectionPointer = null; }, { passive: true });
  }

  function bindSelectionAndPageLifecycle() {
    document.addEventListener("selectionchange", () => {
      if (readerContext.pdfSelectionBoundaryUpdate ||
          !["pdf", "pdf-pages"].includes(/** @type {string} */ (readerContext.capability.mode))) return;
      const selection = document.getSelection();
      if (!selection || selection.isCollapsed || !selection.rangeCount || !selection.anchorNode || !selection.focusNode) return;
      const runs = [...readerContext.content.querySelectorAll(".reader-pdf-text-run")]
        .filter((run) => run.firstChild?.nodeType === Node.TEXT_NODE);
      if (!runs.length) return;
      const anchorNode = selection.anchorNode, focusNode = selection.focusNode;
      const anchorRun = anchorNode.parentElement?.closest(".reader-pdf-text-run");
      const focusRun = focusNode.parentElement?.closest(".reader-pdf-text-run");
      if (!anchorRun || focusRun) return;
      // Separators (line ends, inter-block gaps) are selectable text nodes
      // directly inside the layer; a focus there is already valid text.
      const focusElement = focusNode.nodeType === Node.ELEMENT_NODE
        ? /** @type {Element} */ (focusNode) : focusNode.parentElement;
      if (focusElement?.closest(".reader-pdf-text")) return;
      const beforeAnchor = focusNode === anchorNode
        ? selection.focusOffset < selection.anchorOffset
        : Boolean(focusNode.compareDocumentPosition(anchorNode) & Node.DOCUMENT_POSITION_FOLLOWING);
      // Clamp to the run nearest the focus in document order. Choosing the
      // first/last run of the whole book jumps to a distant retained page
      // when the focus lands on a page whose text layer is not loaded yet.
      const focus = document.createRange();
      focus.setStart(focusNode, selection.focusOffset);
      let low = 0, high = runs.length;
      while (low < high) {
        const middle = (low + high) >> 1;
        const node = runs[middle]?.firstChild;
        if (!node) return;
        if (focus.comparePoint(node, 0) < 0) low = middle + 1;
        else high = middle;
      }
      const target = beforeAnchor ? runs[Math.min(low, runs.length - 1)] : runs[Math.max(low - 1, 0)];
      const node = target?.firstChild;
      if (!(node instanceof Text)) return;
      readerContext.pdfSelectionBoundaryUpdate = true;
      try {
        selection.setBaseAndExtent(selection.anchorNode, selection.anchorOffset, node,
          beforeAnchor ? 0 : node.length);
      } finally {
        readerContext.pdfSelectionBoundaryUpdate = false;
      }
    }, { passive: true });
    window.addEventListener("pagehide", (event) => {
      readerContext.saveProgress(event);
      if (!event.persisted) readerContext.disposeReader();
    });
    window.addEventListener("pageshow", (event) => {
      if (event.persisted && !readerContext.readerLifecycle.disposed) {
        readerContext.updateProgressTools();
      }
    });
    document.addEventListener("visibilitychange", () => {
      if (document.visibilityState === "hidden") readerContext.saveProgress();
      if (document.hidden) readerContext.stopPdfManifestPrefetch();
      else readerContext.queuePdfManifestPrefetch();
    });
    window.addEventListener("offline", readerContext.stopPdfManifestPrefetch);
    window.addEventListener("online", () => readerContext.queuePdfManifestPrefetch());
  }

  function mountProgressControls() {
    readerContext.progressTools.className = "reader-progress-tools";
    readerContext.progressTools.innerHTML =
      '<div class="reader-progress-row"><button class="reader-chapter-prev" type="button" aria-label="上一章" title="上一章"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m14 5-7 7 7 7"/></svg></button><input class="reader-progress-range" type="range" min="0" max="100" step="0.1" value="0" aria-label="阅读进度"><span class="reader-progress-percent">0.0%</span><button class="reader-progress-undo" type="button" aria-label="撤销进度调整" title="撤销进度调整"><svg viewBox="0 0 100 100" aria-hidden="true" focusable="false"><path fill="currentColor" stroke="none" d="M22 50.5a28.5 28.5 0 1 1 11.4 22.8l-5.3 5.3A36 36 0 1 0 14.5 50.5H3l16 16 16-16z"/><circle cx="50.5" cy="50.5" r="8" fill="currentColor" stroke="none"/></svg></button><button class="reader-chapter-next" type="button" aria-label="下一章" title="下一章"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m10 5 7 7-7 7"/></svg></button></div>';
    /** @type {Element} */ (document.querySelector("#history-panel")).appendChild(readerContext.progressTools);
  }

  function mountProgressSummary() {
    readerContext.readingProgressSummary.className = "reader-progress-summary";
    readerContext.readingProgressSummary.innerHTML =
      '<strong>阅读状态</strong><span class="reader-progress-summary-value">0.0%</span><button class="reader-progress-bookmark text-action" type="button">在当前位置添加书签</button>';
    readerContext.progressTools.prepend(readerContext.readingProgressSummary);
    /** @type {Element} */ (readerContext.readingProgressSummary.querySelector(".reader-progress-bookmark"))
      .addEventListener("click", (event) => readerContext.openBookmarkPopover(event.currentTarget instanceof HTMLElement ? event.currentTarget : undefined));

    readerContext.updateReadingProgressSummary();

    readerContext.syncTocTab();
  }

  function bindProgressActions() {
    let seekChanged = false;
    const startSeeking = () => {
      if (readerContext.progressSeeking || readerContext.progressRange.disabled) return;
      readerContext.progressSeeking = true;
      seekChanged = false;
    };
    const finishSeeking = () => {
      if (!readerContext.progressSeeking) return;
      readerContext.progressSeeking = false;
      const generation = readerContext.readerRuntime.currentGeneration("navigation");
      readerContext.flushEpubSeek().then(() => {
        if (readerContext.isReaderGenerationCurrent("navigation", generation)) readerContext.updateProgressTools();
      });
    };
    readerContext.progressRange.addEventListener("pointerdown", startSeeking);
    const seekKeys = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End"];
    readerContext.progressRange.addEventListener("keydown", (event) => {
      if (seekKeys.includes(event.key) && !event.defaultPrevented && !event.altKey && !event.ctrlKey && !event.metaKey)
        startSeeking();
    });
    readerContext.progressRange.addEventListener("keyup", (event) => {
      if (seekKeys.includes(event.key)) finishSeeking();
    });
    readerContext.progressRange.addEventListener("blur", finishSeeking);
    readerContext.progressRange.addEventListener("input", () => {
      // A key or pointer press may leave the value unchanged. Snapshot only on a valid input.
      if (!readerContext.seekProgress(readerContext.progressRange.value, readerContext.progressSeeking && seekChanged)) {
        readerContext.progressSeeking = false;
        readerContext.updateProgressTools();
        return;
      }
      readerContext.progressPercent.textContent = `${Number(readerContext.progressRange.value).toFixed(1)}%`;
      readerContext.progressRange.setAttribute("aria-valuetext", readerContext.progressPercent.textContent);
      seekChanged = true;
    });
    for (const type of ["pointerup", "pointercancel"])
      readerContext.progressRange.addEventListener(type, finishSeeking);
    readerContext.progressUndo.addEventListener("click", () => {
      const restoreFocus = document.activeElement === readerContext.progressUndo;
      const state = readerContext.previousProgressState;
      readerContext.previousProgressState = null;
      readerContext.progressSeeking = false;
      readerContext.restoreProgressState(state);
      readerContext.updateProgressTools();
      if (restoreFocus) readerContext.progressRange.focus({ preventScroll: true });
    });
    readerContext.chapterPrev.addEventListener("click", () =>
      readerContext.activateChapter(readerContext.adjacentTocIndex(-1))
    );
    readerContext.chapterNext.addEventListener("click", () =>
      readerContext.activateChapter(readerContext.adjacentTocIndex(1))
    );
  }

  function ownPdfSearchStorageAndStart() {
    readerContext.trackReaderResource(() => {
      readerContext.pdfPersistentTextStore?.dispose();
      readerContext.pdfPersistentTextStore = readerContext.pdfPersistentTextOpening = readerContext.pdfPersistentTextVersion = null;
      readerContext.pdfSearchTextCache.clear();
      readerContext.pdfSearchTextCacheBytes = 0;
    });

    readerContext.registerReaderFormatAdapters();
    readerContext.syncCapabilityControls();
    readerContext.updateProgressTools();
    readerContext.start().catch((error) => {
      if (readerContext.readerAbortController.signal.aborted || error?.name === "AbortError") return;
      console.error(error);
      const code = readerContext.classifyReaderError(error);
      readerContext.fail("阅读文件解析失败,请刷新后重试,或下载原文件。", typeof code === "string" ? code : "READER_PARSE");
    });
  }

  return {
    trackStartupOwners,
    publishDiagnosticsAndInstallCompatibility,
    readSelectedSourceSession,
    applySourceSessionAndCachedMetadata,
    publishSourceAndSubscribeToStore,
    initializePanelAccessibility,
    mountInitialLoadingFeedback,
    initializeDocumentTitle,
    restoreReturnNavigation,
    validateReturnHistory,
    ownChapterSearchClient,
    ownIndependentPdfResources,
    ownPdfBookSearchClient,
    ownPdfPrefetchAndQueues,
    initializeGenerations,
    mountMediaPanel,
    restoreAndBindPageInversion,
    restoreReaderThemeAndBindReturn,
    bindZoomAndPageControls,
    bindReaderUiHistory,
    bindPanelBookmarkAndLifecycleControls,
    bindPdfPointerSelection,
    bindSelectionAndPageLifecycle,
    mountProgressControls,
    mountProgressSummary,
    bindProgressActions,
    ownPdfSearchStorageAndStart
  };
}