fix: avoid reload for user-code history changes (#3045) (#3048)

The Fresh partials popstate handler causes page reloads when user code
makes use of navigation history state. This can lead to a loss of user
data in a browsing context.
To fix this behavior, FreshHistoryState now has a flag which validates
partials functionality/explicitly opts-in to any partial related
location management.
This commit is contained in:
Chris
2025-07-09 20:59:32 +02:00
committed by GitHub
parent 3e211dc7ec
commit d072dc2fc0
2 changed files with 41 additions and 0 deletions
+9
View File
@@ -27,7 +27,11 @@ export const PARTIAL_ATTR = "f-partial";
class NoPartialsError extends Error {}
// Fresh partials history updates set the fClientNav flag
// and prevent reloads in the popstate handler when
// user-code triggers history navigation events.
export interface FreshHistoryState {
fClientNav: boolean;
index: number;
scrollX: number;
scrollY: number;
@@ -43,6 +47,7 @@ function checkClientNavEnabled(el: HTMLElement) {
let index = history.state?.index || 0;
if (!history.state) {
const state: FreshHistoryState = {
fClientNav: true,
index,
scrollX,
scrollY,
@@ -56,6 +61,7 @@ function maybeUpdateHistory(nextUrl: URL) {
// "refresh" the current page.
if (nextUrl.href !== globalThis.location.href) {
const state: FreshHistoryState = {
fClientNav: true,
index,
scrollX: globalThis.scrollX,
scrollY: globalThis.scrollY,
@@ -164,6 +170,9 @@ addEventListener("popstate", async (e) => {
}
return;
}
// Do nothing if Fresh navigation is not explicitly opted-in.
// Other applications might manage scrollRestoration individually.
if (!e.state.fClientNav) return;
const state: FreshHistoryState = history.state;
const nextIdx = state.index ?? index + 1;