Unverified Commit 9937a54a authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Use RouteTree<T> for CacheNode tree (#98971)

Refactors the CacheNode tree to use the RouteTree<T> data type.
CacheNode used to be a tree-shaped object, with a similar structure to
RouteTree<T>. CacheNode is now a data container instead, embedded inside
a RouteTree structure.

So the usage sites change from CacheNode to RouteTree<CacheNode>.

As a result, we can now diff against the render tree directly during
prefetches and navigations, instead of diffing against
FlightRouterState. This gets us closer to migrating everything away from
FlightRouterState to our shared data types.
parent 03383c3d
import type { RouteTree } from './segment-cache/cache'
import type { import type {
FlightRouterState, FlightRouterState,
ScrollRef, ScrollRef,
...@@ -60,7 +61,7 @@ export function navigate( ...@@ -60,7 +61,7 @@ export function navigate(
url: URL, url: URL,
currentUrl: URL, currentUrl: URL,
currentRenderedSearch: string, currentRenderedSearch: string,
currentCacheNode: CacheNode | null, currentRenderTree: RouteTree<CacheNode>,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null, nextUrl: string | null,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
...@@ -89,7 +90,7 @@ export function navigate( ...@@ -89,7 +90,7 @@ export function navigate(
url, url,
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
currentCacheNode, currentRenderTree,
currentFlightRouterState, currentFlightRouterState,
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
...@@ -105,7 +106,7 @@ export function navigate( ...@@ -105,7 +106,7 @@ export function navigate(
url, url,
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
currentCacheNode, currentRenderTree,
currentFlightRouterState, currentFlightRouterState,
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
...@@ -122,7 +123,7 @@ function navigateImpl( ...@@ -122,7 +123,7 @@ function navigateImpl(
url: URL, url: URL,
currentUrl: URL, currentUrl: URL,
currentRenderedSearch: string, currentRenderedSearch: string,
currentCacheNode: CacheNode | null, currentRenderTree: RouteTree<CacheNode>,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null, nextUrl: string | null,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
...@@ -147,8 +148,7 @@ function navigateImpl( ...@@ -147,8 +148,7 @@ function navigateImpl(
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
nextUrl, nextUrl,
currentCacheNode, currentRenderTree,
currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
scrollBehavior, scrollBehavior,
navigateType, navigateType,
...@@ -185,8 +185,7 @@ function navigateImpl( ...@@ -185,8 +185,7 @@ function navigateImpl(
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
nextUrl, nextUrl,
currentCacheNode, currentRenderTree,
currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
scrollBehavior, scrollBehavior,
navigateType, navigateType,
...@@ -210,7 +209,7 @@ function navigateImpl( ...@@ -210,7 +209,7 @@ function navigateImpl(
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
nextUrl, nextUrl,
currentCacheNode, currentRenderTree,
currentFlightRouterState, currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
scrollBehavior, scrollBehavior,
...@@ -231,8 +230,7 @@ export function navigateToKnownRoute( ...@@ -231,8 +230,7 @@ export function navigateToKnownRoute(
navigationSeed: NavigationSeed, navigationSeed: NavigationSeed,
currentUrl: URL, currentUrl: URL,
currentRenderedSearch: string, currentRenderedSearch: string,
currentCacheNode: CacheNode | null, currentRenderTree: RouteTree<CacheNode>,
currentFlightRouterState: FlightRouterState,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
nextUrl: string | null, nextUrl: string | null,
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
...@@ -345,8 +343,7 @@ export function navigateToKnownRoute( ...@@ -345,8 +343,7 @@ export function navigateToKnownRoute(
now, now,
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
currentCacheNode, currentRenderTree,
currentFlightRouterState,
navigationSeed.routeTree, navigationSeed.routeTree,
navigationSeed.metadataVaryPath, navigationSeed.metadataVaryPath,
freshnessPolicy, freshnessPolicy,
...@@ -397,8 +394,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -397,8 +394,7 @@ function navigateUsingPrefetchedRouteTree(
currentUrl: URL, currentUrl: URL,
currentRenderedSearch: string, currentRenderedSearch: string,
nextUrl: string | null, nextUrl: string | null,
currentCacheNode: CacheNode | null, currentRenderTree: RouteTree<CacheNode>,
currentFlightRouterState: FlightRouterState,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
...@@ -429,8 +425,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -429,8 +425,7 @@ function navigateUsingPrefetchedRouteTree(
prefetchSeed, prefetchSeed,
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
currentCacheNode, currentRenderTree,
currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
nextUrl, nextUrl,
scrollBehavior, scrollBehavior,
...@@ -463,7 +458,7 @@ async function navigateToUnknownRoute( ...@@ -463,7 +458,7 @@ async function navigateToUnknownRoute(
currentUrl: URL, currentUrl: URL,
currentRenderedSearch: string, currentRenderedSearch: string,
nextUrl: string | null, nextUrl: string | null,
currentCacheNode: CacheNode | null, currentRenderTree: RouteTree<CacheNode>,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
...@@ -479,7 +474,7 @@ async function navigateToUnknownRoute( ...@@ -479,7 +474,7 @@ async function navigateToUnknownRoute(
// //
// To avoid duplication of logic, we're going to pretend that the tree // To avoid duplication of logic, we're going to pretend that the tree
// returned by the dynamic request is, in fact, a prefetch tree. Then we can // returned by the dynamic request is, in fact, a prefetch tree. Then we can
// use the same server response to write the actual data into the CacheNode // use the same server response to write the actual data into the render
// tree. So it's the same flow as the "happy path" (prefetch, then // tree. So it's the same flow as the "happy path" (prefetch, then
// navigation), except we use a single server response for both stages. // navigation), except we use a single server response for both stages.
...@@ -618,8 +613,7 @@ async function navigateToUnknownRoute( ...@@ -618,8 +613,7 @@ async function navigateToUnknownRoute(
navigationSeed, navigationSeed,
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
currentCacheNode, currentRenderTree,
currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
nextUrl, nextUrl,
scrollBehavior, scrollBehavior,
...@@ -677,7 +671,7 @@ export function completeSoftNavigation( ...@@ -677,7 +671,7 @@ export function completeSoftNavigation(
url: URL, url: URL,
referringNextUrl: string | null, referringNextUrl: string | null,
tree: FlightRouterState, tree: FlightRouterState,
cache: CacheNode, cache: RouteTree<CacheNode>,
renderedSearch: string, renderedSearch: string,
canonicalUrl: string, canonicalUrl: string,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
...@@ -737,7 +731,7 @@ export function completeSoftNavigation( ...@@ -737,7 +731,7 @@ export function completeSoftNavigation(
// //
// If this navigation created new scroll targets (scrollRef !== null), // If this navigation created new scroll targets (scrollRef !== null),
// neutralize them. If it didn't, any prior scroll targets carried // neutralize them. If it didn't, any prior scroll targets carried
// forward on the cache nodes via reuseSharedCacheNode remain active. // forward on reused cache nodes remain active.
if (scrollRef !== null) { if (scrollRef !== null) {
scrollRef.current = false scrollRef.current = false
} }
...@@ -814,7 +808,7 @@ export function completeTraverseNavigation( ...@@ -814,7 +808,7 @@ export function completeTraverseNavigation(
state: AppRouterState, state: AppRouterState,
url: URL, url: URL,
renderedSearch: string, renderedSearch: string,
cache: CacheNode, cache: RouteTree<CacheNode>,
tree: FlightRouterState, tree: FlightRouterState,
nextUrl: string | null nextUrl: string | null
) { ) {
...@@ -854,7 +848,7 @@ async function ensurePrefetchThenNavigate( ...@@ -854,7 +848,7 @@ async function ensurePrefetchThenNavigate(
url: URL, url: URL,
currentUrl: URL, currentUrl: URL,
currentRenderedSearch: string, currentRenderedSearch: string,
currentCacheNode: CacheNode | null, currentRenderTree: RouteTree<CacheNode>,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null, nextUrl: string | null,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
...@@ -877,7 +871,7 @@ async function ensurePrefetchThenNavigate( ...@@ -877,7 +871,7 @@ async function ensurePrefetchThenNavigate(
const navigationLockPrefetch = beginNavigationLockPrefetch() const navigationLockPrefetch = beginNavigationLockPrefetch()
const prefetchTask = schedulePrefetchTask( const prefetchTask = schedulePrefetchTask(
cacheKey, cacheKey,
currentFlightRouterState, currentRenderTree,
fetchStrategy, fetchStrategy,
PrefetchPriority.Default, PrefetchPriority.Default,
null, // onInvalidate null, // onInvalidate
...@@ -897,7 +891,7 @@ async function ensurePrefetchThenNavigate( ...@@ -897,7 +891,7 @@ async function ensurePrefetchThenNavigate(
url, url,
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
currentCacheNode, currentRenderTree,
currentFlightRouterState, currentFlightRouterState,
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
......
import type { RouteTree } from './segment-cache/cache'
import React, { import React, {
useEffect, useEffect,
useMemo, useMemo,
...@@ -159,8 +160,8 @@ function HistoryUpdater({ ...@@ -159,8 +160,8 @@ function HistoryUpdater({
// task. Re-prefetch all visible links with the updated values. In most // task. Re-prefetch all visible links with the updated values. In most
// cases, this will not result in any new network requests, only if // cases, this will not result in any new network requests, only if
// the prefetch result actually varies on one of these inputs. // the prefetch result actually varies on one of these inputs.
pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree) pingVisibleLinks(appRouterState.nextUrl, appRouterState.cache)
}, [appRouterState.nextUrl, appRouterState.tree]) }, [appRouterState.nextUrl, appRouterState.cache])
return null return null
} }
...@@ -182,16 +183,16 @@ function copyNextJsInternalHistoryState(data: any) { ...@@ -182,16 +183,16 @@ function copyNextJsInternalHistoryState(data: any) {
} }
function Head({ function Head({
headCacheNode, headRenderTree,
}: { }: {
headCacheNode: CacheNode | null headRenderTree: RouteTree<CacheNode> | null
}): React.ReactNode { }): React.ReactNode {
// If this segment has a `prefetchHead`, it's the statically prefetched data. // If this segment has a `prefetchHead`, it's the statically prefetched data.
// We should use that on initial render instead of `head`. Then we'll switch // We should use that on initial render instead of `head`. Then we'll switch
// to `head` when the dynamic response streams in. // to `head` when the dynamic response streams in.
const head = headCacheNode !== null ? headCacheNode.head : null const head = headRenderTree !== null ? headRenderTree.data.head : null
const prefetchHead = const prefetchHead =
headCacheNode !== null ? headCacheNode.prefetchHead : null headRenderTree !== null ? headRenderTree.data.prefetchHead : null
// If no prefetch data is available, then we go straight to rendering `head`. // If no prefetch data is available, then we go straight to rendering `head`.
const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head
...@@ -466,7 +467,7 @@ function Router({ ...@@ -466,7 +467,7 @@ function Router({
const layoutRouterContext = useMemo(() => { const layoutRouterContext = useMemo(() => {
return { return {
parentTree: tree, parentTree: tree,
parentCacheNode: cache, parentRenderTree: cache,
parentSegmentPath: null, parentSegmentPath: null,
parentParams: {}, parentParams: {},
parentLoadingData: null, parentLoadingData: null,
...@@ -498,9 +499,9 @@ function Router({ ...@@ -498,9 +499,9 @@ function Router({
// //
// The `key` is used to remount the component whenever the head moves to // The `key` is used to remount the component whenever the head moves to
// a different segment. // a different segment.
const [headCacheNode, headKey] = matchingHead const [headRenderTree, headKey] = matchingHead
head = <Head key={headKey} headCacheNode={headCacheNode} /> head = <Head key={headKey} headRenderTree={headRenderTree} />
} else { } else {
head = null head = null
} }
...@@ -511,7 +512,7 @@ function Router({ ...@@ -511,7 +512,7 @@ function Router({
{/* RootLayoutBoundary enables detection of Suspense boundaries around the root layout. {/* RootLayoutBoundary enables detection of Suspense boundaries around the root layout.
When users wrap their layout in <Suspense>, this creates the component stack pattern When users wrap their layout in <Suspense>, this creates the component stack pattern
"Suspense -> RootLayoutBoundary" which dynamic-rendering.ts uses to allow dynamic rendering. */} "Suspense -> RootLayoutBoundary" which dynamic-rendering.ts uses to allow dynamic rendering. */}
<RootLayoutBoundary>{cache.rsc}</RootLayoutBoundary> <RootLayoutBoundary>{cache.data.rsc}</RootLayoutBoundary>
<AppRouterAnnouncer tree={tree} /> <AppRouterAnnouncer tree={tree} />
</RedirectBoundary> </RedirectBoundary>
) )
......
import type { RouteTree } from './segment-cache/cache'
import type { import type {
CacheNode, CacheNode,
FlightRouterState, FlightRouterState,
...@@ -9,7 +10,7 @@ const MAX_BF_CACHE_ENTRIES = process.env.__NEXT_CACHE_COMPONENTS ? 3 : 1 ...@@ -9,7 +10,7 @@ const MAX_BF_CACHE_ENTRIES = process.env.__NEXT_CACHE_COMPONENTS ? 3 : 1
export type RouterBFCacheEntry = { export type RouterBFCacheEntry = {
tree: FlightRouterState tree: FlightRouterState
cacheNode: CacheNode renderTree: RouteTree<CacheNode>
stateKey: string stateKey: string
// The entries form a linked list, sorted in order of most recently active. // The entries form a linked list, sorted in order of most recently active.
next: RouterBFCacheEntry | null next: RouterBFCacheEntry | null
...@@ -30,14 +31,13 @@ export type RouterBFCacheEntry = { ...@@ -30,14 +31,13 @@ export type RouterBFCacheEntry = {
* unmounted, then the React tree would be, too. So, we use React state to * unmounted, then the React tree would be, too. So, we use React state to
* manage it. * manage it.
* *
* Note that we don't store the RSC data for the cache entries in this hook — * Each entry retains its render tree, including its RSC data. This hook
* the data for inactive segments is stored in the parent CacheNode, which * determines which trees should have their React and DOM state preserved
* *does* have a longer lifetime than the React tree. This hook only determines * by <Activity>.
* which of those trees should have their *state* preserved, by <Activity>.
*/ */
export function useRouterBFCache( export function useRouterBFCache(
activeTree: FlightRouterState, activeTree: FlightRouterState,
activeCacheNode: CacheNode, activeRenderTree: RouteTree<CacheNode>,
activeStateKey: string activeStateKey: string
): RouterBFCacheEntry { ): RouterBFCacheEntry {
// The currently active entry. The entries form a linked list, sorted in // The currently active entry. The entries form a linked list, sorted in
...@@ -53,7 +53,7 @@ export function useRouterBFCache( ...@@ -53,7 +53,7 @@ export function useRouterBFCache(
() => { () => {
const initialEntry: RouterBFCacheEntry = { const initialEntry: RouterBFCacheEntry = {
tree: activeTree, tree: activeTree,
cacheNode: activeCacheNode, renderTree: activeRenderTree,
stateKey: activeStateKey, stateKey: activeStateKey,
next: null, next: null,
} }
...@@ -78,7 +78,7 @@ export function useRouterBFCache( ...@@ -78,7 +78,7 @@ export function useRouterBFCache(
// linked list. // linked list.
const newActiveEntry: RouterBFCacheEntry = { const newActiveEntry: RouterBFCacheEntry = {
tree: activeTree, tree: activeTree,
cacheNode: activeCacheNode, renderTree: activeRenderTree,
stateKey: activeStateKey, stateKey: activeStateKey,
next: null, next: null,
} }
...@@ -105,7 +105,7 @@ export function useRouterBFCache( ...@@ -105,7 +105,7 @@ export function useRouterBFCache(
n++ n++
const entry: RouterBFCacheEntry = { const entry: RouterBFCacheEntry = {
tree: oldEntry.tree, tree: oldEntry.tree,
cacheNode: oldEntry.cacheNode, renderTree: oldEntry.renderTree,
stateKey: oldEntry.stateKey, stateKey: oldEntry.stateKey,
next: null, next: null,
} }
......
'use client' 'use client'
import type { RouteTree } from './segment-cache/cache'
import type { CacheNode } from '../../shared/lib/app-router-types' import type { CacheNode } from '../../shared/lib/app-router-types'
import type { LoadingModuleData } from '../../shared/lib/app-router-types' import type { LoadingModuleData } from '../../shared/lib/app-router-types'
import type { import type {
...@@ -136,7 +138,7 @@ function getHashFragmentDomNode(hashFragment: string) { ...@@ -136,7 +138,7 @@ function getHashFragmentDomNode(hashFragment: string) {
interface ScrollHandlerProps { interface ScrollHandlerProps {
scrollRef: ScrollHandlerRef scrollRef: ScrollHandlerRef
children: React.ReactNode children: React.ReactNode
cacheNode: CacheNode renderTree: RouteTree<CacheNode>
} }
/** /**
...@@ -148,11 +150,11 @@ function InnerScrollHandler(props: ScrollHandlerProps) { ...@@ -148,11 +150,11 @@ function InnerScrollHandler(props: ScrollHandlerProps) {
useLayoutEffect( useLayoutEffect(
() => { () => {
const { scrollRef: scrollHandlerRef, cacheNode } = props const { scrollRef: scrollHandlerRef, renderTree } = props
const scrollRef = scrollHandlerRef.forceScroll const scrollRef = scrollHandlerRef.forceScroll
? scrollHandlerRef.scrollRef ? scrollHandlerRef.scrollRef
: cacheNode.scrollRef : renderTree.data.scrollRef
if (scrollRef === null || !scrollRef.current) return if (scrollRef === null || !scrollRef.current) return
let instance: FragmentInstance | HTMLElement | null = null let instance: FragmentInstance | HTMLElement | null = null
...@@ -277,10 +279,10 @@ function InnerScrollHandler(props: ScrollHandlerProps) { ...@@ -277,10 +279,10 @@ function InnerScrollHandler(props: ScrollHandlerProps) {
function ScrollHandler({ function ScrollHandler({
children, children,
cacheNode, renderTree,
}: { }: {
children: React.ReactNode children: React.ReactNode
cacheNode: CacheNode renderTree: RouteTree<CacheNode>
}) { }) {
const context = useContext(GlobalLayoutRouterContext) const context = useContext(GlobalLayoutRouterContext)
if (!context) { if (!context) {
...@@ -288,7 +290,7 @@ function ScrollHandler({ ...@@ -288,7 +290,7 @@ function ScrollHandler({
} }
return ( return (
<InnerScrollHandler scrollRef={context.scrollRef} cacheNode={cacheNode}> <InnerScrollHandler scrollRef={context.scrollRef} renderTree={renderTree}>
{children} {children}
</InnerScrollHandler> </InnerScrollHandler>
) )
...@@ -301,7 +303,7 @@ function InnerLayoutRouter({ ...@@ -301,7 +303,7 @@ function InnerLayoutRouter({
tree, tree,
segmentPath, segmentPath,
debugNameContext, debugNameContext,
cacheNode: maybeCacheNode, renderTree,
params, params,
url, url,
isActive, isActive,
...@@ -309,7 +311,7 @@ function InnerLayoutRouter({ ...@@ -309,7 +311,7 @@ function InnerLayoutRouter({
tree: FlightRouterState tree: FlightRouterState
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
debugNameContext: string debugNameContext: string
cacheNode: CacheNode | null renderTree: RouteTree<CacheNode>
params: Params params: Params
url: string url: string
isActive: boolean isActive: boolean
...@@ -321,19 +323,6 @@ function InnerLayoutRouter({ ...@@ -321,19 +323,6 @@ function InnerLayoutRouter({
throw new Error('invariant global layout router not mounted') throw new Error('invariant global layout router not mounted')
} }
const cacheNode =
maybeCacheNode !== null
? maybeCacheNode
: // This segment is not in the cache. Suspend indefinitely.
//
// This should only be reachable for inactive/hidden segments, during
// prerendering The active segment should always be consistent with the
// CacheNode tree. Regardless, if we don't have a matching CacheNode, we
// must suspend rather than render nothing, to prevent showing an
// inconsistent route.
(use(unresolvedThenable) as never)
// `rsc` represents the renderable node for this segment. // `rsc` represents the renderable node for this segment.
// If this segment has a `prefetchRsc`, it's the statically prefetched data. // If this segment has a `prefetchRsc`, it's the statically prefetched data.
...@@ -342,12 +331,14 @@ function InnerLayoutRouter({ ...@@ -342,12 +331,14 @@ function InnerLayoutRouter({
// //
// If no prefetch data is available, then we go straight to rendering `rsc`. // If no prefetch data is available, then we go straight to rendering `rsc`.
const resolvedPrefetchRsc = const resolvedPrefetchRsc =
cacheNode.prefetchRsc !== null ? cacheNode.prefetchRsc : cacheNode.rsc renderTree.data.prefetchRsc !== null
? renderTree.data.prefetchRsc
: renderTree.data.rsc
// We use `useDeferredValue` to handle switching between the prefetched and // We use `useDeferredValue` to handle switching between the prefetched and
// final values. The second argument is returned on initial render, then it // final values. The second argument is returned on initial render, then it
// re-renders with the first argument. // re-renders with the first argument.
const rsc: any = useDeferredValue(cacheNode.rsc, resolvedPrefetchRsc) const rsc: any = useDeferredValue(renderTree.data.rsc, resolvedPrefetchRsc)
// `rsc` is either a React node or a promise for a React node, except we // `rsc` is either a React node or a promise for a React node, except we
// special case `null` to represent that this segment's data is missing. If // special case `null` to represent that this segment's data is missing. If
...@@ -401,7 +392,7 @@ function InnerLayoutRouter({ ...@@ -401,7 +392,7 @@ function InnerLayoutRouter({
<LayoutRouterContext.Provider <LayoutRouterContext.Provider
value={{ value={{
parentTree: tree, parentTree: tree,
parentCacheNode: cacheNode, parentRenderTree: renderTree,
parentSegmentPath: segmentPath, parentSegmentPath: segmentPath,
parentParams: params, parentParams: params,
// This is always set to null as we enter a child segment. It's // This is always set to null as we enter a child segment. It's
...@@ -434,7 +425,7 @@ export function LoadingBoundaryProvider({ ...@@ -434,7 +425,7 @@ export function LoadingBoundaryProvider({
// loading.tsx creates a Suspense boundary around each of a layout's child // loading.tsx creates a Suspense boundary around each of a layout's child
// slots. (Might be bit confusing to think about the data flow, but: if // slots. (Might be bit confusing to think about the data flow, but: if
// loading.tsx and layout.tsx are in the same directory, they are assigned // loading.tsx and layout.tsx are in the same directory, they are assigned
// to the same CacheNode.) // to the same render tree.)
// //
// This provider component does not render the Suspense boundary directly; // This provider component does not render the Suspense boundary directly;
// that's handled by LoadingBoundary. // that's handled by LoadingBoundary.
...@@ -453,7 +444,7 @@ export function LoadingBoundaryProvider({ ...@@ -453,7 +444,7 @@ export function LoadingBoundaryProvider({
<LayoutRouterContext.Provider <LayoutRouterContext.Provider
value={{ value={{
parentTree: parentContext.parentTree, parentTree: parentContext.parentTree,
parentCacheNode: parentContext.parentCacheNode, parentRenderTree: parentContext.parentRenderTree,
parentSegmentPath: parentContext.parentSegmentPath, parentSegmentPath: parentContext.parentSegmentPath,
parentParams: parentContext.parentParams, parentParams: parentContext.parentParams,
parentLoadingData: loading, parentLoadingData: loading,
...@@ -544,7 +535,7 @@ export default function OuterLayoutRouter({ ...@@ -544,7 +535,7 @@ export default function OuterLayoutRouter({
const { const {
parentTree, parentTree,
parentCacheNode, parentRenderTree,
parentSegmentPath, parentSegmentPath,
parentParams, parentParams,
parentLoadingData, parentLoadingData,
...@@ -553,7 +544,7 @@ export default function OuterLayoutRouter({ ...@@ -553,7 +544,7 @@ export default function OuterLayoutRouter({
debugNameContext, debugNameContext,
} = context } = context
// Get the CacheNode for this segment by reading it from the parent segment's // Get the render tree for this segment by reading it from the parent segment's
// child map. // child map.
const parentTreeSegment = parentTree[0] const parentTreeSegment = parentTree[0]
const segmentPath = const segmentPath =
...@@ -577,8 +568,8 @@ export default function OuterLayoutRouter({ ...@@ -577,8 +568,8 @@ export default function OuterLayoutRouter({
// (This only applies to page segments; layout segments cannot access search // (This only applies to page segments; layout segments cannot access search
// params on the server.) // params on the server.)
const activeTree = parentTree[1][parallelRouterKey] const activeTree = parentTree[1][parallelRouterKey]
const maybeParentSlots = parentCacheNode.slots const activeRenderTree = parentRenderTree.slots?.get(parallelRouterKey)
if (activeTree === undefined || maybeParentSlots === null) { if (activeTree === undefined || activeRenderTree === undefined) {
// Could not find a matching segment. The client tree is inconsistent with // Could not find a matching segment. The client tree is inconsistent with
// the server tree. Suspend indefinitely; the router will have already // the server tree. Suspend indefinitely; the router will have already
// detected the inconsistency when handling the server response, and // detected the inconsistency when handling the server response, and
...@@ -592,7 +583,6 @@ export default function OuterLayoutRouter({ ...@@ -592,7 +583,6 @@ export default function OuterLayoutRouter({
} }
const activeSegment = activeTree[0] const activeSegment = activeTree[0]
const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null
const activeStateKey = createSegmentKey(activeSegment, true) // no search params const activeStateKey = createSegmentKey(activeSegment, true) // no search params
// At each level of the route tree, not only do we render the currently // At each level of the route tree, not only do we render the currently
...@@ -603,13 +593,13 @@ export default function OuterLayoutRouter({ ...@@ -603,13 +593,13 @@ export default function OuterLayoutRouter({
// bfcacheEntry is a linked list of FlightRouterStates. // bfcacheEntry is a linked list of FlightRouterStates.
let bfcacheEntry: RouterBFCacheEntry | null = useRouterBFCache( let bfcacheEntry: RouterBFCacheEntry | null = useRouterBFCache(
activeTree, activeTree,
activeCacheNode, activeRenderTree!,
activeStateKey activeStateKey
) )
let children: Array<React.ReactNode> = [] let children: Array<React.ReactNode> = []
do { do {
const tree = bfcacheEntry.tree const tree = bfcacheEntry.tree
const cacheNode = bfcacheEntry.cacheNode const renderTree = bfcacheEntry.renderTree
const stateKey = bfcacheEntry.stateKey const stateKey = bfcacheEntry.stateKey
const segment = tree[0] const segment = tree[0]
/* /*
...@@ -676,7 +666,7 @@ export default function OuterLayoutRouter({ ...@@ -676,7 +666,7 @@ export default function OuterLayoutRouter({
const debugNameToDisplay = isVirtual ? undefined : debugNameContext const debugNameToDisplay = isVirtual ? undefined : debugNameContext
let templateValue = ( let templateValue = (
<ScrollHandler cacheNode={cacheNode}> <ScrollHandler renderTree={renderTree}>
<ErrorBoundary <ErrorBoundary
errorComponent={error} errorComponent={error}
errorStyles={errorStyles} errorStyles={errorStyles}
...@@ -706,7 +696,7 @@ export default function OuterLayoutRouter({ ...@@ -706,7 +696,7 @@ export default function OuterLayoutRouter({
url={url} url={url}
tree={tree} tree={tree}
params={params} params={params}
cacheNode={cacheNode} renderTree={renderTree}
segmentPath={segmentPath} segmentPath={segmentPath}
debugNameContext={childDebugNameContext} debugNameContext={childDebugNameContext}
isActive={isActive && stateKey === activeStateKey} isActive={isActive && stateKey === activeStateKey}
......
import type { FlightRouterState } from '../../shared/lib/app-router-types' import type { RouteTree } from './segment-cache/cache'
import type { CacheNode } from '../../shared/lib/app-router-types'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime' import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { import {
FetchStrategy, FetchStrategy,
...@@ -338,14 +339,13 @@ function rescheduleLinkPrefetch( ...@@ -338,14 +339,13 @@ function rescheduleLinkPrefetch(
const appRouterState = getCurrentAppRouterState() const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) { if (appRouterState !== null) {
const treeAtTimeOfPrefetch = appRouterState.tree
if (existingPrefetchTask === null) { if (existingPrefetchTask === null) {
// Initiate a prefetch task. // Initiate a prefetch task.
const nextUrl = appRouterState.nextUrl const nextUrl = appRouterState.nextUrl
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl) const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask( instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey, cacheKey,
treeAtTimeOfPrefetch, appRouterState.cache,
instance.fetchStrategy, instance.fetchStrategy,
priority, priority,
null, null,
...@@ -356,7 +356,7 @@ function rescheduleLinkPrefetch( ...@@ -356,7 +356,7 @@ function rescheduleLinkPrefetch(
// effectively the same as canceling the old task and creating a new one. // effectively the same as canceling the old task and creating a new one.
reschedulePrefetchTask( reschedulePrefetchTask(
existingPrefetchTask, existingPrefetchTask,
treeAtTimeOfPrefetch, appRouterState.cache,
instance.fetchStrategy, instance.fetchStrategy,
priority priority
) )
...@@ -367,18 +367,18 @@ function rescheduleLinkPrefetch( ...@@ -367,18 +367,18 @@ function rescheduleLinkPrefetch(
export function pingVisibleLinks( export function pingVisibleLinks(
nextUrl: string | null, nextUrl: string | null,
tree: FlightRouterState cache: RouteTree<CacheNode>
) { ) {
// For each currently visible link, cancel the existing prefetch task (if it // For each currently visible link, cancel the existing prefetch task (if it
// exists) and schedule a new one. This is effectively the same as if all the // exists) and schedule a new one. This is effectively the same as if all the
// visible links left and then re-entered the viewport. // visible links left and then re-entered the viewport.
// //
// This is called when the Next-Url or the base tree changes, since those // This is called when the Next-Url or the active cache tree changes, since those
// may affect the result of a prefetch task. It's also called after a // may affect the result of a prefetch task. It's also called after a
// cache invalidation. // cache invalidation.
for (const instance of prefetchableAndVisible) { for (const instance of prefetchableAndVisible) {
const task = instance.prefetchTask const task = instance.prefetchTask
if (task !== null && !isPrefetchTaskDirty(task, nextUrl, tree)) { if (task !== null && !isPrefetchTaskDirty(task, nextUrl, cache)) {
// The cache has not been invalidated, and none of the inputs have // The cache has not been invalidated, and none of the inputs have
// changed. Bail out. // changed. Bail out.
continue continue
...@@ -391,7 +391,7 @@ export function pingVisibleLinks( ...@@ -391,7 +391,7 @@ export function pingVisibleLinks(
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl) const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask( instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey, cacheKey,
tree, cache,
instance.fetchStrategy, instance.fetchStrategy,
PrefetchPriority.Default, PrefetchPriority.Default,
null, null,
......
...@@ -177,7 +177,7 @@ export function useRouter(): AppRouterInstance { ...@@ -177,7 +177,7 @@ export function useRouter(): AppRouterInstance {
// a `b` prefix, so the id can be safely concatenated with other keys // a `b` prefix, so the id can be safely concatenated with other keys
// without collision. // without collision.
const layout = useContext(LayoutRouterContext) const layout = useContext(LayoutRouterContext)
const bfcacheIdNumber = layout?.parentCacheNode.bfcacheId ?? 0 const bfcacheIdNumber = layout?.parentRenderTree.data.bfcacheId ?? 0
return useMemo<AppRouterInstance>( return useMemo<AppRouterInstance>(
() => ({ () => ({
back: router.back, back: router.back,
......
import type { FlightRouterState } from '../../shared/lib/app-router-types' import type { RouteTree } from './segment-cache/cache'
import type { CacheNode } from '../../shared/lib/app-router-types'
import type { PrefetchOptions } from '../../shared/lib/app-router-context.shared-runtime' import type { PrefetchOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { PrefetchKind } from './router-reducer/router-reducer-types' import { PrefetchKind } from './router-reducer/router-reducer-types'
import { createPrefetchURL } from './app-router-utils' import { createPrefetchURL } from './app-router-utils'
...@@ -61,7 +62,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void { ...@@ -61,7 +62,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
prefetch( prefetch(
href, href,
state.nextUrl, state.nextUrl,
state.tree, state.cache,
fetchStrategy, fetchStrategy,
options?.onInvalidate ?? null options?.onInvalidate ?? null
) )
...@@ -73,8 +74,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void { ...@@ -73,8 +74,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
* or router.prefetch. It must be validated before we attempt to prefetch it. * or router.prefetch. It must be validated before we attempt to prefetch it.
* @param nextUrl - A special header used by the server for interception routes. * @param nextUrl - A special header used by the server for interception routes.
* Roughly corresponds to the current URL. * Roughly corresponds to the current URL.
* @param treeAtTimeOfPrefetch - The FlightRouterState at the time the prefetch * @param renderTreeAtTimeOfPrefetch - The active data and its vary paths.
* was requested. This is only used when PPR is disabled.
* @param fetchStrategy - Whether to prefetch dynamic data, in addition to * @param fetchStrategy - Whether to prefetch dynamic data, in addition to
* static data. This is used by `<Link prefetch={true}>`. * static data. This is used by `<Link prefetch={true}>`.
* @param onInvalidate - A callback that will be called when the prefetch cache * @param onInvalidate - A callback that will be called when the prefetch cache
...@@ -90,7 +90,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void { ...@@ -90,7 +90,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
export function prefetch( export function prefetch(
href: string, href: string,
nextUrl: string | null, nextUrl: string | null,
treeAtTimeOfPrefetch: FlightRouterState, renderTreeAtTimeOfPrefetch: RouteTree<CacheNode>,
fetchStrategy: PrefetchTaskFetchStrategy, fetchStrategy: PrefetchTaskFetchStrategy,
onInvalidate: null | (() => void) onInvalidate: null | (() => void)
) { ) {
...@@ -102,7 +102,7 @@ export function prefetch( ...@@ -102,7 +102,7 @@ export function prefetch(
const cacheKey = createCacheKey(url.href, nextUrl) const cacheKey = createCacheKey(url.href, nextUrl)
schedulePrefetchTask( schedulePrefetchTask(
cacheKey, cacheKey,
treeAtTimeOfPrefetch, renderTreeAtTimeOfPrefetch,
fetchStrategy, fetchStrategy,
PrefetchPriority.Default, PrefetchPriority.Default,
onInvalidate, onInvalidate,
......
...@@ -5,7 +5,7 @@ import { extractPathFromFlightRouterState } from './compute-changed-path' ...@@ -5,7 +5,7 @@ import { extractPathFromFlightRouterState } from './compute-changed-path'
import type { AppRouterState } from './router-reducer-types' import type { AppRouterState } from './router-reducer-types'
import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport' import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'
import { createInitialCacheNodeForHydration } from '../render-tree' import { createInitialRenderTreeForHydration } from '../render-tree'
import { import {
writeRuntimePrefetchStreamIntoCache, writeRuntimePrefetchStreamIntoCache,
spawnStaticStageCacheWrite, spawnStaticStageCacheWrite,
...@@ -71,7 +71,7 @@ export function createInitialRouterState({ ...@@ -71,7 +71,7 @@ export function createInitialRouterState({
// stores this tree in the route cache, which strips the data on write — // stores this tree in the route cache, which strips the data on write —
// see stripDataFromRouteTree.) // see stripDataFromRouteTree.)
// NOTE: The metadataVaryPath isn't used for anything currently because the // NOTE: The metadataVaryPath isn't used for anything currently because the
// head is embedded into the CacheNode tree, but eventually we'll lift it out // head is embedded into the render tree, but eventually we'll lift it out
// and store it on the top-level state object. // and store it on the top-level state object.
// //
// For statically-generated-at-build-time HTML pages, the tree baked into // For statically-generated-at-build-time HTML pages, the tree baked into
...@@ -104,7 +104,7 @@ export function createInitialRouterState({ ...@@ -104,7 +104,7 @@ export function createInitialRouterState({
acc acc
) )
const metadataVaryPath = acc.metadataVaryPath const metadataVaryPath = acc.metadataVaryPath
const initialTask = createInitialCacheNodeForHydration( const initialTask = createInitialRenderTreeForHydration(
navigatedAt, navigatedAt,
initialRouteTree, initialRouteTree,
initialHead, initialHead,
......
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types' import { PrefetchHint } from '../../../shared/lib/app-router-types'
import type { RouteTree, RSCSegmentData } from '../segment-cache/cache' import type { RouteTree } from '../segment-cache/cache'
export function isNavigatingToNewRootLayout( export function isNavigatingToNewRootLayout<TCurrent, TNext>(
currentTree: FlightRouterState, currentTree: RouteTree<TCurrent>,
nextTree: RouteTree<RSCSegmentData | null> nextTree: RouteTree<TNext>
): boolean { ): boolean {
// Decides whether navigating from currentTree to nextTree crosses into a // Decides whether navigating from currentTree to nextTree crosses into a
// different root layout, which requires a full-page (MPA-style) navigation. // different root layout, which requires a full-page (MPA-style) navigation.
...@@ -16,7 +15,7 @@ export function isNavigatingToNewRootLayout( ...@@ -16,7 +15,7 @@ export function isNavigatingToNewRootLayout(
// dynamic param *values*) for the same depth. So we walk the prefix in // dynamic param *values*) for the same depth. So we walk the prefix in
// lockstep and report a change as soon as the prefixes diverge. // lockstep and report a change as soon as the prefixes diverge.
const currentInPrefix = const currentInPrefix =
((currentTree[4] ?? 0) & PrefetchHint.IsRootLayoutOrAbove) !== 0 (currentTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0
const nextInPrefix = const nextInPrefix =
(nextTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0 (nextTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0
...@@ -38,7 +37,7 @@ export function isNavigatingToNewRootLayout( ...@@ -38,7 +37,7 @@ export function isNavigatingToNewRootLayout(
// (e.g. /[name] for slug1 vs slug2) still resolve to the same /[name]/layout. // (e.g. /[name] for slug1 vs slug2) still resolve to the same /[name]/layout.
// E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js: (group1) changed // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js: (group1) changed
// to (group2) inside the prefix, so the root layout changed. // to (group2) inside the prefix, so the root layout changed.
const currentTreeSegment = currentTree[0] const currentTreeSegment = currentTree.segment
const nextTreeSegment = nextTree.segment const nextTreeSegment = nextTree.segment
if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) { if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {
if ( if (
...@@ -54,10 +53,10 @@ export function isNavigatingToNewRootLayout( ...@@ -54,10 +53,10 @@ export function isNavigatingToNewRootLayout(
// Keep walking the prefix. (Above the root layout there is only a `children` // Keep walking the prefix. (Above the root layout there is only a `children`
// slot, but we traverse all slots defensively.) // slot, but we traverse all slots defensively.)
const slots = nextTree.slots const slots = nextTree.slots
const currentTreeChildren = currentTree[1] const currentTreeChildren = currentTree.slots
if (slots !== null) { if (slots !== null) {
for (const [slot, nextTreeChild] of slots) { for (const [slot, nextTreeChild] of slots) {
const currentTreeChild = currentTreeChildren[slot] const currentTreeChild = currentTreeChildren?.get(slot)
if ( if (
currentTreeChild === undefined || currentTreeChild === undefined ||
isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild) isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild)
......
import type { RouteTree } from '../../segment-cache/cache'
import type { import type {
FlightRouterState, FlightRouterState,
CacheNode, CacheNode,
...@@ -6,20 +7,20 @@ import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment' ...@@ -6,20 +7,20 @@ import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
import { createSegmentKey } from '../create-segment-key' import { createSegmentKey } from '../create-segment-key'
export function findHeadInCache( export function findHeadInCache(
cache: CacheNode, cache: RouteTree<CacheNode>,
parallelRoutes: FlightRouterState[1] parallelRoutes: FlightRouterState[1]
): [CacheNode, string] | null { ): [RouteTree<CacheNode>, string] | null {
return findHeadInCacheImpl(cache, parallelRoutes, '') return findHeadInCacheImpl(cache, parallelRoutes, '')
} }
function findHeadInCacheImpl( function findHeadInCacheImpl(
cache: CacheNode, cache: RouteTree<CacheNode>,
parallelRoutes: FlightRouterState[1], parallelRoutes: FlightRouterState[1],
keyPrefix: string keyPrefix: string
): [CacheNode, string] | null { ): [RouteTree<CacheNode>, string] | null {
const isLastItem = Object.keys(parallelRoutes).length === 0 const isLastItem = Object.keys(parallelRoutes).length === 0
if (isLastItem) { if (isLastItem) {
// Returns the entire Cache Node of the segment whose head we will render. // Returns the render tree of the segment whose head we will render.
return [cache, keyPrefix] return [cache, keyPrefix]
} }
...@@ -44,8 +45,8 @@ function findHeadInCacheImpl( ...@@ -44,8 +45,8 @@ function findHeadInCacheImpl(
continue continue
} }
const childCacheNode = slots[key] const childRenderTree = slots.get(key)
if (!childCacheNode) { if (!childRenderTree) {
continue continue
} }
...@@ -54,7 +55,7 @@ function findHeadInCacheImpl( ...@@ -54,7 +55,7 @@ function findHeadInCacheImpl(
const segmentKey = createSegmentKey(segment) const segmentKey = createSegmentKey(segment)
const item = findHeadInCacheImpl( const item = findHeadInCacheImpl(
childCacheNode, childRenderTree,
childParallelRoutes, childParallelRoutes,
keyPrefix + '/' + segmentKey keyPrefix + '/' + segmentKey
) )
......
...@@ -33,8 +33,8 @@ export function refreshReducer( ...@@ -33,8 +33,8 @@ export function refreshReducer(
process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation
if (!bypassCacheInvalidation) { if (!bypassCacheInvalidation) {
const currentNextUrl = state.nextUrl const currentNextUrl = state.nextUrl
const currentRouterState = state.tree const currentRenderTree = state.cache
invalidateSegmentCacheEntries(currentNextUrl, currentRouterState) invalidateSegmentCacheEntries(currentNextUrl, currentRenderTree)
} }
// A full refresh has no HMR generation to cancel. // A full refresh has no HMR generation to cancel.
return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined) return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)
...@@ -100,7 +100,6 @@ export function refreshDynamicData( ...@@ -100,7 +100,6 @@ export function refreshDynamicData(
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
state.cache, state.cache,
currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
nextUrlForRefresh, nextUrlForRefresh,
scrollBehavior, scrollBehavior,
......
...@@ -70,7 +70,6 @@ export function restoreReducer( ...@@ -70,7 +70,6 @@ export function restoreReducer(
currentUrl, currentUrl,
state.renderedSearch, state.renderedSearch,
state.cache, state.cache,
state.tree,
restoreSeed.routeTree, restoreSeed.routeTree,
restoreSeed.metadataVaryPath, restoreSeed.metadataVaryPath,
FreshnessPolicy.HistoryTraversal, FreshnessPolicy.HistoryTraversal,
......
...@@ -365,7 +365,7 @@ export function serverActionReducer( ...@@ -365,7 +365,7 @@ export function serverActionReducer(
// invalidate both caches until we have a way to detect cookie // invalidate both caches until we have a way to detect cookie
// mutations on the client. // mutations on the client.
if (revalidationKind === ActionDidRevalidateStaticAndDynamic) { if (revalidationKind === ActionDidRevalidateStaticAndDynamic) {
invalidateEntirePrefetchCache(nextUrl, state.tree) invalidateEntirePrefetchCache(nextUrl, state.cache)
} }
// Start a cooldown before re-prefetching to allow CDN cache // Start a cooldown before re-prefetching to allow CDN cache
...@@ -525,7 +525,6 @@ export function serverActionReducer( ...@@ -525,7 +525,6 @@ export function serverActionReducer(
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
state.cache, state.cache,
currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
nextUrl, nextUrl,
scrollBehavior, scrollBehavior,
......
...@@ -60,7 +60,6 @@ export function serverPatchReducer( ...@@ -60,7 +60,6 @@ export function serverPatchReducer(
currentUrl, currentUrl,
currentRenderedSearch, currentRenderedSearch,
state.cache, state.cache,
state.tree,
action.freshnessPolicy, action.freshnessPolicy,
retryNextUrl, retryNextUrl,
scrollBehavior, scrollBehavior,
......
import type { RouteTree } from '../segment-cache/cache'
import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types' import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/decode-server-response' import type { NavigationSeed } from '../segment-cache/decode-server-response'
...@@ -185,7 +186,7 @@ export type ScrollHandlerRef = { ...@@ -185,7 +186,7 @@ export type ScrollHandlerRef = {
* When true, the scroll handler uses the navigation-level `scrollRef` * When true, the scroll handler uses the navigation-level `scrollRef`
* for every segment regardless of per-node state. Used for hash-only * for every segment regardless of per-node state. Used for hash-only
* navigations where every segment should be treated as a scroll * navigations where every segment should be treated as a scroll
* target. When false, the handler checks `cacheNode.scrollRef` * target. When false, the handler checks `renderTree.data.scrollRef`
* instead (per-node), so only segments that actually navigated scroll. * instead (per-node), so only segments that actually navigated scroll.
*/ */
forceScroll: boolean forceScroll: boolean
...@@ -213,7 +214,7 @@ export type AppRouterState = { ...@@ -213,7 +214,7 @@ export type AppRouterState = {
* The cache holds React nodes for every segment that is shown on screen as well as previously shown segments. * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.
* It also holds in-progress data requests. * It also holds in-progress data requests.
*/ */
cache: CacheNode cache: RouteTree<CacheNode>
/** /**
* Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation. * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.
*/ */
......
import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer' import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type { VaryPath } from './vary-path' import type { VaryPath } from './vary-path'
/** /**
...@@ -68,6 +69,24 @@ export function invalidateBfCache(): void { ...@@ -68,6 +69,24 @@ export function invalidateBfCache(): void {
} }
export function writeToBFCache( export function writeToBFCache(
now: number,
varyPath: VaryPath,
cacheNode: CacheNode,
dynamicStaleAt: number
): void {
writeEntryToBFCache(
now,
varyPath,
cacheNode.rsc,
cacheNode.prefetchRsc,
cacheNode.head,
cacheNode.prefetchHead,
dynamicStaleAt,
cacheNode.bfcacheId
)
}
function writeEntryToBFCache(
now: number, now: number,
varyPath: VaryPath, varyPath: VaryPath,
rsc: React.ReactNode, rsc: React.ReactNode,
...@@ -116,21 +135,20 @@ export function writeToBFCache( ...@@ -116,21 +135,20 @@ export function writeToBFCache(
export function writeHeadToBFCache( export function writeHeadToBFCache(
now: number, now: number,
varyPath: VaryPath, varyPath: VaryPath,
head: React.ReactNode, cacheNode: CacheNode,
prefetchHead: React.ReactNode, dynamicStaleAt: number
dynamicStaleAt: number,
bfcacheId: number
): void { ): void {
// Read the special "segment" that represents the head data. // Write the special "segment" that represents the head data. The page
writeToBFCache( // node's head fields take the place of the entry's segment fields.
writeEntryToBFCache(
now, now,
varyPath, varyPath,
head, cacheNode.head,
prefetchHead, cacheNode.prefetchHead,
null, null,
null, null,
dynamicStaleAt, dynamicStaleAt,
bfcacheId cacheNode.bfcacheId
) )
} }
......
import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'
import type React from 'react' import type React from 'react'
import type { Segment as FlightRouterStateSegment } from '../../../shared/lib/app-router-types'
import { import {
PrefetchHint, PrefetchHint,
StaticAttemptHints, StaticAttemptHints,
...@@ -201,9 +201,7 @@ export type RSCSegmentData = { ...@@ -201,9 +201,7 @@ export type RSCSegmentData = {
export type RouteTree<TData> = { export type RouteTree<TData> = {
requestKey: SegmentRequestKey requestKey: SegmentRequestKey
// TODO: Remove the `segment` field, now that it can be reconstructed segment: Segment
// from `param`.
segment: FlightRouterStateSegment
varyPath: VaryPath varyPath: VaryPath
// The vary path used for shell-scoped keying of this segment: the // The vary path used for shell-scoped keying of this segment: the
// segment's vary path with every non-root param replaced with Fallback // segment's vary path with every non-root param replaced with Fallback
...@@ -212,14 +210,6 @@ export type RouteTree<TData> = { ...@@ -212,14 +210,6 @@ export type RouteTree<TData> = {
// don't have to recompute it on every shell request. // don't have to recompute it on every shell request.
shellVaryPath: VaryPath shellVaryPath: VaryPath
refreshState: RefreshState | null refreshState: RefreshState | null
// Render output for this segment, when the tree was created from a server
// response that rendered it. The type parameter encodes a lifecycle
// invariant: trees stored long-term in the route cache
// (RouteCacheEntry.tree / .metadata) are RouteTree<null> — structure only —
// so RSC payloads can never be pinned in memory outside the segment
// cache's eviction control. Trees that carry data must be transient:
// created for a navigation or cache-write, then dropped once the data is
// transferred into CacheNodes / SegmentCacheEntries.
data: TData data: TData
// Keyed by parallel route slot name. Stored as a Map rather than a plain // Keyed by parallel route slot name. Stored as a Map rather than a plain
// object because slot names are app-defined; with a plain object, every // object because slot names are app-defined; with a plain object, every
...@@ -454,7 +444,7 @@ export function getCurrentSegmentCacheVersion(): number { ...@@ -454,7 +444,7 @@ export function getCurrentSegmentCacheVersion(): number {
*/ */
export function invalidateEntirePrefetchCache( export function invalidateEntirePrefetchCache(
nextUrl: string | null, nextUrl: string | null,
tree: FlightRouterState tree: RouteTree<CacheNode>
): void { ): void {
currentRouteCacheVersion++ currentRouteCacheVersion++
currentSegmentCacheVersion++ currentSegmentCacheVersion++
...@@ -472,7 +462,7 @@ export function invalidateEntirePrefetchCache( ...@@ -472,7 +462,7 @@ export function invalidateEntirePrefetchCache(
*/ */
export function invalidateRouteCacheEntries( export function invalidateRouteCacheEntries(
nextUrl: string | null, nextUrl: string | null,
tree: FlightRouterState tree: RouteTree<CacheNode>
): void { ): void {
currentRouteCacheVersion++ currentRouteCacheVersion++
...@@ -489,7 +479,7 @@ export function invalidateRouteCacheEntries( ...@@ -489,7 +479,7 @@ export function invalidateRouteCacheEntries(
*/ */
export function invalidateSegmentCacheEntries( export function invalidateSegmentCacheEntries(
nextUrl: string | null, nextUrl: string | null,
tree: FlightRouterState tree: RouteTree<CacheNode>
): void { ): void {
currentSegmentCacheVersion++ currentSegmentCacheVersion++
...@@ -534,7 +524,7 @@ function notifyInvalidationListener(task: PrefetchTask): void { ...@@ -534,7 +524,7 @@ function notifyInvalidationListener(task: PrefetchTask): void {
export function pingInvalidationListeners( export function pingInvalidationListeners(
nextUrl: string | null, nextUrl: string | null,
tree: FlightRouterState cache: RouteTree<CacheNode>
): void { ): void {
// The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks. // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.
// This is called when the Next-Url or the base tree changes, since those // This is called when the Next-Url or the base tree changes, since those
...@@ -544,7 +534,7 @@ export function pingInvalidationListeners( ...@@ -544,7 +534,7 @@ export function pingInvalidationListeners(
const tasks = invalidationListeners const tasks = invalidationListeners
invalidationListeners = null invalidationListeners = null
for (const task of tasks) { for (const task of tasks) {
if (isPrefetchTaskDirty(task, nextUrl, tree)) { if (isPrefetchTaskDirty(task, nextUrl, cache)) {
notifyInvalidationListener(task) notifyInvalidationListener(task)
} }
} }
...@@ -1639,36 +1629,31 @@ export function convertRootFlightRouterStateToRouteTree( ...@@ -1639,36 +1629,31 @@ export function convertRootFlightRouterStateToRouteTree(
) )
} }
export function convertReusedFlightRouterStateToRouteTree( export function rebaseInactiveRouteTree<TData>(
parentRouteTree: RouteTree<RSCSegmentData | null>, treeToRebase: RouteTree<TData>
parallelRouteKey: string, ): RouteTree<null> {
flightRouterState: FlightRouterState, // A parallel route slot that the target route doesn't provide keeps the
renderedSearch: NormalizedSearch, // slot already active on the current route, under the new parent. The slot
acc: RouteTreeAccumulator // sits at the same route position, so its request keys and vary paths are
) { // unchanged: copy the structure and drop the payloads, which belong to the
// Create a RouteTree for a FlightRouterState that was reused from an older // previous render and are reused separately by render-tree.
// route. This happens during a navigation when a parallel route slot does not let slots: Map<string, RouteTree<null>> | null = null
// match the target route; we reuse whatever slot was already active. if (treeToRebase.slots !== null) {
slots = new Map()
// Unlike a FlightRouterState, the RouteTree type contains backreferences to for (const [parallelRouteKey, child] of treeToRebase.slots) {
// the parent segments. Append the vary path to the parent's vary path. slots.set(parallelRouteKey, rebaseInactiveRouteTree(child))
const parentPartialVaryPath = getPartialVaryPath(parentRouteTree.varyPath) }
const segment = flightRouterState[0] }
// And the request key. return {
const parentRequestKey = parentRouteTree.requestKey requestKey: treeToRebase.requestKey,
const requestKeyPart = createSegmentRequestKeyPart(segment) segment: treeToRebase.segment,
const requestKey = appendSegmentRequestKeyPart( varyPath: treeToRebase.varyPath,
parentRequestKey, shellVaryPath: treeToRebase.shellVaryPath,
parallelRouteKey, refreshState: treeToRebase.refreshState,
requestKeyPart data: null,
) slots,
return convertFlightRouterStateToRouteTree( prefetchHints: treeToRebase.prefetchHints,
flightRouterState, }
requestKey,
parentPartialVaryPath,
renderedSearch,
acc
)
} }
export function convertFlightRouterStateToRouteTree( export function convertFlightRouterStateToRouteTree(
...@@ -1744,8 +1729,8 @@ export function convertFlightRouterStateToRouteTree( ...@@ -1744,8 +1729,8 @@ export function convertFlightRouterStateToRouteTree(
return tree return tree
} }
export function convertRouteTreeToFlightRouterState( export function convertRouteTreeToFlightRouterState<TData>(
routeTree: RouteTree<RSCSegmentData | null> routeTree: RouteTree<TData>
): FlightRouterState { ): FlightRouterState {
const parallelRoutes: Record<string, FlightRouterState> = {} const parallelRoutes: Record<string, FlightRouterState> = {}
const slots = routeTree.slots const slots = routeTree.slots
......
...@@ -230,9 +230,8 @@ export function createNavigationSeed( ...@@ -230,9 +230,8 @@ export function createNavigationSeed(
* information (vary paths, the normalized segment value) * information (vary paths, the normalized segment value)
* initialized, and the remaining fields set to their defaults. The caller * initialized, and the remaining fields set to their defaults. The caller
* finishes initializing those in place after recursing into the children. * finishes initializing those in place after recursing into the children.
* Shared by the FlightRouterState converter and the transport decoder so the * Shared by FlightRouterState conversion, transport decoding, and subtree
* two cannot drift, and so every node they produce has the same property * rebasing so their routing identity stays consistent.
* order (one hidden class).
*/ */
export function createRouteTreeNode<TData>( export function createRouteTreeNode<TData>(
originalSegment: FlightRouterStateSegment, originalSegment: FlightRouterStateSegment,
...@@ -323,7 +322,7 @@ export function createRouteTreeNode<TData>( ...@@ -323,7 +322,7 @@ export function createRouteTreeNode<TData>(
* *
* TODO: The base is a FlightRouterState only because that's the * TODO: The base is a FlightRouterState only because that's the
* representation the client router currently renders from (the router * representation the client router currently renders from (the router
* reducer's `state.tree`, which the CacheNode tree and layout-router are * reducer's `state.tree`, which the render tree and layout-router are
* keyed against). Once the rendering path is updated to use RouteTree as its * keyed against). Once the rendering path is updated to use RouteTree as its
* source of truth, the base tree here can be a RouteTree, and the base-only * source of truth, the base tree here can be a RouteTree, and the base-only
* conversion path (convertFlightRouterStateToRouteTree) goes away with it. * conversion path (convertFlightRouterStateToRouteTree) goes away with it.
......
...@@ -4,7 +4,7 @@ import type { ...@@ -4,7 +4,7 @@ import type {
NormalizedSearch, NormalizedSearch,
NormalizedNextUrl, NormalizedNextUrl,
} from './cache-key' } from './cache-key'
import type { RouteTree, RSCSegmentData } from './cache' import type { RouteTree } from './cache'
import { Fallback, type FallbackType } from './cache-map' import { Fallback, type FallbackType } from './cache-map'
import { import {
HEAD_REQUEST_KEY, HEAD_REQUEST_KEY,
...@@ -251,9 +251,9 @@ export function finalizeMetadataVaryPath( ...@@ -251,9 +251,9 @@ export function finalizeMetadataVaryPath(
) )
} }
export function getSegmentVaryPathForRequest( export function getSegmentVaryPathForRequest<TData>(
fetchStrategy: FetchStrategy, fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null> tree: RouteTree<TData>
): VaryPath { ): VaryPath {
// This is used for storing pending requests in the cache. We want to choose // This is used for storing pending requests in the cache. We want to choose
// the most generic vary path based on the strategy used to fetch it, i.e. // the most generic vary path based on the strategy used to fetch it, i.e.
......
'use client' 'use client'
import type { RouteTree } from '../../client/components/segment-cache/cache'
import type { import type {
ScrollHandlerRef, ScrollHandlerRef,
PrefetchKind, PrefetchKind,
...@@ -94,7 +96,7 @@ export const AppRouterContext = React.createContext<AppRouterInstance | null>( ...@@ -94,7 +96,7 @@ export const AppRouterContext = React.createContext<AppRouterInstance | null>(
) )
export const LayoutRouterContext = React.createContext<{ export const LayoutRouterContext = React.createContext<{
parentTree: FlightRouterState parentTree: FlightRouterState
parentCacheNode: CacheNode parentRenderTree: RouteTree<CacheNode>
parentSegmentPath: FlightSegmentPath | null parentSegmentPath: FlightSegmentPath | null
parentParams: Params parentParams: Params
parentLoadingData: LoadingModuleData | null parentLoadingData: LoadingModuleData | null
......
...@@ -18,9 +18,9 @@ import type { FullTransportData, PartialTransportData } from './rsc-transport' ...@@ -18,9 +18,9 @@ import type { FullTransportData, PartialTransportData } from './rsc-transport'
export type HeadData = React.ReactNode export type HeadData = React.ReactNode
/** /**
* Cache node used in app-router / layout-router. * Render state for a segment. Reuse this object while its data is unchanged;
* create a new one when a navigation replaces the segment's data.
*/ */
export type CacheNode = { export type CacheNode = {
/** /**
* When rsc is not null, it represents the RSC data for the * When rsc is not null, it represents the RSC data for the
...@@ -49,8 +49,6 @@ export type CacheNode = { ...@@ -49,8 +49,6 @@ export type CacheNode = {
head: HeadData head: HeadData
slots: Record<string, CacheNode> | null
/** /**
* A shared mutable ref that tracks whether this segment should be scrolled * A shared mutable ref that tracks whether this segment should be scrolled
* to. All new segments created during a single navigation share the same * to. All new segments created during a single navigation share the same
...@@ -371,7 +369,7 @@ export function propagateSubtreeBits( ...@@ -371,7 +369,7 @@ export function propagateSubtreeBits(
/** /**
* A path through the segment tree: a repeating sequence of segment and * A path through the segment tree: a repeating sequence of segment and
* parallel route key. Used by the client to address positions in the * parallel route key. Used by the client to address positions in the
* CacheNode tree (see layout-router). * render tree (see layout-router).
*/ */
export type FlightSegmentPath = export type FlightSegmentPath =
// Uses `any` as repeating pattern can't be typed. // Uses `any` as repeating pattern can't be typed.
......
...@@ -377,14 +377,14 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -377,14 +377,14 @@ describe(`Terminal Logging (${bundlerName})`, () => {
https://react.dev/link/hydration-mismatch https://react.dev/link/hydration-mismatch
... ...
<ScrollHandler cacheNode={{rsc:{...}, ...}}> <ScrollHandler renderTree={{...}}>
<InnerScrollHandler scrollRef={{scrollRef:null, ...}} cacheNode={{rsc:{...}, ...}}> <InnerScrollHandler scrollRef={{scrollRef:null, ...}} renderTree={{...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}> <ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary name="hydration-..." loading={null}> <LoadingBoundary name="hydration-..." loading={null}>
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/hydration..." tree={[...]} params={{}} cacheNode={{rsc:{...}, ...}} ...> <InnerLayoutRouter url="/hydration..." tree={[...]} params={{}} renderTree={{...}} segmentPath={[...]} ...>
<SegmentViewNode type="page" pagePath="hydration-..."> <SegmentViewNode type="page" pagePath="hydration-...">
<SegmentTrieNode> <SegmentTrieNode>
<ClientPageRoot Component={function Page} serverProvidedParams={{...}}> <ClientPageRoot Component={function Page} serverProvidedParams={{...}}>
......
import { connection } from 'next/server'
export default async function Side({
searchParams,
}: {
searchParams: Promise<{ value?: string }>
}) {
await connection()
const { value } = await searchParams
return (
<>
<p id="retained-value">{value}</p>
<p id="retained-render">{crypto.randomUUID()}</p>
</>
)
}
import Link from 'next/link'
import { Suspense } from 'react'
import { RefreshButton } from '../components/RefreshButton'
export default function Layout({
children,
side,
}: {
children: React.ReactNode
side: React.ReactNode
}) {
return (
<>
<Link prefetch={false} href="/retained-search/two?value=second">
Two
</Link>
<Link prefetch={false} href="/retained-search/three?value=third">
Three
</Link>
<RefreshButton />
{children}
<Suspense fallback={null}>{side}</Suspense>
</>
)
}
export default function Page() {
return <p id="active-page">one</p>
}
export default function Page() {
return <p id="active-page">three</p>
}
export default function Page() {
return <p id="active-page">two</p>
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils' import { check, retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
import type * as Playwright from 'playwright'
describe('parallel-routes-revalidation', () => { describe('parallel-routes-revalidation', () => {
const { next, isNextDev, isNextStart, isNextDeploy } = nextTestSetup({ const { next, isNextDev, isNextStart, isNextDeploy } = nextTestSetup({
...@@ -43,6 +45,43 @@ describe('parallel-routes-revalidation', () => { ...@@ -43,6 +45,43 @@ describe('parallel-routes-revalidation', () => {
}) })
} }
it('refreshes a retained slot using its original URL after multiple navigations', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/retained-search/one?value=first', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
const originalRender = await browser.elementById('retained-render').text()
expect(await browser.elementById('retained-value').text()).toBe('first')
for (const [page, value] of [
['two', 'second'],
['three', 'third'],
]) {
await act(async () => {
await browser
.elementByCss(`a[href="/retained-search/${page}?value=${value}"]`)
.click()
})
expect(await browser.elementById('active-page').text()).toBe(page)
expect(await browser.elementById('retained-value').text()).toBe('first')
expect(await browser.elementById('retained-render').text()).toBe(
originalRender
)
}
await act(async () => {
await browser.elementById('refresh-button').click()
})
expect(await browser.elementById('retained-render').text()).not.toBe(
originalRender
)
expect(await browser.elementById('retained-value').text()).toBe('first')
expect(await browser.elementById('active-page').text()).toBe('three')
expect(new URL(await browser.url()).search).toBe('?value=third')
})
it('should handle router.refresh() when called in a slot', async () => { it('should handle router.refresh() when called in a slot', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await check(() => browser.hasElementByCssSelector('#refresh-router'), false) await check(() => browser.hasElementByCssSelector('#refresh-router'), false)
......
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