From 654a32a8566776aecf47afa24592a89a581a0ca4 Mon Sep 17 00:00:00 2001 From: codedogQBY <1369175442@qq.com> Date: Sat, 13 Jun 2026 08:56:08 +0800 Subject: [PATCH] fix(reader): flush location on close --- .../app/src/components/reader/ReaderView.tsx | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/app/src/components/reader/ReaderView.tsx b/packages/app/src/components/reader/ReaderView.tsx index 0605de7d..35684215 100644 --- a/packages/app/src/components/reader/ReaderView.tsx +++ b/packages/app/src/components/reader/ReaderView.tsx @@ -883,6 +883,11 @@ export function ReaderView({ bookId, tabId }: ReaderViewProps) { } | null>(null); const totalBookCharactersRef = useRef(null); const progressTrackingGuardUntilRef = useRef(0); + const latestProgressRef = useRef<{ + bookId: string; + progress: number; + cfi: string; + } | null>(null); const suppressProgressTracking = useCallback((duration = PROGRAMMATIC_NAV_GUARD_MS) => { progressTrackingGuardUntilRef.current = Math.max( @@ -924,6 +929,27 @@ export function ReaderView({ bookId, tabId }: ReaderViewProps) { }, 5000), ).current; + const flushLatestProgress = useCallback(() => { + const latest = latestProgressRef.current; + if (!latest || latest.bookId !== bookId) return; + updateBook(latest.bookId, { + progress: latest.progress, + currentCfi: latest.cfi, + lastOpenedAt: Date.now(), + }); + }, [bookId, updateBook]); + + useEffect(() => { + window.addEventListener("pagehide", flushLatestProgress); + window.addEventListener("beforeunload", flushLatestProgress); + + return () => { + window.removeEventListener("pagehide", flushLatestProgress); + window.removeEventListener("beforeunload", flushLatestProgress); + flushLatestProgress(); + }; + }, [flushLatestProgress]); + // --- Load book on mount --- useEffect(() => { if (!book?.filePath || isInitializedRef.current) return; @@ -958,6 +984,7 @@ export function ReaderView({ bookId, tabId }: ReaderViewProps) { useEffect(() => { sessionProgressRef.current = null; + latestProgressRef.current = null; suppressProgressTracking(INITIAL_PROGRESS_RESTORE_GUARD_MS); }, [bookId, tabId, bookFormat, suppressProgressTracking]); @@ -1105,6 +1132,7 @@ export function ReaderView({ bookId, tabId }: ReaderViewProps) { // Update reader store (immediate) setProgress(tabId, progress, cfi); + latestProgressRef.current = { bookId, progress, cfi }; // Update chapter info if (detail.tocItem?.label) {