Skip to content

Commit 5f5697a

Browse files
committed
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
1 parent c5d5463 commit 5f5697a

4 files changed

Lines changed: 213 additions & 7 deletions

File tree

‎src/hooks/useDiscover.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { MediaStatus } from '@server/constants/media';
44
import { useEffect } from 'react';
55
import { useIntl } from 'react-intl';
66
import useSWRInfinite from 'swr/infinite';
7+
import { usePageCountRestoration } from './useScrollRestoration';
78
import useSettings from './useSettings';
89
import { Permission, useUser } from './useUser';
910

@@ -109,6 +110,8 @@ const useDiscover = <
109110
setSize(size + 1);
110111
};
111112

113+
usePageCountRestoration(size, setSize, isLoadingMore);
114+
112115
let titles = (data ?? []).reduce((a, v) => {
113116
const results: T[] = [];
114117

‎src/hooks/useScrollRestoration.ts‎

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
import { useRouter } from 'next/router';
2+
import { useEffect, useLayoutEffect, useRef } from 'react';
3+
4+
const ENTRIES_KEY = 'scroll-restoration';
5+
const HIDDEN_ENTRY_KEY = 'scroll-restoration-hidden-entry';
6+
const CHECK_INTERVAL_MS = 100;
7+
const SETTLE_MS = 1000;
8+
const MAX_WAIT_MS = 10000;
9+
const INPUT_EVENTS = ['keydown', 'pointerdown', 'wheel'];
10+
const KEY_REFRESH_EVENTS = ['keydown', 'pointerdown', 'scroll'];
11+
12+
interface ScrollEntry {
13+
url: string;
14+
y: number;
15+
pages?: number;
16+
}
17+
18+
let listPages: number | undefined;
19+
let pageRestore: { url: string; pages: number } | undefined;
20+
21+
// sessionStorage throws when site data is blocked or the quota is full
22+
const tryStorage = <T>(access: () => T): T | undefined => {
23+
try {
24+
return access();
25+
} catch {
26+
return undefined;
27+
}
28+
};
29+
30+
const readEntries = (): Record<string, ScrollEntry> =>
31+
tryStorage(() => JSON.parse(sessionStorage.getItem(ENTRIES_KEY) ?? '{}')) ??
32+
{};
33+
34+
export const usePageCountRestoration = (
35+
size: number,
36+
setSize: (size: number) => void,
37+
isLoading: boolean
38+
) => {
39+
const router = useRouter();
40+
41+
useEffect(() => {
42+
listPages = size;
43+
return () => {
44+
listPages = undefined;
45+
};
46+
}, [size]);
47+
48+
useEffect(() => {
49+
if (pageRestore?.url !== router.asPath || isLoading) {
50+
return;
51+
}
52+
53+
if (size < pageRestore.pages) {
54+
setSize(pageRestore.pages);
55+
} else {
56+
pageRestore = undefined;
57+
}
58+
}, [isLoading, router.asPath, setSize, size]);
59+
};
60+
61+
const useScrollRestoration = () => {
62+
const router = useRouter();
63+
const isLandingRef = useRef(true);
64+
const poppedRef = useRef(false);
65+
66+
// a layout effect so pageRestore is set before the page's own effects read it
67+
useLayoutEffect(() => {
68+
const url = router.asPath;
69+
const isLanding = isLandingRef.current;
70+
const popped = poppedRef.current;
71+
isLandingRef.current = false;
72+
poppedRef.current = false;
73+
pageRestore = undefined;
74+
75+
// routeChangeStart can fire after a back/forward has already moved history.state
76+
let entryKey: string | undefined = window.history.state?.key;
77+
let pendingY: number | undefined;
78+
let timer: ReturnType<typeof setInterval> | undefined;
79+
80+
const refreshKey = () => {
81+
if (!poppedRef.current) {
82+
entryKey = window.history.state?.key;
83+
}
84+
};
85+
const save = () => {
86+
if (!entryKey) {
87+
return;
88+
}
89+
90+
const entries = readEntries();
91+
entries[entryKey] = {
92+
url,
93+
y: pendingY ?? window.scrollY,
94+
pages: pageRestore?.pages ?? listPages,
95+
};
96+
tryStorage(() =>
97+
sessionStorage.setItem(ENTRIES_KEY, JSON.stringify(entries))
98+
);
99+
};
100+
const saveIfHidden = () => {
101+
if (document.visibilityState === 'hidden') {
102+
refreshKey();
103+
save();
104+
const hiddenKey = entryKey;
105+
if (hiddenKey) {
106+
tryStorage(() => sessionStorage.setItem(HIDDEN_ENTRY_KEY, hiddenKey));
107+
}
108+
}
109+
};
110+
const onPopState = () => {
111+
poppedRef.current = true;
112+
stop();
113+
};
114+
const stop = () => {
115+
clearInterval(timer);
116+
INPUT_EVENTS.forEach((event) =>
117+
window.removeEventListener(event, cancel)
118+
);
119+
};
120+
const done = () => {
121+
pendingY = undefined;
122+
stop();
123+
};
124+
const cancel = () => {
125+
pageRestore = undefined;
126+
done();
127+
};
128+
129+
let entry: ScrollEntry | undefined;
130+
if (isLanding) {
131+
// a fresh load opened from another page won't match the hidden URL
132+
const hiddenKey = tryStorage(() =>
133+
sessionStorage.getItem(HIDDEN_ENTRY_KEY)
134+
);
135+
tryStorage(() => sessionStorage.removeItem(HIDDEN_ENTRY_KEY));
136+
entry = hiddenKey ? readEntries()[hiddenKey] : undefined;
137+
} else if (popped && entryKey) {
138+
entry = readEntries()[entryKey];
139+
}
140+
141+
if (entry?.url === url && entry.y) {
142+
const { y } = entry;
143+
pendingY = y;
144+
if (entry.pages) {
145+
pageRestore = { url, pages: entry.pages };
146+
}
147+
148+
const startedAt = Date.now();
149+
let height: number | undefined;
150+
let changedAt: number | undefined;
151+
const check = () => {
152+
const now = Date.now();
153+
const maxY = document.documentElement.scrollHeight - window.innerHeight;
154+
// a spinner holds the height still, so settling counts from the first change
155+
if (height !== undefined && maxY !== height) {
156+
changedAt = now;
157+
}
158+
height = maxY;
159+
160+
// a list still loading its saved pages has not settled
161+
const isSettled =
162+
!pageRestore &&
163+
changedAt !== undefined &&
164+
now - changedAt >= SETTLE_MS;
165+
if (maxY >= y || isSettled) {
166+
window.scrollTo(0, y);
167+
done();
168+
} else if (changedAt === undefined && now - startedAt >= MAX_WAIT_MS) {
169+
done();
170+
}
171+
};
172+
173+
INPUT_EVENTS.forEach((event) =>
174+
window.addEventListener(event, cancel, { passive: true })
175+
);
176+
timer = setInterval(check, CHECK_INTERVAL_MS);
177+
check();
178+
}
179+
180+
router.events.on('routeChangeStart', save);
181+
window.addEventListener('popstate', onPopState);
182+
KEY_REFRESH_EVENTS.forEach((event) =>
183+
window.addEventListener(event, refreshKey, { passive: true })
184+
);
185+
document.addEventListener('visibilitychange', saveIfHidden);
186+
187+
return () => {
188+
stop();
189+
router.events.off('routeChangeStart', save);
190+
window.removeEventListener('popstate', onPopState);
191+
KEY_REFRESH_EVENTS.forEach((event) =>
192+
window.removeEventListener(event, refreshKey)
193+
);
194+
document.removeEventListener('visibilitychange', saveIfHidden);
195+
};
196+
}, [router.asPath, router.events]);
197+
};
198+
199+
export default useScrollRestoration;

‎src/hooks/useSearchInput.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,15 @@ const useSearchInput = (): SearchObject => {
3434
useEffect(() => {
3535
if (debouncedValue !== '' && searchOpen) {
3636
if (router.pathname.startsWith('/search')) {
37-
router.replace({
38-
pathname: router.pathname,
39-
query: {
40-
...router.query,
41-
query: debouncedValue,
42-
},
43-
});
37+
if (router.query.query !== debouncedValue) {
38+
router.replace({
39+
pathname: router.pathname,
40+
query: {
41+
...router.query,
42+
query: debouncedValue,
43+
},
44+
});
45+
}
4446
} else {
4547
setLastRoute(router.asPath);
4648
router

‎src/pages/_app.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { InteractionProvider } from '@app/context/InteractionContext';
77
import { LanguageContext } from '@app/context/LanguageContext';
88
import { SettingsProvider } from '@app/context/SettingsContext';
99
import { UserContext } from '@app/context/UserContext';
10+
import useScrollRestoration from '@app/hooks/useScrollRestoration';
1011
import type { User } from '@app/hooks/useUser';
1112
import { Permission, useUser } from '@app/hooks/useUser';
1213
import '@app/styles/globals.css';
@@ -130,6 +131,7 @@ const CoreApp: Omit<NextAppComponentType, 'origGetInitialProps'> = ({
130131
let component: React.ReactNode;
131132
const [loadedMessages, setMessages] = useState<MessagesType>(messages);
132133
const [currentLocale, setLocale] = useState<AvailableLocale>(locale);
134+
useScrollRestoration();
133135

134136
useEffect(() => {
135137
loadLocaleData(currentLocale).then(setMessages);

0 commit comments

Comments
 (0)