/** * @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(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} saveProgress * @property {Promise} 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} promise @param {AbortSignal | null} [extraSignal] @returns {Promise>} */ 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} */ (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 = ``; 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 }; }