File size: 10,946 Bytes
2be9ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822b94b
2be9ba5
3a37705
1dc63a4
2be9ba5
 
 
 
 
 
 
2315c7d
2be9ba5
 
 
49a03ba
 
 
 
 
 
 
 
 
 
2be9ba5
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2be9ba5
49a03ba
 
 
 
2be9ba5
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ceac12
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
9ceac12
49a03ba
 
2be9ba5
49a03ba
 
 
 
2be9ba5
49a03ba
 
 
 
2be9ba5
49a03ba
2be9ba5
2315c7d
2be9ba5
2315c7d
6c8fd46
 
2be9ba5
6c8fd46
49a03ba
 
 
 
 
 
 
 
1dc63a4
 
49a03ba
3a37705
49a03ba
 
2be9ba5
49a03ba
 
 
 
 
 
2be9ba5
49a03ba
 
 
 
2be9ba5
49a03ba
2be9ba5
49a03ba
 
 
 
 
 
 
 
 
 
169f8e1
49a03ba
 
 
 
 
 
 
 
2be9ba5
49a03ba
 
2315c7d
 
 
49a03ba
 
bef5045
 
49a03ba
 
 
 
 
3a37705
49a03ba
6c8fd46
2315c7d
 
 
 
6c8fd46
9c77549
bef5045
 
 
2315c7d
49a03ba
 
 
 
 
2315c7d
 
b841389
6c8fd46
b841389
 
6c8fd46
b841389
 
 
 
 
 
bef5045
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
/**
 * @typedef {object} ReaderLifecycleContext
 * @property {AbortController} readerAbortController
 * @property {Set<() => unknown>} readerResources
 * @property {{state: {lifecycle: {disposed: boolean}}, setPhase(phase: string): boolean,
 *   setStage(stage: string): boolean, nextGeneration(name: string): number,
 *   isCurrent(name: string, value: number): boolean, dispose(): unknown, fail(code: string): unknown}} readerRuntime
 * @property {{disposed: boolean, stage: string}} readerLifecycle
 * @property {() => Error} readerAbortError
 * @property {() => void} assertReaderActive
 * @property {() => void} drainPdfTextWaiters
 * @property {(name: string, value: number) => boolean} isReaderGenerationCurrent
 * @property {(update: {restorationReady: boolean}) => unknown} updateDocumentState
 * @property {number} saveTimer
 * @property {number} themeAnimationTimer
 * @property {number} panelAnimationTimer
 * @property {number} markerFrame
 * @property {{mode: string | null} | null | undefined} capability
 * @property {HTMLElement} loadingIndicator
 * @property {boolean} readerContentReady
 * @property {{preserve<T>(change: () => T): T}} chapterScrollAnchors
 * @property {(open: boolean) => unknown} setReaderPanelOpen
 * @property {() => unknown} stopReaderWork
 * @property {{dispose(): unknown}} readerRequestManager
 * @property {{dispose(): unknown}} formatAdapters
 * @property {HTMLElement} content
 * @property {HTMLElement} status
 * @property {() => unknown} markReaderContentReady
 * @property {() => Promise<unknown>} saveProgress
 * @property {Promise<unknown>} progressSaveChain
 */
/** @param {ReaderLifecycleContext} readerContext */
export function createReaderLifecycle(readerContext) {
  function readerAbortError() {
    return new DOMException("Reader work cancelled", "AbortError");
  }

  function assertReaderActive() {
    if (readerContext.readerAbortController.signal.aborted || readerContext.readerRuntime.state.lifecycle.disposed)
      throw readerContext.readerAbortError();
  }

  /** @param {() => unknown} cleanup */
  function trackReaderResource(cleanup) {
    if (readerContext.readerAbortController.signal.aborted) cleanup();
    else readerContext.readerResources.add(cleanup);
    return () => readerContext.readerResources.delete(cleanup);
  }

  function stopReaderWork() {
    readerContext.readerAbortController.abort();
    for (const cleanup of readerContext.readerResources) {
      try {
        cleanup();
      } catch (_) {}
    }
    readerContext.readerResources.clear();
  }

  /** @template T @param {T | PromiseLike<T>} promise @param {AbortSignal | null} [extraSignal] @returns {Promise<Awaited<T>>} */
  function awaitReader(promise, extraSignal = null) {
    return new Promise((resolve, reject) => {
      let settled = false;
      const signals = extraSignal ? [readerContext.readerAbortController.signal, extraSignal] : [readerContext.readerAbortController.signal];
      /** @template U @param {(value: U) => void} callback @param {U} value */
      const finish = (callback, value) => {
        if (settled) return;
        settled = true;
        signals.forEach(signal => signal.removeEventListener("abort", abort));
        callback(value);
      };
      const abort = () => finish(reject, readerContext.readerAbortError());
      Promise.resolve(promise)
        .then(value => finish(resolve, value), error => finish(reject, error));
      if (signals.some(signal => signal.aborted)) abort();
      else signals.forEach(signal => signal.addEventListener("abort", abort, { once: true }));
    });
  }

  function waitForReader(delay = 0, animationFrame = false) {
    return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
      readerContext.assertReaderActive();
      const signal = readerContext.readerAbortController.signal;
      const abort = () => {
        if (animationFrame) cancelAnimationFrame(handle);
        else clearTimeout(handle);
        reject(readerContext.readerAbortError());
      };
      const done = () => {
        signal.removeEventListener("abort", abort);
        resolve();
      };
      const handle = animationFrame ? requestAnimationFrame(done) : setTimeout(done, delay);
      signal.addEventListener("abort", abort, { once: true });
    }));
  }

  /** @param {string} phase */
  function setReaderPhase(phase) {
    return readerContext.readerRuntime.setPhase(phase);
  }

  /** @param {string} stage */
  function setReaderStage(stage) {
    return readerContext.readerRuntime.setStage(stage);
  }

  /** @param {unknown} error @param {string} [fallback] */
  function classifyReaderError(error, fallback = "READER_PARSE") {
    if ((/** @type {{code?: unknown} | null | undefined} */ (error))?.code === "READER_PDF_RATE_LIMIT") return "READER_PDF_TRANSPORT";
    if ((/** @type {unknown[]} */ (["READER_ENGINE_NETWORK", "READER_RESTORE", "READER_PDF_TRANSPORT", "READER_CHAPTER_MANIFEST_TRANSIENT"]))
      .includes((/** @type {{code?: unknown} | null | undefined} */ (error))?.code)) return (/** @type {{code?: unknown}} */ (error)).code;
    if ((/** @type {{code?: unknown} | null | undefined} */ (error))?.code === "DJVU_RANGE_TRANSIENT") return "READER_DJVU_TRANSPORT";
    if ((/** @type {{code?: unknown} | null | undefined} */ (error))?.code === "READER_BODY_INTERRUPTED" &&
        ["text", "markdown", "html"].includes(readerContext.capability?.mode || "")) return "READER_DOCUMENT_INTERRUPTED";
    const value = `${(/** @type {{name?: unknown} | null | undefined} */ (error))?.name || ""} ${(/** @type {{message?: unknown} | null | undefined} */ (error))?.message || error || ""}`;
    if (/AbortError|timeout|network|fetch|HTTP[\s_]*\d+/i.test(value)) return "READER_NETWORK";
    if (
      /EPUB_INVALID|corrupt|damage|truncated|central directory|end of data|invalid zip/i.test(value)
    )
      return "READER_CORRUPT";
    return fallback;
  }

  function markReaderContentReady() {
    if (readerContext.capability?.mode === "epub-chapters" && readerContext.loadingIndicator.isConnected)
      readerContext.chapterScrollAnchors.preserve(() => readerContext.loadingIndicator.remove());
    else readerContext.loadingIndicator.remove();
    readerContext.readerContentReady = true;
  }

  /** @param {string} name */
  function nextReaderGeneration(name) {
    const generation = readerContext.readerRuntime.nextGeneration(name);
    if (name === "search") readerContext.drainPdfTextWaiters();
    return generation;
  }

  /** @param {string} name @param {number} value */
  function isReaderGenerationCurrent(name, value) {
    return !readerContext.readerAbortController.signal.aborted && readerContext.readerRuntime.isCurrent(name, value);
  }

  /** @param {unknown} error @param {number} generation */
  function reportNavigationError(error, generation) {
    if (readerContext.isReaderGenerationCurrent("navigation", generation) && (/** @type {{name?: unknown} | null | undefined} */ (error))?.name !== "AbortError")
      console.warn("Reader navigation failed", error);
  }

  function disposeReader() {
    if (readerContext.readerLifecycle.disposed) return;
    readerContext.updateDocumentState({ restorationReady: false });
    readerContext.readerRuntime.dispose();
    clearTimeout(readerContext.saveTimer);
    clearTimeout(readerContext.themeAnimationTimer);
    clearTimeout(readerContext.panelAnimationTimer);
    if (readerContext.markerFrame) cancelAnimationFrame(readerContext.markerFrame);
    readerContext.saveTimer =
      readerContext.themeAnimationTimer =
      readerContext.panelAnimationTimer =
      readerContext.markerFrame =
        0;
    VoiceOfMLReaderStore.dispose?.();
  }

  /** @param {string} message @param {string} [code] */
  function fail(message, code = "READER_PARSE") {
    if (readerContext.readerLifecycle.disposed || readerContext.readerAbortController.signal.aborted) return;
    // Capture the current eligible position before clearing the page shells.
    // saveProgress itself rejects unrestored positions and honours history opt-out.
    if (code === "READER_DJVU_TRANSPORT") void readerContext.saveProgress().catch(() => {});
    readerContext.updateDocumentState({ restorationReady: false });
    readerContext.readerRuntime.fail(code);
    const closePanel = ["READER_PDF_TRANSPORT", "READER_DJVU_TRANSPORT", "READER_MEDIA"].includes(code);
    if (closePanel) readerContext.setReaderPanelOpen(false);
    readerContext.stopReaderWork();
    readerContext.readerRequestManager.dispose();
    readerContext.formatAdapters.dispose();
    window.__VOICE_PDF_PRELOAD__?.dispose();
    readerContext.content.dataset.errorCode = code;
    // The error surface also ends loading, without marking restoration ready.
    readerContext.markReaderContentReady();
    const description = code === "READER_DOCUMENT_INTERRUPTED"
      ? "正文下载中断,原阅读进度已保留。请重试加载完整文件。"
      : code === "READER_CHAPTER_MANIFEST_TRANSIENT" ? "章节列表暂时无法加载,请重试加载。"
      : code === "READER_DJVU_TRANSPORT" ? "DjVu 数据暂时无法读取,请重试加载整本文件。"
      : message;
    const visibleMessage = `${description} [${readerContext.readerLifecycle.stage}]`;
    readerContext.content.innerHTML = `<div class="reader-error" role="alert"></div>`;
    const surface = /** @type {Element} */ (readerContext.content.querySelector(".reader-error"));
    surface.textContent = visibleMessage;
    const waitForProgress = closePanel || code === "READER_DOCUMENT_INTERRUPTED";
    if (waitForProgress || ["READER_ENGINE_NETWORK", "READER_RESTORE", "READER_CHAPTER_MANIFEST_TRANSIENT"].includes(code)) {
      const retry = document.createElement("button");
      retry.type = "button";
      retry.className = "text-button";
      retry.id = "reader-engine-retry";
      retry.textContent = "重试加载";
      // Reopen this reader, not a source or return URL. A new load also
      // creates a fresh decoder rather than reusing a failed worker.
      retry.addEventListener("click", async () => {
        if (waitForProgress) {
          let timer;
          try {
            await Promise.race([readerContext.progressSaveChain.catch(() => {}),
              new Promise(resolve => { timer = setTimeout(resolve, 500); })]);
          } finally { clearTimeout(timer); }
          if (readerContext.readerLifecycle.disposed) return;
        }
        location.reload();
      });
      surface.append(document.createElement("br"), retry);
    }
    readerContext.status.textContent = "无法打开";
  }

  return {
    readerAbortError,
    assertReaderActive,
    trackReaderResource,
    stopReaderWork,
    awaitReader,
    waitForReader,
    setReaderPhase,
    setReaderStage,
    classifyReaderError,
    markReaderContentReady,
    nextReaderGeneration,
    isReaderGenerationCurrent,
    reportNavigationError,
    disposeReader,
    fail
  };
}