From e0e5d71a45ca4cd613e03ea09dfda4f7543b516e Mon Sep 17 00:00:00 2001 From: fallenbagel <98979876+Fallenbagel@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:49:05 +0800 Subject: [PATCH] fix: restore scroll position and loaded pages after reload Reloading any page went back to the top, and discover lists also fell back to three pages, as Next only restores scroll on popstate and the page count only lived in the SWR cache. Scroll positions and list page counts are now saved to sessionStorage and restored after a reload, including when going back after reloading another page. Search also no longer replaces its own unchanged URL, which reset scroll on back navigation. fix #3740, ref #3739 --- src/hooks/useDiscover.ts | 3 + src/hooks/useScrollRestoration.ts | 203 ++++++++++++++++++++++++++++++ src/hooks/useSearchInput.ts | 16 +-- src/pages/_app.tsx | 2 + 4 files changed, 217 insertions(+), 7 deletions(-) create mode 100644 src/hooks/useScrollRestoration.ts diff --git a/src/hooks/useDiscover.ts b/src/hooks/useDiscover.ts index 53259dbcf6..19c781df48 100644 --- a/src/hooks/useDiscover.ts +++ b/src/hooks/useDiscover.ts @@ -4,6 +4,7 @@ import { MediaStatus } from '@server/constants/media'; import { useEffect } from 'react'; import { useIntl } from 'react-intl'; import useSWRInfinite from 'swr/infinite'; +import { usePageCountRestoration } from './useScrollRestoration'; import useSettings from './useSettings'; import { Permission, useUser } from './useUser'; @@ -109,6 +110,8 @@ const useDiscover = < setSize(size + 1); }; + usePageCountRestoration(size, setSize, isLoadingMore); + let titles = (data ?? []).reduce((a, v) => { const results: T[] = []; diff --git a/src/hooks/useScrollRestoration.ts b/src/hooks/useScrollRestoration.ts new file mode 100644 index 0000000000..8dff403142 --- /dev/null +++ b/src/hooks/useScrollRestoration.ts @@ -0,0 +1,203 @@ +import { useRouter } from 'next/router'; +import { useEffect, useLayoutEffect, useRef } from 'react'; + +const ENTRIES_KEY = 'scroll-restoration'; +const HIDDEN_ENTRY_KEY = 'scroll-restoration-hidden-entry'; +const CHECK_INTERVAL_MS = 100; +const SETTLE_MS = 1000; +const MAX_WAIT_MS = 10000; +const INPUT_EVENTS = ['keydown', 'pointerdown', 'wheel']; +const KEY_REFRESH_EVENTS = ['keydown', 'pointerdown', 'scroll']; + +interface ScrollEntry { + url: string; + y: number; + pages?: number; +} + +let listPages: number | undefined; +let pageRestore: { url: string; pages: number } | undefined; + +// sessionStorage throws when site data is blocked or the quota is full +const tryStorage = (access: () => T): T | undefined => { + try { + return access(); + } catch { + return undefined; + } +}; + +const readEntries = (): Record => + tryStorage(() => JSON.parse(sessionStorage.getItem(ENTRIES_KEY) ?? '{}')) ?? + {}; + +export const usePageCountRestoration = ( + size: number, + setSize: (size: number) => void, + isLoading: boolean +) => { + const router = useRouter(); + + useEffect(() => { + listPages = size; + return () => { + listPages = undefined; + }; + }, [size]); + + useEffect(() => { + if (pageRestore?.url !== router.asPath || isLoading) { + return; + } + + if (size < pageRestore.pages) { + setSize(pageRestore.pages); + } else { + pageRestore = undefined; + } + }, [isLoading, router.asPath, setSize, size]); +}; + +const useScrollRestoration = () => { + const router = useRouter(); + const isLandingRef = useRef(true); + const poppedRef = useRef(false); + + // a layout effect so pageRestore is set before the page's own effects read it + useLayoutEffect(() => { + const url = router.asPath; + const isLanding = isLandingRef.current; + const popped = poppedRef.current; + isLandingRef.current = false; + poppedRef.current = false; + pageRestore = undefined; + + // routeChangeStart can fire after a back/forward has already moved history.state + let entryKey: string | undefined = window.history.state?.key; + let pendingY: number | undefined; + let timer: ReturnType | undefined; + + const refreshKey = () => { + if (!poppedRef.current) { + entryKey = window.history.state?.key; + } + }; + const save = () => { + if (!entryKey) { + return; + } + + const entries = readEntries(); + entries[entryKey] = { + url, + y: pendingY ?? window.scrollY, + pages: pageRestore?.pages ?? listPages, + }; + tryStorage(() => + sessionStorage.setItem(ENTRIES_KEY, JSON.stringify(entries)) + ); + }; + const saveIfHidden = () => { + if (document.visibilityState === 'hidden') { + refreshKey(); + save(); + const hiddenKey = entryKey; + if (hiddenKey) { + tryStorage(() => sessionStorage.setItem(HIDDEN_ENTRY_KEY, hiddenKey)); + } + } + }; + const onPopState = () => { + poppedRef.current = true; + stop(); + }; + const stop = () => { + clearInterval(timer); + INPUT_EVENTS.forEach((event) => + window.removeEventListener(event, cancel) + ); + }; + const done = () => { + pendingY = undefined; + stop(); + }; + const cancel = () => { + pageRestore = undefined; + done(); + }; + + let entry: ScrollEntry | undefined; + if (isLanding) { + // a fresh load opened from another page won't match the hidden URL + const hiddenKey = tryStorage(() => + sessionStorage.getItem(HIDDEN_ENTRY_KEY) + ); + tryStorage(() => sessionStorage.removeItem(HIDDEN_ENTRY_KEY)); + entry = hiddenKey ? readEntries()[hiddenKey] : undefined; + } else if (popped && entryKey) { + entry = readEntries()[entryKey]; + } + + if (entry?.url === url && entry.y) { + const { y } = entry; + pendingY = y; + if (entry.pages) { + pageRestore = { url, pages: entry.pages }; + } + + const startedAt = Date.now(); + let height: number | undefined; + let changedAt: number | undefined; + const check = () => { + const now = Date.now(); + const maxY = document.documentElement.scrollHeight - window.innerHeight; + // a spinner holds the height still, so settling counts from the first change + if (height !== undefined && maxY !== height) { + changedAt = now; + } + height = maxY; + + // a list still loading its saved pages has not settled + const isSettled = + !pageRestore && + changedAt !== undefined && + now - changedAt >= SETTLE_MS; + if (maxY >= y || isSettled) { + window.scrollTo(0, y); + done(); + } else if ( + !pageRestore && + changedAt === undefined && + now - startedAt >= MAX_WAIT_MS + ) { + done(); + } + }; + + INPUT_EVENTS.forEach((event) => + window.addEventListener(event, cancel, { passive: true }) + ); + timer = setInterval(check, CHECK_INTERVAL_MS); + check(); + } + + router.events.on('routeChangeStart', save); + window.addEventListener('popstate', onPopState); + KEY_REFRESH_EVENTS.forEach((event) => + window.addEventListener(event, refreshKey, { passive: true }) + ); + document.addEventListener('visibilitychange', saveIfHidden); + + return () => { + stop(); + router.events.off('routeChangeStart', save); + window.removeEventListener('popstate', onPopState); + KEY_REFRESH_EVENTS.forEach((event) => + window.removeEventListener(event, refreshKey) + ); + document.removeEventListener('visibilitychange', saveIfHidden); + }; + }, [router.asPath, router.events]); +}; + +export default useScrollRestoration; diff --git a/src/hooks/useSearchInput.ts b/src/hooks/useSearchInput.ts index a60b28c075..e55752539a 100644 --- a/src/hooks/useSearchInput.ts +++ b/src/hooks/useSearchInput.ts @@ -34,13 +34,15 @@ const useSearchInput = (): SearchObject => { useEffect(() => { if (debouncedValue !== '' && searchOpen) { if (router.pathname.startsWith('/search')) { - router.replace({ - pathname: router.pathname, - query: { - ...router.query, - query: debouncedValue, - }, - }); + if (router.query.query !== debouncedValue) { + router.replace({ + pathname: router.pathname, + query: { + ...router.query, + query: debouncedValue, + }, + }); + } } else { setLastRoute(router.asPath); router diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx index e11bf14a4e..7c11ea8425 100644 --- a/src/pages/_app.tsx +++ b/src/pages/_app.tsx @@ -7,6 +7,7 @@ import { InteractionProvider } from '@app/context/InteractionContext'; import { LanguageContext } from '@app/context/LanguageContext'; import { SettingsProvider } from '@app/context/SettingsContext'; import { UserContext } from '@app/context/UserContext'; +import useScrollRestoration from '@app/hooks/useScrollRestoration'; import type { User } from '@app/hooks/useUser'; import { Permission, useUser } from '@app/hooks/useUser'; import '@app/styles/globals.css'; @@ -130,6 +131,7 @@ const CoreApp: Omit = ({ let component: React.ReactNode; const [loadedMessages, setMessages] = useState(messages); const [currentLocale, setLocale] = useState(locale); + useScrollRestoration(); useEffect(() => { loadLocaleData(currentLocale).then(setMessages);