From 33817bbe4214a6568dc41bb900db020bddfdab4c Mon Sep 17 00:00:00 2001 From: bbassie <17990055+bbassie@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:43:57 +0000 Subject: [PATCH] Remember scroll position on back/forward and reload BrowserRouter has no scroll handling and the browser's own restoration runs before the page has loaded its data, so it lands short. Track the window scroll per history entry in sessionStorage and restore it on POP, retrying as the page grows until it fits, the user scrolls or 5 s pass. Pushing a new pathname scrolls to the top; query-only pushes (table sort, filter, page) keep the position. Closes #1247 Co-Authored-By: Claude Opus 5.5 --- packages/web_ui/src/components/SiteLayout.tsx | 2 + .../web_ui/src/util/useScrollRestoration.ts | 138 ++++++++++++++++++ test/web_ui/useScrollRestoration.js | 63 ++++++++ 3 files changed, 203 insertions(+) create mode 100644 packages/web_ui/src/util/useScrollRestoration.ts create mode 100644 test/web_ui/useScrollRestoration.js diff --git a/packages/web_ui/src/components/SiteLayout.tsx b/packages/web_ui/src/components/SiteLayout.tsx index ed03e0ad..8bd02e75 100644 --- a/packages/web_ui/src/components/SiteLayout.tsx +++ b/packages/web_ui/src/components/SiteLayout.tsx @@ -11,6 +11,7 @@ import AboutModal from "./AboutModal"; import Link from "./Link"; import { saveJson } from "../util/save_file"; +import useScrollRestoration from "../util/useScrollRestoration"; import { useAccount } from "../model/account"; import { DraggingContext } from "../model/is_dragging"; import webUiPackage from "../../package.json"; @@ -50,6 +51,7 @@ function isActiveDropzone(element: HTMLElement | null): boolean { export default function SiteLayout() { let navigate = useNavigate(); + useScrollRestoration(); let [currentSidebarPath, setCurrentSidebarPath] = useState(null); const screens = Grid.useBreakpoint(); // On phone screens the sidebar becomes an overlay drawer instead of a fixed sider. diff --git a/packages/web_ui/src/util/useScrollRestoration.ts b/packages/web_ui/src/util/useScrollRestoration.ts new file mode 100644 index 00000000..05941397 --- /dev/null +++ b/packages/web_ui/src/util/useScrollRestoration.ts @@ -0,0 +1,138 @@ +import { useEffect, useLayoutEffect, useRef } from "react"; +import { type Location, useLocation, useNavigationType } from "react-router-dom"; + +const storageKey = "scroll_positions"; +const maxEntries = 100; +const restoreTimeoutMs = 5000; + +/** Read saved scroll positions, oldest first. */ +export function loadScrollPositions(storage: Pick): Map { + try { + const stored = JSON.parse(storage.getItem(storageKey) ?? "[]"); + if (Array.isArray(stored)) { + return new Map(stored.filter( + (entry): entry is [string, number] => typeof entry[0] === "string" && typeof entry[1] === "number" + )); + } + } catch { + // Fall through to an empty map on corrupt data. + } + return new Map(); +} + +/** Record a position as the newest entry, dropping the oldest past the limit. */ +export function setScrollPosition(positions: Map, key: string, y: number) { + positions.delete(key); + positions.set(key, y); + for (const oldest of positions.keys()) { + if (positions.size <= maxEntries) { + break; + } + positions.delete(oldest); + } +} + +export function saveScrollPositions(storage: Pick, positions: Map) { + try { + storage.setItem(storageKey, JSON.stringify([...positions])); + } catch { + // Ignore storage errors (e.g. quota exceeded or storage disabled). + } +} + +/** History entries created outside the router all share the key "default". */ +export function scrollKey(location: Pick) { + return location.key === "default" ? `${location.pathname}${location.search}` : location.key; +} + +/** + * Scroll to y, retrying as the page grows while its data loads. Gives up after + * a timeout or when the user scrolls. + */ +function restoreScroll(y: number, onDone: () => void) { + const inputEvents = ["wheel", "touchstart", "keydown", "pointerdown"]; + const observer = new ResizeObserver(attempt); + const timeout = setTimeout(stop, restoreTimeoutMs); + let stopped = false; + + function stop() { + if (stopped) { + return; + } + stopped = true; + observer.disconnect(); + clearTimeout(timeout); + for (const event of inputEvents) { + window.removeEventListener(event, stop, true); + } + onDone(); + } + + function attempt() { + window.scrollTo(0, y); + if (window.scrollY >= y - 1) { + stop(); + } + } + + for (const event of inputEvents) { + window.addEventListener(event, stop, { capture: true, passive: true }); + } + observer.observe(document.body); + attempt(); + return stop; +} + +/** + * Restore the window scroll position on back/forward and page reload, and + * scroll to the top when navigating to another page. + */ +export default function useScrollRestoration() { + const location = useLocation(); + const navigationType = useNavigationType(); + const key = scrollKey(location); + const positions = useRef | null>(null); + const currentKey = useRef(key); + const restoring = useRef(false); + const pathname = useRef(location.pathname); + if (!positions.current) { + positions.current = loadScrollPositions(sessionStorage); + } + + useEffect(() => { + window.history.scrollRestoration = "manual"; + function onScroll() { + if (!restoring.current) { + setScrollPosition(positions.current!, currentKey.current, window.scrollY); + } + } + function persist() { + saveScrollPositions(sessionStorage, positions.current!); + } + window.addEventListener("scroll", onScroll, { passive: true }); + window.addEventListener("pagehide", persist); + return () => { + window.removeEventListener("scroll", onScroll); + window.removeEventListener("pagehide", persist); + persist(); + }; + }, []); + + useLayoutEffect(() => { + currentKey.current = key; + saveScrollPositions(sessionStorage, positions.current!); + const pathChanged = pathname.current !== location.pathname; + pathname.current = location.pathname; + // Table sort, filter and page changes only change the query + if (navigationType === "PUSH" && pathChanged) { + window.scrollTo(0, 0); + return undefined; + } + if (navigationType !== "POP") { + setScrollPosition(positions.current!, key, window.scrollY); + return undefined; + } + restoring.current = true; + return restoreScroll(positions.current!.get(key) ?? 0, () => { restoring.current = false; }); + }, [key]); +} diff --git a/test/web_ui/useScrollRestoration.js b/test/web_ui/useScrollRestoration.js new file mode 100644 index 00000000..9bc748e4 --- /dev/null +++ b/test/web_ui/useScrollRestoration.js @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; + +import { + loadScrollPositions, saveScrollPositions, scrollKey, setScrollPosition, +} from "../../packages/web_ui/src/util/useScrollRestoration.ts"; + +class MemoryStorage { + items = new Map(); + getItem(key) { return this.items.get(key) ?? null; } + setItem(key, value) { this.items.set(key, String(value)); } +} + +describe("web_ui/util/useScrollRestoration", function() { + describe("loadScrollPositions()", function() { + it("should round trip through saveScrollPositions", function() { + const storage = new MemoryStorage(); + saveScrollPositions(storage, new Map([["a", 10], ["b", 20.5]])); + assert.deepEqual([...loadScrollPositions(storage)], [["a", 10], ["b", 20.5]]); + }); + it("should return an empty map when nothing is stored", function() { + assert.equal(loadScrollPositions(new MemoryStorage()).size, 0); + }); + it("should ignore corrupt data", function() { + const storage = new MemoryStorage(); + storage.setItem("scroll_positions", "{not json"); + assert.equal(loadScrollPositions(storage).size, 0); + storage.setItem("scroll_positions", JSON.stringify({ a: 1 })); + assert.equal(loadScrollPositions(storage).size, 0); + storage.setItem("scroll_positions", JSON.stringify([["a", 1], ["b", "x"], [2, 3]])); + assert.deepEqual([...loadScrollPositions(storage)], [["a", 1]]); + }); + }); + describe("saveScrollPositions()", function() { + it("should ignore storage errors", function() { + saveScrollPositions({ setItem() { throw new Error("QuotaExceededError"); } }, new Map([["a", 1]])); + }); + }); + describe("setScrollPosition()", function() { + it("should move an updated key to the newest position", function() { + const positions = new Map([["a", 1], ["b", 2]]); + setScrollPosition(positions, "a", 3); + assert.deepEqual([...positions], [["b", 2], ["a", 3]]); + }); + it("should drop the oldest entries past 100", function() { + const positions = new Map(); + for (let i = 0; i < 105; i++) { + setScrollPosition(positions, `k${i}`, i); + } + assert.equal(positions.size, 100); + assert.equal(positions.has("k4"), false); + assert.equal(positions.get("k5"), 5); + assert.equal(positions.get("k104"), 104); + }); + }); + describe("scrollKey()", function() { + it("should use the location key", function() { + assert.equal(scrollKey({ key: "abc123", pathname: "/users", search: "" }), "abc123"); + }); + it("should fall back to the path for entries created outside the router", function() { + assert.equal(scrollKey({ key: "default", pathname: "/users", search: "?q=a" }), "/users?q=a"); + }); + }); +});