`useBeforeLeave` and scroll restoration break on Back after 50 history entries (`_depth` taken from the capped `history.length`)
Los mantenedores suelen responder en 1 día
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 1-2 días
- Aptitud para principiantes
- 57/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- typescript
- Área
- frontend
Línea de trabajo
Start by reading saveCurrentDepth() and notifyIfNotBlocked in src/lifecycle.ts, then trace set() in src/routers/history.ts on next and the matching router code in src/routers/scrollRestoration.ts. Check how depth is assigned after the browser history reaches its entry cap and how Back and Forward use it. Done means navigation blocking and scroll restoration work across the cap, including after going Back and pushing a new entry.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Describe the bug
saveCurrentDepth() (src/lifecycle.ts) stamps a new entry with _depth: window.history.length - 1:
export function saveCurrentDepth() {
if (!window.history.state || window.history.state._depth == null) {
window.history.replaceState({ ...window.history.state, _depth: window.history.length - 1 }, "");
}
depth = window.history.state._depth;
}
Chromium (kMaxSessionHistoryEntries) and Firefox (browser.sessionhistory.max_entries) cap the session history at 50 entries (WebKit at 100, not tested). Once it is full, pushState drops the oldest entry and history.length stays at 50, so every new entry gets the same _depth as the one below it.
Everything keyed on _depth then misbehaves between those entries:
notifyIfNotBlocked(src/lifecycle.ts): Back from the newest entry computesdelta = 0, soif (delta && block(delta))skipsblock:useBeforeLeavelisteners are never called and the navigation can't be prevented.createScrollRestoration(src/routers/scrollRestoration.ts, same path onnext): positions are stored per depth, so consecutive entries share one slot, andonPush()deletes every key>= depth. Back restores the offset of the entry just left instead of its own.
Present in 1.0.0 (latest on npm) / main (set() in Router and HashRouter), and on next (2.0.0-next.42) in src/routers/history.ts (saveCurrentDepth, set() in browserHistory() and hashHistory()), where scroll restoration is on by default with the default browser history, so it hits without opting in.
Your Example Website or App
Minimal code below; no hosted repro needed, it shows from the console in any Chromium or Firefox tab.
Steps to Reproduce the Bug or Issue
Fresh tab (so the history starts at length 1):
import { render } from "solid-js/web";
import { Router, Route, useNavigate, useBeforeLeave, useParams } from "@solidjs/router";
function Page() {
const params = useParams();
(window as any).nav = useNavigate();
useBeforeLeave((e) => {
if ((window as any).guard && !confirm("Leave?")) e.preventDefault();
});
return <p>page {params.n}</p>;
}
render(
() => (
<Router>
<Route path="/:n?" component={Page} />
</Router>
),
document.getElementById("root")!,
);
In the console:
for (let i = 1; i <= 52; i++) {
nav(`/${i}`);
await new Promise((r) => setTimeout(r));
console.log(i, history.length, history.state._depth);
}
Then run guard = true and press the browser Back button.
Expected behavior
_depthequalsion every line: the last three print 50, 51, 52.- Back triggers the
useBeforeLeaveconfirm.
Actual:
- From
i = 50on,history.lengthstays 50 and_depthstays 49 (Firefox: 50, as it applies its cap asynchronously). - Back navigates to
/51without the confirm (deltais 0). With<Router scrollRestoration>and a page taller than the window, scrolled before the last push, Back restores the offset of the entry just left.
Below the cap (e.g. Back from /10) the confirm shows and blocking works.
Platform
- OS: Linux
- Browser: Chromium 156.0.8078.4, Firefox 157
@solidjs/router: 1.0.0 (same code onnext2.0.0-next.42)
Additional context
Suggested fix: stamp each entry the router pushes from the depth of the entry it leaves, rather than from history.length. depth isn't exported from lifecycle.ts, so e.g. a small helper there:
export const nextDepth = () => depth + 1;
// in set() of Router / HashRouter:
window.history.pushState({ ...state, _depth: nextDepth() }, "", value);
and the fallback in saveCurrentDepth() becomes _depth: depth == null ? window.history.length - 1 : depth + 1, so entries pushed outside the router (e.g. location.hash) keep counting up past the cap too.
depth + 1 equals today's value below the cap, including after going Back (pushState drops the forward entries). A Math.max(history.length - 1, depth + 1) variant is wrong there: history.length is read before the forward entries are dropped, so after going Back 3 entries and navigating, the new entry is over-stamped, so a Back that useBeforeLeave prevents still goes through: the listener sees delta -3 instead of -1, and the router's go(3) undo has no forward entries to return to. With the change above, I checked in Chromium and Firefox that Back and Forward past the cap are blocked, scroll is restored, and a reload keeps the stamped depth. replace goes through keepDepth, which the change doesn't touch (from reading the code).
- Lenguaje dominante
- TypeScript
- Estrellas
- 1.3k
- Forks
- 185
- Merge medio
- 15 h 47 min
- PR fusionados (30 d)
- 47
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de solidjs/solid-router
-
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
solidjs/solid-router#696 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
solidjs/solid-router#691 ·
Los mantenedores suelen responder en 1 día
-
Forward pressed while a Back navigation is still loading is dropped; the URL and the rendered route get out of syncPosiblemente ocupada @sean0407 la tomó hace 10 días. Abierto1.x
Dificultad 4/5 1-2 días Aptitud para principiantes 54/100
solidjs/solid-router#687 ·
Los mantenedores suelen responder en 1 día
-
<A> costs ~6us of server CPU per instance during SSR (20x a plain <a>), mostly mergeProps/splitPropsPosiblemente ocupada @birkskyum la tomó hace 81 días. Abierto1.x
Dificultad 4/5 3-5 días Aptitud para principiantes 55/100
solidjs/solid-router#583 ·
Los mantenedores suelen responder en 1 día
-
1.x enhancement
Dificultad 3/5 1-2 días Aptitud para principiantes 38/100
solidjs/solid-router#518 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de solidjs/solid-router
Issues similares
-
bug
Dificultad 1/5 Menos de una hora Aptitud para principiantes 86/100
awslabs/visual-asset-management-system#937 ·
Los mantenedores suelen responder en 1 día
-
t0ggles
Dificultad 1/5 Menos de una hora Aptitud para principiantes 82/100
nolimits4web/swiper#8255 · 1 comentario ·
Los mantenedores suelen responder en 15 días
-
render: --variables-file (and --variables <path>) fails with "io.readFile is not a function" since 0.8.212Posiblemente ocupada @miguel-heygen la tomó hoy. Abiertobug triage/needs-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
heygen-com/hyperframes#6830 ·
Los mantenedores suelen responder en 1 día
-
bug launch local use
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
Los mantenedores suelen responder en 1 día
-
account: profile bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 5 días