forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

scroll-restore.ts59 lines, 2.1 KiBHistoryRawDownload
1import { createEffect, onCleanup, onMount } from "solid-js";
2
3/** The router's id for the current history entry (TanStack keeps it in `history.state`). */
4function historyEntry(): string {
5 const state = history.state as Record<string, unknown> | null;
6 return String(state?.__TSR_key ?? state?.key ?? "");
7}
8
9/**
10 * Put the page back where the reader left it when they return to the same
11 * history entry (Back from a detail page). The router's own restoration runs
12 * before a list's rows arrive, so it clamps to a short page and a long list
13 * came back near the top. This remembers the window offset per entry and
14 * re-applies it once `ready()` says the rows are drawn — never on a fresh
15 * visit, which gets a new entry id.
16 */
17export function createScrollRestore(key: string | null, ready: () => boolean) {
18 if (!key || typeof window === "undefined") return;
19 const name = `scroll:${key}`;
20
21 let saveTimer: ReturnType<typeof setTimeout> | undefined;
22 const save = () => {
23 clearTimeout(saveTimer);
24 saveTimer = setTimeout(() => {
25 try {
26 sessionStorage.setItem(name, JSON.stringify({ y: Math.round(window.scrollY), entry: historyEntry() }));
27 } catch {
28 // storage blocked: no restore, nothing else breaks
29 }
30 }, 150);
31 };
32 onMount(() => {
33 window.addEventListener("scroll", save, { passive: true });
34 onCleanup(() => {
35 clearTimeout(saveTimer);
36 window.removeEventListener("scroll", save);
37 });
38 });
39
40 let restored = false;
41 createEffect(() => {
42 if (restored || !ready()) return;
43 restored = true;
44 try {
45 const saved = JSON.parse(sessionStorage.getItem(name) ?? "null") as { y?: number; entry?: string } | null;
46 const target = saved?.y;
47 if (!target || saved.entry !== historyEntry()) return;
48 // Correct once the rows are laid out, and once more after late content
49 // (avatars, badges, images) settles.
50 const settle = () => {
51 if (Math.abs(window.scrollY - target) > 8) window.scrollTo(0, target);
52 };
53 requestAnimationFrame(settle);
54 setTimeout(settle, 300);
55 } catch {
56 // malformed entry: start at the top
57 }
58 });
59}