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