Unverified Commit 6270c09c authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Refactor: Unify history traversal with other nav types (#87128)

This merges the logic inside updateCacheNodeOnPopstateRestoration into
the function used for all other navigation types.

The main difference between history traversal navigations and other
navigation types is our treatment of dynamic data. History traversal
operations are allowed to reuse dynamic data regardless of its freshness
or staleness. So I've updated the `shouldRefreshDynamicData` argument to
be an enum that accounts for our various freshness policies. As of now,
there are three: Default, HistoryTraversal, and RefreshAll.

This is part of an ongoing series of refactors to unify all navigation
types into a single flow, both to simplify the implementation, and to
ensure the behavior is consistent.
parent c18fb497
......@@ -17,6 +17,7 @@ import {
} from '../../segment-cache/navigation'
import { NavigationResultTag } from '../../segment-cache/types'
import { getStaleTimeMs } from '../../segment-cache/cache'
import { FreshnessPolicy } from '../ppr-navigations'
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 0 seconds (dynamic)
......@@ -161,14 +162,13 @@ export function navigateReducer(
// implementation. Eventually we'll rewrite the router reducer to a
// state machine.
const currentUrl = new URL(state.canonicalUrl, location.origin)
const shouldRefreshDynamicData = false
const result = navigateUsingSegmentCache(
url,
currentUrl,
state.cache,
state.tree,
state.nextUrl,
shouldRefreshDynamicData,
FreshnessPolicy.Default,
shouldScroll,
mutable
)
......
......@@ -8,6 +8,7 @@ import { handleNavigationResult } from './navigate-reducer'
import { navigateToSeededRoute } from '../../segment-cache/navigation'
import { revalidateEntireCache } from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy } from '../ppr-navigations'
export function refreshReducer(
state: ReadonlyReducerState,
......@@ -33,7 +34,6 @@ export function refreshReducer(
const url = currentUrl
const currentFlightRouterState = state.tree
const shouldScroll = true
const shouldRefreshDynamicData = true
const seedFlightRouterState = state.tree
const seedRenderedSearch = state.renderedSearch
......@@ -49,7 +49,7 @@ export function refreshReducer(
seedRenderedSearch,
seedData,
seedHead,
shouldRefreshDynamicData,
FreshnessPolicy.RefreshAll,
nextUrlForRefresh,
shouldScroll
)
......
......@@ -5,15 +5,20 @@ import type {
RestoreAction,
} from '../router-reducer-types'
import { extractPathFromFlightRouterState } from '../compute-changed-path'
import { updateCacheNodeOnPopstateRestoration } from '../ppr-navigations'
import {
FreshnessPolicy,
listenForDynamicRequest,
startPPRNavigation,
type NavigationRequestAccumulation,
} from '../ppr-navigations'
import type { FlightRouterState } from '../../../../shared/lib/app-router-types'
import { handleExternalUrl } from './navigate-reducer'
import type { Mutable } from '../router-reducer-types'
export function restoreReducer(
state: ReadonlyReducerState,
action: RestoreAction
): ReducerState {
const { url, historyState } = action
const href = createHrefFromUrl(url)
// This action is used to restore the router state from the history state.
// However, it's possible that the history state no longer contains the `FlightRouterState`.
// We will copy over the internal state on pushState/replaceState events, but if a history entry
......@@ -22,6 +27,7 @@ export function restoreReducer(
// In this case, we'll continue to use the existing tree so the router doesn't get into an invalid state.
let treeToRestore: FlightRouterState | undefined
let renderedSearch: string | undefined
const historyState = action.historyState
if (historyState) {
treeToRestore = historyState.tree
renderedSearch = historyState.renderedSearch
......@@ -30,18 +36,54 @@ export function restoreReducer(
renderedSearch = state.renderedSearch
}
const oldCache = state.cache
const newCache = process.env.__NEXT_PPR
? // When PPR is enabled, we update the cache to drop the prefetch
// data for any segment whose dynamic data was already received. This
// prevents an unnecessary flash back to PPR state during a
// back/forward navigation.
updateCacheNodeOnPopstateRestoration(oldCache, treeToRestore)
: oldCache
const currentUrl = new URL(state.canonicalUrl, location.origin)
const restoredUrl = action.url
const restoredCanonicalUrl = createHrefFromUrl(restoredUrl)
const restoredNextUrl =
extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname
const now = Date.now()
const accumulation: NavigationRequestAccumulation = {
scrollableSegments: null,
separateRefreshUrls: null,
}
const task = startPPRNavigation(
now,
currentUrl,
state.cache,
state.tree,
treeToRestore,
FreshnessPolicy.HistoryTraversal,
null,
null,
null,
null,
false,
false,
accumulation
)
if (task === null) {
const mutable: Mutable = {
preserveCustomHistoryState: true,
}
return handleExternalUrl(state, mutable, restoredCanonicalUrl, false)
}
if (task.dynamicRequestTree !== null) {
listenForDynamicRequest(
restoredUrl,
restoredNextUrl,
task,
task.dynamicRequestTree,
null,
accumulation
)
}
return {
// Set canonical url
canonicalUrl: href,
canonicalUrl: restoredCanonicalUrl,
renderedSearch,
pushRef: {
pendingPush: false,
......@@ -50,10 +92,14 @@ export function restoreReducer(
preserveCustomHistoryState: true,
},
focusAndScrollRef: state.focusAndScrollRef,
cache: newCache,
cache: task.node,
// Restore provided tree
tree: treeToRestore,
nextUrl: extractPathFromFlightRouterState(treeToRestore) ?? url.pathname,
nextUrl: restoredNextUrl,
// TODO: We need to restore previousNextUrl, too, which represents the
// Next-Url that was used to fetch the data. Anywhere we fetch using the
// canonical URL, there should be a corresponding Next-Url.
previousNextUrl: null,
debugInfo: null,
}
......
......@@ -61,6 +61,7 @@ import {
type ActionRevalidationKind,
} from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy } from '../ppr-navigations'
const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
......@@ -388,8 +389,10 @@ export function serverActionReducer(
// If the action triggered a revalidation of the cache, we should also
// refresh all the dynamic data.
const shouldRefreshDynamicData =
revalidationKind !== ActionDidNotRevalidate
const freshnessPolicy =
revalidationKind === ActionDidNotRevalidate
? FreshnessPolicy.Default
: FreshnessPolicy.RefreshAll
// The server may have sent back new data. If so, we will perform a
// "seeded" navigation that uses the data from the response.
......@@ -421,7 +424,7 @@ export function serverActionReducer(
seedRenderedSearch,
seedData,
seedHead,
shouldRefreshDynamicData,
freshnessPolicy,
nextUrl,
shouldScroll
)
......@@ -443,7 +446,7 @@ export function serverActionReducer(
state.cache,
currentFlightRouterState,
nextUrl,
shouldRefreshDynamicData,
freshnessPolicy,
shouldScroll,
mutable
)
......
......@@ -13,6 +13,7 @@ import { fetchServerResponse } from '../router-reducer/fetch-server-response'
import {
startPPRNavigation,
listenForDynamicRequest,
FreshnessPolicy,
type NavigationTask,
type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations'
......@@ -72,7 +73,7 @@ export function navigate(
currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState,
nextUrl: string | null,
shouldRefreshDynamicData: boolean,
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
accumulation: { collectedDebugInfo?: Array<unknown> }
): NavigationResult {
......@@ -131,7 +132,7 @@ export function navigate(
isPrefetchHeadPartial,
newCanonicalUrl,
renderedSearch,
shouldRefreshDynamicData,
freshnessPolicy,
shouldScroll,
url.hash
)
......@@ -176,7 +177,7 @@ export function navigate(
isPrefetchHeadPartial,
newCanonicalUrl,
newRenderedSearch,
shouldRefreshDynamicData,
freshnessPolicy,
shouldScroll,
url.hash
)
......@@ -198,7 +199,7 @@ export function navigate(
isSamePageNavigation,
currentCacheNode,
currentFlightRouterState,
shouldRefreshDynamicData,
freshnessPolicy,
shouldScroll,
url.hash,
collectedDebugInfo
......@@ -215,7 +216,7 @@ export function navigateToSeededRoute(
seedRenderedSearch: string,
seedData: CacheNodeSeedData | null,
seedHead: HeadData | null,
shouldRefreshDynamicData: boolean,
freshnessPolicy: FreshnessPolicy,
nextUrl: string | null,
shouldScroll: boolean
): SuccessfulNavigationResult | MPANavigationResult {
......@@ -234,7 +235,7 @@ export function navigateToSeededRoute(
currentCacheNode,
currentFlightRouterState,
seedFlightRouterState,
shouldRefreshDynamicData,
freshnessPolicy,
seedData,
seedHead,
null,
......@@ -284,7 +285,7 @@ function navigateUsingPrefetchedRouteTree(
isPrefetchHeadPartial: boolean,
canonicalUrl: string,
renderedSearch: string,
shouldRefreshDynamicData: boolean,
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
hash: string
): SuccessfulNavigationResult | MPANavigationResult {
......@@ -306,7 +307,7 @@ function navigateUsingPrefetchedRouteTree(
currentCacheNode,
currentFlightRouterState,
prefetchFlightRouterState,
shouldRefreshDynamicData,
freshnessPolicy,
seedData,
seedHead,
prefetchSeedData,
......@@ -512,7 +513,7 @@ async function navigateDynamicallyWithNoPrefetch(
isSamePageNavigation: boolean,
currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState,
shouldRefreshDynamicData: boolean,
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
hash: string,
collectedDebugInfo: Array<unknown>
......@@ -529,10 +530,23 @@ async function navigateDynamicallyWithNoPrefetch(
// tree. So it's the same flow as the "happy path" (prefetch, then
// navigation), except we use a single server response for both stages.
let dynamicRequestTree: FlightRouterState
switch (freshnessPolicy) {
case FreshnessPolicy.Default:
case FreshnessPolicy.HistoryTraversal:
dynamicRequestTree = currentFlightRouterState
break
case FreshnessPolicy.RefreshAll:
dynamicRequestTree = DynamicRequestTreeForEntireRoute
break
default:
freshnessPolicy satisfies never
dynamicRequestTree = currentFlightRouterState
break
}
const promiseForDynamicServerResponse = fetchServerResponse(url, {
flightRouterState: shouldRefreshDynamicData
? DynamicRequestTreeForEntireRoute
: currentFlightRouterState,
flightRouterState: dynamicRequestTree,
nextUrl,
})
const result = await promiseForDynamicServerResponse
......@@ -582,7 +596,7 @@ async function navigateDynamicallyWithNoPrefetch(
currentCacheNode,
currentFlightRouterState,
prefetchFlightRouterState,
shouldRefreshDynamicData,
freshnessPolicy,
seedData,
seedHead,
prefetchData,
......
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