Unverified Commit 48a50718 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Update history in useInsertionEffect (#48553)

### What?

Currently `pushState` / `replaceState` happens in `useEffect`. This
causes a problem with timing as the history navigation will happen the
moment the new page has been rendered. In short that means that you'll
see the new route rendered before the history entry is injected. This
causes some issues:
- Scroll position for back/forward navigation (popstate) is not
preserved correctly
- Safari takes a snapshot of the current page at the point of navigation
that is then used to show when you "swipe to back" on iPhone/iPad/Mac

### How?

This PR changes the approach to `useInsertionEffect` based on the advice
from @sebmarkbage. This runs before the new page contents get committed
so it ensures the history navigation is captured before additional
rendering happens.
parent 437bbf5e
...@@ -83,6 +83,41 @@ function isExternalURL(url: URL) { ...@@ -83,6 +83,41 @@ function isExternalURL(url: URL) {
return url.origin !== window.location.origin return url.origin !== window.location.origin
} }
function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) {
// @ts-ignore TODO-APP: useInsertionEffect is available
React.useInsertionEffect(() => {
// When mpaNavigation flag is set do a hard navigation to the new url.
if (pushRef.mpaNavigation) {
const location = window.location
if (pushRef.pendingPush) {
location.assign(canonicalUrl)
} else {
location.replace(canonicalUrl)
}
return
}
// Identifier is shortened intentionally.
// __NA is used to identify if the history entry can be handled by the app-router.
// __N is used to identify if the history entry can be handled by the old router.
const historyState = {
__NA: true,
tree,
}
if (
pushRef.pendingPush &&
createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl
) {
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef.pendingPush = false
window.history.pushState(historyState, '', canonicalUrl)
} else {
window.history.replaceState(historyState, '', canonicalUrl)
}
sync()
}, [tree, pushRef, canonicalUrl, sync])
return null
}
/** /**
* The global router that wraps the application components. * The global router that wraps the application components.
*/ */
...@@ -274,37 +309,6 @@ function Router({ ...@@ -274,37 +309,6 @@ function Router({
return routerInstance return routerInstance
}, [dispatch]) }, [dispatch])
useEffect(() => {
// When mpaNavigation flag is set do a hard navigation to the new url.
if (pushRef.mpaNavigation) {
const location = window.location
if (pushRef.pendingPush) {
location.assign(canonicalUrl)
} else {
location.replace(canonicalUrl)
}
return
}
// Identifier is shortened intentionally.
// __NA is used to identify if the history entry can be handled by the app-router.
// __N is used to identify if the history entry can be handled by the old router.
const historyState = { __NA: true, tree }
if (
pushRef.pendingPush &&
createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl
) {
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef.pendingPush = false
window.history.pushState(historyState, '', canonicalUrl)
} else {
window.history.replaceState(historyState, '', canonicalUrl)
}
sync()
}, [tree, pushRef, canonicalUrl, sync])
// Add `window.nd` for debugging purposes. // Add `window.nd` for debugging purposes.
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router. // This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
...@@ -371,36 +375,44 @@ function Router({ ...@@ -371,36 +375,44 @@ function Router({
) )
return ( return (
<PathnameContext.Provider value={pathname}> <>
<SearchParamsContext.Provider value={searchParams}> <HistoryUpdater
<GlobalLayoutRouterContext.Provider tree={tree}
value={{ pushRef={pushRef}
changeByServerResponse, canonicalUrl={canonicalUrl}
tree, sync={sync}
focusAndScrollRef, />
nextUrl, <PathnameContext.Provider value={pathname}>
}} <SearchParamsContext.Provider value={searchParams}>
> <GlobalLayoutRouterContext.Provider
<AppRouterContext.Provider value={appRouter}> value={{
<LayoutRouterContext.Provider changeByServerResponse,
value={{ tree,
childNodes: cache.parallelRoutes, focusAndScrollRef,
tree: tree, nextUrl,
// Root node always has `url` }}
// Provided in AppTreeContext to ensure it can be overwritten in layout-router >
url: canonicalUrl, <AppRouterContext.Provider value={appRouter}>
}} <LayoutRouterContext.Provider
> value={{
{HotReloader ? ( childNodes: cache.parallelRoutes,
<HotReloader assetPrefix={assetPrefix}>{content}</HotReloader> tree: tree,
) : ( // Root node always has `url`
content // Provided in AppTreeContext to ensure it can be overwritten in layout-router
)} url: canonicalUrl,
</LayoutRouterContext.Provider> }}
</AppRouterContext.Provider> >
</GlobalLayoutRouterContext.Provider> {HotReloader ? (
</SearchParamsContext.Provider> <HotReloader assetPrefix={assetPrefix}>{content}</HotReloader>
</PathnameContext.Provider> ) : (
content
)}
</LayoutRouterContext.Provider>
</AppRouterContext.Provider>
</GlobalLayoutRouterContext.Provider>
</SearchParamsContext.Provider>
</PathnameContext.Provider>
</>
) )
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment