Move scroll restoration logic out of the hook for testing

The effects now call a ScrollRestorer class and restoreScroll is exported,
so the tests can drive both against a fake window, sessionStorage and
ResizeObserver. The hook is three lines that wire them to the router.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-21 02:50:12 +00:00
1 parent 33817bbe42
commit 628e59bf2c
2 files changed
+241 -48

No files matched your search

@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef } from "react";
import { type Location, useLocation, useNavigationType } from "react-router-dom";
import { useEffect, useLayoutEffect, useState } from "react";
import { type Location, type NavigationType, useLocation, useNavigationType } from "react-router-dom";
const storageKey = "scroll_positions";
const maxEntries = 100;
@@ -49,7 +49,7 @@ export function scrollKey(location: Pick<Location, "key" | "pathname" | "search"
* 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) {
export function restoreScroll(y: number, onDone: () => void) {
const inputEvents = ["wheel", "touchstart", "keydown", "pointerdown"];
const observer = new ResizeObserver(attempt);
const timeout = setTimeout(stop, restoreTimeoutMs);
@@ -83,6 +83,56 @@ function restoreScroll(y: number, onDone: () => void) {
return stop;
}
export class ScrollRestorer {
positions = loadScrollPositions(sessionStorage);
restoring = false;
key: string;
pathname: string;
constructor(key: string, pathname: string) {
this.key = key;
this.pathname = pathname;
}
/** Start recording scroll positions, returns a function that stops it. */
attach() {
window.history.scrollRestoration = "manual";
const onScroll = () => {
if (!this.restoring) {
setScrollPosition(this.positions, this.key, window.scrollY);
}
};
const persist = () => saveScrollPositions(sessionStorage, this.positions);
window.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("pagehide", persist);
return () => {
window.removeEventListener("scroll", onScroll);
window.removeEventListener("pagehide", persist);
persist();
};
}
/** Handle a location change, returns a function that cancels a pending restore. */
navigate(key: string, pathname: string, navigationType: NavigationType) {
this.key = key;
saveScrollPositions(sessionStorage, this.positions);
const pathChanged = this.pathname !== pathname;
this.pathname = 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(this.positions, key, window.scrollY);
return undefined;
}
this.restoring = true;
return restoreScroll(this.positions.get(key) ?? 0, () => { this.restoring = false; });
}
}
/**
* Restore the window scroll position on back/forward and page reload, and
* scroll to the top when navigating to another page.
@@ -91,48 +141,7 @@ export default function useScrollRestoration() {
const location = useLocation();
const navigationType = useNavigationType();
const key = scrollKey(location);
const positions = useRef<Map<string, number> | 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]);
const [restorer] = useState(() => new ScrollRestorer(key, location.pathname));
useEffect(() => restorer.attach(), []);
useLayoutEffect(() => restorer.navigate(key, location.pathname, navigationType), [key]);
}
+185 -1
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import {
loadScrollPositions, saveScrollPositions, scrollKey, setScrollPosition,
ScrollRestorer, loadScrollPositions, restoreScroll, saveScrollPositions, scrollKey, setScrollPosition,
} from "../../packages/web_ui/src/util/useScrollRestoration.ts";
class MemoryStorage {
@@ -10,6 +10,68 @@ class MemoryStorage {
setItem(key, value) { this.items.set(key, String(value)); }
}
class FakeWindow {
scrollY = 0;
maxScroll = 0;
listeners = new Map();
history = { scrollRestoration: "auto" };
scrollTo(_x, y) {
this.scrollY = Math.max(0, Math.min(y, this.maxScroll));
this.emit("scroll");
}
addEventListener(type, listener) {
if (!this.listeners.has(type)) {
this.listeners.set(type, new Set());
}
this.listeners.get(type).add(listener);
}
removeEventListener(type, listener) {
this.listeners.get(type)?.delete(listener);
}
emit(type) {
for (const listener of [...this.listeners.get(type) ?? []]) {
listener();
}
}
count(type) {
return this.listeners.get(type)?.size ?? 0;
}
}
class FakeResizeObserver {
static observers = new Set();
constructor(callback) { this.callback = callback; }
observe() { FakeResizeObserver.observers.add(this); }
disconnect() { FakeResizeObserver.observers.delete(this); }
}
function resize(maxScroll) {
window.maxScroll = maxScroll;
for (const observer of [...FakeResizeObserver.observers]) {
observer.callback();
}
}
function withDom() {
beforeEach(function() {
FakeResizeObserver.observers.clear();
globalThis.window = new FakeWindow();
globalThis.document = { body: {} };
globalThis.sessionStorage = new MemoryStorage();
globalThis.ResizeObserver = FakeResizeObserver;
});
afterEach(function() {
delete globalThis.window;
delete globalThis.document;
delete globalThis.sessionStorage;
delete globalThis.ResizeObserver;
});
}
describe("web_ui/util/useScrollRestoration", function() {
describe("loadScrollPositions()", function() {
it("should round trip through saveScrollPositions", function() {
@@ -60,4 +122,126 @@ describe("web_ui/util/useScrollRestoration", function() {
assert.equal(scrollKey({ key: "default", pathname: "/users", search: "?q=a" }), "/users?q=a");
});
});
describe("restoreScroll()", function() {
withDom();
it("should scroll immediately when the page is tall enough", function() {
window.maxScroll = 2000;
let done = 0;
restoreScroll(1500, () => { done += 1; });
assert.equal(window.scrollY, 1500);
assert.equal(done, 1);
assert.equal(FakeResizeObserver.observers.size, 0);
assert.equal(window.count("wheel"), 0);
});
it("should retry as the page grows", function() {
let done = 0;
restoreScroll(1500, () => { done += 1; });
assert.equal(window.scrollY, 0);
resize(800);
assert.equal(window.scrollY, 800);
assert.equal(done, 0);
resize(3000);
assert.equal(window.scrollY, 1500);
assert.equal(done, 1);
});
it("should give up when the user scrolls", function() {
let done = 0;
restoreScroll(1500, () => { done += 1; });
window.emit("wheel");
assert.equal(done, 1);
resize(3000);
assert.equal(window.scrollY, 0);
});
it("should give up after the timeout", function() {
const realSetTimeout = globalThis.setTimeout;
let fire;
globalThis.setTimeout = (callback, ms) => {
assert.equal(ms, 5000);
fire = callback;
return 0;
};
let done = 0;
try {
restoreScroll(1500, () => { done += 1; });
} finally {
globalThis.setTimeout = realSetTimeout;
}
fire();
assert.equal(done, 1);
resize(3000);
assert.equal(window.scrollY, 0);
});
it("should stop only once when cancelled", function() {
let done = 0;
const stop = restoreScroll(1500, () => { done += 1; });
stop();
stop();
assert.equal(done, 1);
});
});
describe("class ScrollRestorer", function() {
withDom();
it("should record scroll positions per key and persist them", function() {
const restorer = new ScrollRestorer("a", "/users");
const detach = restorer.attach();
assert.equal(window.history.scrollRestoration, "manual");
window.maxScroll = 2000;
window.scrollTo(0, 700);
window.emit("pagehide");
assert.deepEqual([...loadScrollPositions(sessionStorage)], [["a", 700]]);
window.scrollTo(0, 900);
detach();
assert.deepEqual([...loadScrollPositions(sessionStorage)], [["a", 900]]);
assert.equal(window.count("scroll"), 0);
assert.equal(window.count("pagehide"), 0);
});
it("should scroll to the top when pushing another path", function() {
const restorer = new ScrollRestorer("a", "/users");
restorer.attach();
window.maxScroll = 2000;
window.scrollTo(0, 1500);
restorer.navigate("b", "/users/x/view", "PUSH");
assert.equal(window.scrollY, 0);
assert.deepEqual([...loadScrollPositions(sessionStorage)], [["a", 1500]]);
});
it("should keep the position when only the query changes", function() {
const restorer = new ScrollRestorer("a", "/users");
restorer.attach();
window.maxScroll = 2000;
window.scrollTo(0, 1500);
restorer.navigate("b", "/users", "PUSH");
assert.equal(window.scrollY, 1500);
assert.equal(restorer.positions.get("b"), 1500);
restorer.navigate("c", "/users", "REPLACE");
assert.equal(restorer.positions.get("c"), 1500);
});
it("should restore the saved position on pop", function() {
saveScrollPositions(sessionStorage, new Map([["a", 1500], ["b", 0]]));
const restorer = new ScrollRestorer("b", "/users/x/view");
restorer.attach();
window.maxScroll = 2000;
window.scrollTo(0, 400);
assert.equal(restorer.positions.get("b"), 400);
restorer.navigate("a", "/users", "POP");
assert.equal(window.scrollY, 1500);
restorer.navigate("b", "/users/x/view", "POP");
assert.equal(window.scrollY, 400);
restorer.navigate("unknown", "/hosts", "POP");
assert.equal(window.scrollY, 0);
});
it("should not record positions while restoring", function() {
saveScrollPositions(sessionStorage, new Map([["a", 1500]]));
const restorer = new ScrollRestorer("a", "/users");
restorer.attach();
const cancel = restorer.navigate("a", "/users", "POP");
resize(600);
assert.equal(window.scrollY, 600);
assert.equal(restorer.positions.get("a"), 1500);
cancel();
window.scrollTo(0, 300);
assert.equal(restorer.positions.get("a"), 300);
});
});
});