Skip to content

Commit eaafba6

Browse files
fix(history): stamp history depth from the current entry, not history.length (#708)
Browsers cap session history (50 entries in Chromium and Firefox). Once the cap is reached, pushState drops the oldest entry and history.length stays the same, so `history.length - 1` gave every new entry the depth of the one below it. Back then computed a zero delta (useBeforeLeave was skipped) and scroll restoration shared one slot between entries. Router and HashRouter now stamp a pushed entry with the current depth + 1, and saveCurrentDepth() stamps an entry the router didn't push (e.g. a #anchor jump) one above the last known depth, falling back to history.length only when no depth is known. Replace keeps the current depth as before. This is the 1.x counterpart of #695 and #707 on `next`. Fixes #694
1 parent d0379e7 commit eaafba6

5 files changed

Lines changed: 129 additions & 7 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/router": patch
3+
---
4+
5+
Stamp history depth from the current entry instead of `history.length`, so `useBeforeLeave` and scroll restoration keep working on Back once the browser's session history is full (#694)

‎src/lifecycle.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,16 @@ export function createBeforeLeave(): BeforeLeaveLifecycle {
4747

4848
let depth: number;
4949
export function saveCurrentDepth() {
50-
if (!window.history.state || window.history.state._depth == null) {
51-
window.history.replaceState({ ...window.history.state, _depth: window.history.length - 1 }, "");
50+
const h = window.history;
51+
let d = h.state && h.state._depth;
52+
if (d == null) {
53+
// An entry the router didn't push (e.g. a `#anchor` jump) sits one above
54+
// the last known one. `history.length` stops growing once the browser's
55+
// session history is full, so only fall back to it when nothing is known.
56+
d = depth == null ? h.length - 1 : depth + 1;
57+
h.replaceState({ ...h.state, _depth: d }, "");
5258
}
53-
depth = window.history.state._depth;
59+
depth = (h.state && h.state._depth) ?? d;
5460
}
5561
if (!isServer) {
5662
saveCurrentDepth();
@@ -63,6 +69,19 @@ export function keepDepth(state: any) {
6369
};
6470
}
6571

72+
// A pushed entry sits one above the current one. Stamp it from the current
73+
// depth, not `history.length`: once the browser's session history is full (50
74+
// entries in Chromium and Firefox) a push drops the oldest entry and `length`
75+
// stays the same, so `length - 1` would give every new entry the depth of the
76+
// one below it.
77+
export function nextDepth(state: any) {
78+
const current = (window.history.state && window.history.state._depth) ?? depth;
79+
return {
80+
...state,
81+
_depth: (current ?? window.history.length - 1) + 1
82+
};
83+
}
84+
6685
export function notifyIfNotBlocked(
6786
notify: (value?: string | LocationChange) => void,
6887
block: (delta: number | null) => boolean

‎src/routers/HashRouter.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { JSX } from "solid-js";
22
import { setupNativeEvents } from "../data/events.js";
33
import type { BaseRouterProps } from "./components.jsx";
44
import { createRouter, scrollToHash, bindEvent } from "./createRouter.js";
5-
import { createBeforeLeave, keepDepth, notifyIfNotBlocked, saveCurrentDepth } from "../lifecycle.js";
5+
import { createBeforeLeave, keepDepth, nextDepth, notifyIfNotBlocked, saveCurrentDepth } from "../lifecycle.js";
66

77
export function hashParser(str: string) {
88
const to = str.replace(/^.*?#/, "");
@@ -27,7 +27,7 @@ export function HashRouter(props: HashRouterProps): JSX.Element {
2727
if (replace) {
2828
window.history.replaceState(keepDepth(state), "", "#" + value);
2929
} else {
30-
window.history.pushState(state, "", "#" + value);
30+
window.history.pushState(nextDepth(state), "", "#" + value);
3131
}
3232
const hashIndex = value.indexOf("#");
3333
const hash = hashIndex >= 0 ? value.slice(hashIndex + 1) : "";

‎src/routers/Router.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { StaticRouter } from "./StaticRouter.js";
44
import { setupNativeEvents } from "../data/events.js";
55
import type { BaseRouterProps } from "./components.jsx";
66
import type { JSX } from "solid-js";
7-
import { createBeforeLeave, keepDepth, notifyIfNotBlocked, saveCurrentDepth } from "../lifecycle.js";
7+
import { createBeforeLeave, keepDepth, nextDepth, notifyIfNotBlocked, saveCurrentDepth } from "../lifecycle.js";
88
import { createScrollRestoration } from "./scrollRestoration.js";
99

1010
export type RouterProps = BaseRouterProps & {
@@ -40,7 +40,7 @@ export function Router(props: RouterProps): JSX.Element {
4040
if (replace) {
4141
window.history.replaceState(keepDepth(state), "", value);
4242
} else {
43-
window.history.pushState(state, "", value);
43+
window.history.pushState(nextDepth(state), "", value);
4444
}
4545
scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
4646
saveCurrentDepth();

‎test/history-depth.spec.tsx‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import { render } from "solid-js/web";
2+
import { vi } from "vitest";
3+
import { HashRouter, Router, Route, useNavigate } from "../src/index.js";
4+
import type { Navigator } from "../src/index.js";
5+
import { notifyIfNotBlocked } from "../src/lifecycle.js";
6+
7+
// #694: browsers cap session history (50 entries in Chromium and Firefox).
8+
// Once full, a push drops the oldest entry and history.length stops growing,
9+
// so depths taken from history.length repeat.
10+
describe("history depth when history.length is capped (#694)", () => {
11+
afterEach(() => {
12+
vi.restoreAllMocks();
13+
document.body.innerHTML = "";
14+
});
15+
16+
const url = () => window.location.pathname + window.location.search + window.location.hash;
17+
18+
async function pushThree(RouterComponent: typeof Router | typeof HashRouter, hash = false) {
19+
let navigate!: Navigator;
20+
const Page = () => {
21+
navigate = useNavigate();
22+
return null;
23+
};
24+
const dispose = render(
25+
() => (
26+
<RouterComponent>
27+
<Route path="/:n?" component={Page} />
28+
</RouterComponent>
29+
),
30+
document.body
31+
);
32+
try {
33+
const depths: number[] = [];
34+
for (let i = 1; i <= 3; i++) {
35+
navigate(`/${i}`);
36+
await vi.waitFor(() => expect(url()).toBe(hash ? `/#/${i}` : `/${i}`));
37+
depths.push(window.history.state._depth);
38+
}
39+
navigate("/3?replaced", { replace: true });
40+
await vi.waitFor(() => expect(url()).toBe(hash ? "/#/3?replaced" : "/3?replaced"));
41+
depths.push(window.history.state._depth);
42+
return depths;
43+
} finally {
44+
dispose();
45+
}
46+
}
47+
48+
test("Router stamps increasing depths on push", async () => {
49+
window.history.replaceState({ _depth: 48 }, "", "/");
50+
vi.spyOn(window.history, "length", "get").mockReturnValue(50);
51+
expect(await pushThree(Router)).toEqual([49, 50, 51, 51]);
52+
});
53+
54+
test("HashRouter stamps increasing depths on push", async () => {
55+
window.history.replaceState({ _depth: 48 }, "", "/");
56+
vi.spyOn(window.history, "length", "get").mockReturnValue(50);
57+
expect(await pushThree(HashRouter, true)).toEqual([49, 50, 51, 51]);
58+
});
59+
60+
test("Router keeps user state when stamping the depth on push", async () => {
61+
window.history.replaceState({ _depth: 3 }, "", "/");
62+
let navigate!: Navigator;
63+
const dispose = render(
64+
() => (
65+
<Router>
66+
<Route
67+
path="/*"
68+
component={() => {
69+
navigate = useNavigate();
70+
return null;
71+
}}
72+
/>
73+
</Router>
74+
),
75+
document.body
76+
);
77+
try {
78+
navigate("/next", { state: { from: "test" } });
79+
await vi.waitFor(() => expect(url()).toBe("/next"));
80+
expect(window.history.state).toEqual({ from: "test", _depth: 4 });
81+
} finally {
82+
dispose();
83+
}
84+
});
85+
86+
test("an entry pushed outside the router counts up from the last depth", () => {
87+
window.history.replaceState({ _depth: 49 }, "", "/");
88+
vi.spyOn(window.history, "length", "get").mockReturnValue(50);
89+
const notify = vi.fn();
90+
const handler = notifyIfNotBlocked(notify, () => false);
91+
handler(); // record the current depth
92+
notify.mockClear();
93+
window.history.pushState(null, "", "/#anchor");
94+
handler();
95+
expect(window.history.state._depth).toBe(50);
96+
expect(notify).toHaveBeenCalledTimes(1);
97+
});
98+
});

0 commit comments

Comments
 (0)