Unverified Commit 643e34a5 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Allow root params in App Shell (client)

The App Shell is the generic loading state for a route. It does not
depend on concrete param values, so it can be used for every navigation
to a route before its params are known.

We've decided to special case root params: those that appear above the
topmost layout for a given route. These are typically used for params
that are low cardinality for a given session, such as the locale. So we
allow them to appear in the generic part of the UI, even though they
technically might change across pages.

We already treat root params as special during static generation, by
always including them during fallback shell generation. So this decision
is consistent with our existing treatment.

This PR updates the client to key App Shells by their root params.
Currently, the client assumes that the shell never varies on _any_
params. This updates the assumption so that it only applies to non-root
params.
parent a64db6f7
......@@ -28,7 +28,7 @@ describe('computeChangedPath', () => {
},
undefined,
undefined,
PrefetchHint.IsRootLayout,
PrefetchHint.IsRootLayoutOrAbove,
],
[
'',
......@@ -53,7 +53,7 @@ describe('computeChangedPath', () => {
},
undefined,
undefined,
PrefetchHint.IsRootLayout,
PrefetchHint.IsRootLayoutOrAbove,
]
)
).toBe('/')
......
......@@ -6,16 +6,41 @@ export function isNavigatingToNewRootLayout(
currentTree: FlightRouterState,
nextTree: RouteTree
): boolean {
// Compare segments
// Decides whether navigating from currentTree to nextTree crosses into a
// different root layout, which requires a full-page (MPA-style) navigation.
//
// The "root layout" is the highest-level layout in the tree. The segments at
// or above it form the "root layout prefix", which the server marks with the
// IsRootLayoutOrAbove hint. Two routes share a root layout iff their root
// layout prefixes are structurally identical — same segments (ignoring
// 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
const nextInPrefix =
(nextTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0
// Both trees have descended past the root layout with everything above
// matching — same root layout.
if (!currentInPrefix && !nextInPrefix) {
return false
}
// One tree's root layout prefix is deeper than the other's, so the root
// layout boundary moved — it must have changed.
// E.g. /[lang]/layout.js -> /[lang]/[region]/layout.js
if (currentInPrefix !== nextInPrefix) {
return true
}
// Both segments are still inside the root layout prefix. They must match.
// Compare dynamic param name and type but ignore the value: different values
// (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 nextTreeSegment = nextTree.segment
// If any segment is different before we find the root layout, the root layout has changed.
// E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js
// First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.
if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {
// Compare dynamic param name and type but ignore the value, different values would not affect the current root layout
// /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js
if (
currentTreeSegment[0] !== nextTreeSegment[0] ||
currentTreeSegment[2] !== nextTreeSegment[2]
......@@ -26,20 +51,8 @@ export function isNavigatingToNewRootLayout(
return true
}
// Current tree root layout found
const currentIsRootLayout =
((currentTree[4] ?? 0) & PrefetchHint.IsRootLayout) !== 0
const nextIsRootLayout =
(nextTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0
if (currentIsRootLayout) {
// If the next tree doesn't have the root layout flag, it must have changed.
return !nextIsRootLayout
}
// Current tree didn't have its root layout here, must have changed.
if (nextIsRootLayout) {
return true
}
// 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]
if (slots !== null) {
......
......@@ -202,7 +202,6 @@ export function startPPRNavigation(
isSamePageNavigation: boolean,
accumulation: NavigationRequestAccumulation
): NavigationTask | null {
const didFindRootLayout = false
const parentNeedsDynamicRequest = false
const parentRefreshState = null
const oldRootRefreshState: RefreshState = {
......@@ -217,7 +216,6 @@ export function startPPRNavigation(
newRouteTree,
newMetadataVaryPath,
freshness,
didFindRootLayout,
seedData,
seedHead,
seedDynamicStaleAt,
......@@ -237,7 +235,6 @@ function updateCacheNodeOnNavigation(
newRouteTree: RouteTree,
newMetadataVaryPath: PageVaryPath | null,
freshness: FreshnessPolicy,
didFindRootLayout: boolean,
seedData: CacheNodeSeedData | null,
seedHead: HeadData | null,
seedDynamicStaleAt: number,
......@@ -275,11 +272,12 @@ function updateCacheNodeOnNavigation(
//
// Refer to isNavigatingToNewRootLayout for details.
//
// Note that we only have to perform this extra traversal if we didn't
// already discover a root layout in the part of the tree that is
// unchanged. We also only need to compare the subtree that is not
// Note that we only have to perform this extra traversal if this changed
// segment is still at or above the root layout (IsRootLayoutOrAbove);
// once we've descended past the root layout, a segment change can't alter
// the root layout. We also only need to compare the subtree that is not
// shared. In the common case, this branch is skipped completely.
(!didFindRootLayout &&
((newRouteTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0 &&
isNavigatingToNewRootLayout(oldRouterState, newRouteTree)) ||
// The global Not Found route (app/global-not-found.tsx) is a special
// case, because it acts like a root layout, but in the router tree, it
......@@ -312,13 +310,6 @@ function updateCacheNodeOnNavigation(
const oldRouterStateChildren = oldRouterState[1]
const seedDataChildren = seedData !== null ? seedData[1] : null
// We're currently traversing the part of the tree that was also part of
// the previous route. If we discover a root layout, then we don't need to
// trigger an MPA navigation.
const childDidFindRootLayout =
didFindRootLayout ||
(newRouteTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0
let shouldRefreshDynamicData: boolean = false
switch (freshness) {
case FreshnessPolicy.Default:
......@@ -517,7 +508,6 @@ function updateCacheNodeOnNavigation(
newRouteTreeChild,
newMetadataVaryPath,
freshness,
childDidFindRootLayout,
seedDataChild ?? null,
seedHeadChild,
seedDynamicStaleAt,
......
......@@ -20,7 +20,7 @@ describe('shouldHardNavigate', () => {
},
undefined,
undefined,
PrefetchHint.IsRootLayout,
PrefetchHint.IsRootLayoutOrAbove,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
......@@ -79,7 +79,7 @@ describe('shouldHardNavigate', () => {
},
null,
null,
PrefetchHint.IsRootLayout,
PrefetchHint.IsRootLayoutOrAbove,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
......@@ -136,7 +136,7 @@ describe('shouldHardNavigate', () => {
},
null,
null,
PrefetchHint.IsRootLayout,
PrefetchHint.IsRootLayoutOrAbove,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
......
......@@ -46,6 +46,7 @@ import {
getFulfilledRouteVaryPath,
getFulfilledSegmentVaryPath,
getSegmentVaryPathForRequest,
getShellSegmentVaryPath,
appendLayoutVaryPath,
finalizeLayoutVaryPath,
finalizePageVaryPath,
......@@ -146,6 +147,11 @@ type RouteTreeShared = {
// TODO: Remove the `segment` field, now that it can be reconstructed
// from `param`.
segment: FlightRouterStateSegment
// The vary path used to key this segment's App Shell entry: the segment's
// vary path with every non-root param replaced with Fallback (see
// getShellSegmentVaryPath). Precomputed once during tree construction so we
// don't have to recompute it on every shell request.
shellVaryPath: SegmentVaryPath
refreshState: RefreshState | null
slots: null | {
[parallelRouteKey: string]: RouteTree
......@@ -753,9 +759,12 @@ function deprecated_createOptimisticRouteTree(
// We only need to clone the vary path if the route is a page.
if (tree.isPage) {
// The shell vary path Fallbacks search params, so it's unaffected by the
// new rendered search and can be reused as-is.
return {
requestKey: tree.requestKey,
segment: tree.segment,
shellVaryPath: tree.shellVaryPath,
refreshState: tree.refreshState,
varyPath: clonePageVaryPathWithNewSearchParams(
tree.varyPath,
......@@ -771,6 +780,7 @@ function deprecated_createOptimisticRouteTree(
return {
requestKey: tree.requestKey,
segment: tree.segment,
shellVaryPath: tree.shellVaryPath,
refreshState: tree.refreshState,
varyPath: tree.varyPath,
isPage: false,
......@@ -1087,6 +1097,7 @@ export function createMetadataRouteTree(
const metadata: RouteTree = {
requestKey: HEAD_REQUEST_KEY,
segment: HEAD_REQUEST_KEY,
shellVaryPath: getShellSegmentVaryPath(metadataVaryPath),
refreshState: null,
varyPath: metadataVaryPath,
// The metadata isn't really a "page" (though it isn't really a "segment"
......@@ -1325,7 +1336,10 @@ function convertTreePrefetchToRouteTree(
childPartialVaryPath = appendLayoutVaryPath(
partialVaryPath,
childParamKey,
childSegmentName
childSegmentName,
// The child's param is a root param iff the child segment is at or
// above the root layout, which the server marks directly.
(childPrefetch.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0
)
childSegment = [
childSegmentName,
......@@ -1397,6 +1411,7 @@ function convertTreePrefetchToRouteTree(
return {
requestKey,
segment,
shellVaryPath: getShellSegmentVaryPath(varyPath),
refreshState: null,
// TODO: Cheating the type system here a bit because TypeScript can't tell
// that the type of isPage and varyPath are consistent. The fix would be to
......@@ -1468,6 +1483,11 @@ function convertFlightRouterStateToRouteTree(
): RouteTree {
const originalSegment = flightRouterState[0]
// This segment's param (if any) is a root param iff the segment is at or
// above the root layout, which the server marks directly.
const isRootParam =
((flightRouterState[4] ?? 0) & PrefetchHint.IsRootLayoutOrAbove) !== 0
// If the FlightRouterState has a refresh state, then this segment is part of
// an inactive parallel route. It has a different rendered search query than
// the outer parent route. In order to construct the inactive route correctly,
......@@ -1494,7 +1514,8 @@ function convertFlightRouterStateToRouteTree(
partialVaryPath = appendLayoutVaryPath(
parentPartialVaryPath,
paramCacheKey,
paramName
paramName,
isRootParam
)
varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)
segment = originalSegment
......@@ -1576,6 +1597,7 @@ function convertFlightRouterStateToRouteTree(
return {
requestKey,
segment,
shellVaryPath: getShellSegmentVaryPath(varyPath),
refreshState,
// TODO: Cheating the type system here a bit because TypeScript can't tell
// that the type of isPage and varyPath are consistent. The fix would be to
......@@ -1607,6 +1629,9 @@ export function convertRouteTreeToFlightRouterState(
null,
null,
]
if (routeTree.prefetchHints !== 0) {
flightRouterState[4] = routeTree.prefetchHints
}
return flightRouterState
}
......@@ -2719,8 +2744,6 @@ function writeSeedDataIntoCache(
}
}
const EMPTY_VARY_PARAMS: Set<string> = new Set()
function fulfillEntrySpawnedByRuntimePrefetch(
now: number,
fetchStrategy:
......@@ -2750,29 +2773,25 @@ function fulfillEntrySpawnedByRuntimePrefetch(
// untrustworthy set could replace concrete params with Fallback and let
// unrelated URLs read each other's content from the cache.
//
// Override to an empty set for RuntimeShell prefetches. The shell is
// param-free by definition — that's the whole point of the strategy — so
// every param node in the vary path should be Fallback regardless of what
// the server reports.
// NOTE: It would be better not to override this value on the client. We
// should be able to trust the server. However, there's one known case where
// the server can over-report search params: the tracking proxy in
// `createVaryingSearchParams` registers `?` on any string property access,
// and `Promise.resolve(proxy)` reads `.then` during thenability detection,
// so just wrapping the proxy in a promise is enough to leak `?` into the
// accumulator. We also don't want to special case "then" access because it's
// perfectly valid to have a search param named "then". The plan to address
// this is to track each search param individually, rather than the entire
// query string as a whole.
//
// When non-null, this is the param set to re-key by; when null, the entry
// stays keyed by the request's concrete vary path.
const fulfilledVaryParams =
process.env.__NEXT_VARY_PARAMS && fetchStrategy !== FetchStrategy.Full
? fetchStrategy === FetchStrategy.RuntimeShell
? EMPTY_VARY_PARAMS
: segmentVaryParams
: null
// For RuntimeShell prefetches, always re-key to the precomputed shell vary
// path. A shell entry is spawned at a concrete param path but is reusable
// across all of them; tree.shellVaryPath (root-param values kept, every other
// param replaced with Fallback) is exactly the path that shell reads look it
// up under.
let fulfilledVaryPath: SegmentVaryPath | null = null
if (process.env.__NEXT_VARY_PARAMS) {
if (fetchStrategy === FetchStrategy.RuntimeShell) {
fulfilledVaryPath = tree.shellVaryPath
} else if (
fetchStrategy !== FetchStrategy.Full &&
segmentVaryParams !== null
) {
fulfilledVaryPath = getFulfilledSegmentVaryPath(
tree.varyPath,
segmentVaryParams
)
}
}
// We should only write into cache entries that are owned by us. Or create
// a new one and write into that. We must never write over an entry that was
......@@ -2788,11 +2807,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
staleAt,
isPartial
)
if (fulfilledVaryParams !== null) {
const fulfilledVaryPath = getFulfilledSegmentVaryPath(
tree.varyPath,
fulfilledVaryParams
)
if (fulfilledVaryPath !== null) {
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
......@@ -2817,11 +2832,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
staleAt,
isPartial
)
if (fulfilledVaryParams !== null) {
const fulfilledVaryPath = getFulfilledSegmentVaryPath(
tree.varyPath,
fulfilledVaryParams
)
if (fulfilledVaryPath !== null) {
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
......@@ -2843,8 +2854,8 @@ function fulfillEntrySpawnedByRuntimePrefetch(
isPartial
)
const varyPath =
fulfilledVaryParams !== null
? getFulfilledSegmentVaryPath(tree.varyPath, fulfilledVaryParams)
fulfilledVaryPath !== null
? fulfilledVaryPath
: getSegmentVaryPathForRequest(fetchStrategy, tree)
upsertSegmentEntry(now, varyPath, newEntry)
}
......
......@@ -44,6 +44,7 @@
*/
import type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
import type { RouteTree, FulfilledRouteCacheEntry } from './cache'
import {
EntryStatus,
......@@ -61,6 +62,7 @@ import {
finalizeLayoutVaryPath,
finalizePageVaryPath,
finalizeMetadataVaryPath,
getShellSegmentVaryPath,
type PartialSegmentVaryPath,
type PageVaryPath,
} from './vary-path'
......@@ -883,6 +885,11 @@ function reifyRouteTree(
): RouteTree {
const originalSegment = pattern.segment
// This segment's param (if any) is a root param iff the segment is at or
// above the root layout, which the server marks directly.
const isRootParam =
(pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0
let newSegment = originalSegment
let partialVaryPath: PartialSegmentVaryPath | null
......@@ -900,7 +907,8 @@ function reifyRouteTree(
partialVaryPath = appendLayoutVaryPath(
parentPartialVaryPath,
newCacheKey,
paramName
paramName,
isRootParam
)
} else {
// Param not found in resolvedParams - keep original and inherit partial
......@@ -945,6 +953,7 @@ function reifyRouteTree(
return {
requestKey: pattern.requestKey,
segment: newSegment,
shellVaryPath: getShellSegmentVaryPath(newVaryPath),
refreshState: pattern.refreshState,
slots: newSlots,
......@@ -961,6 +970,7 @@ function reifyRouteTree(
return {
requestKey: pattern.requestKey,
segment: newSegment,
shellVaryPath: getShellSegmentVaryPath(newVaryPath),
refreshState: pattern.refreshState,
slots: newSlots,
......
......@@ -1324,6 +1324,9 @@ function diffRouteTreeAgainstCurrent(
null,
null,
]
if (newTree.prefetchHints !== 0) {
requestTree[4] = newTree.prefetchHints
}
return requestTree
}
......@@ -1431,6 +1434,9 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
null,
refetchMarker,
]
if (tree.prefetchHints !== 0) {
requestTree[4] = tree.prefetchHints
}
return requestTree
}
......@@ -1564,6 +1570,9 @@ function pingRouteTreeAndIncludeDynamicData(
null,
refetchMarker,
]
if (tree.prefetchHints !== 0) {
requestTree[4] = tree.prefetchHints
}
return requestTree
}
......@@ -1618,6 +1627,9 @@ function pingRuntimePrefetches(
null,
null,
]
if (tree.prefetchHints !== 0) {
requestTree[4] = tree.prefetchHints
}
return requestTree
}
......
......@@ -37,6 +37,14 @@ export type VaryPath = {
*/
id: string | null
value: string | null | FallbackType
/**
* Whether this node corresponds to a root param — a path param at or above
* the application's root layout. Root params may appear in the App Shell, so
* the shell vary path keeps their concrete value instead of replacing it with
* Fallback. See getShellSegmentVaryPath. Only set on path param nodes;
* undefined (falsy) for structural and search param nodes.
*/
isRootParam?: boolean
parent: VaryPath | null
}
......@@ -142,11 +150,13 @@ export function getFulfilledRouteVaryPath(
export function appendLayoutVaryPath(
parentPath: PartialSegmentVaryPath | null,
cacheKey: string,
paramName: string
paramName: string,
isRootParam: boolean
): PartialSegmentVaryPath {
const varyPathPart: VaryPath = {
id: paramName,
value: cacheKey,
isRootParam,
parent: parentPath,
}
return varyPathPart as PartialSegmentVaryPath
......@@ -270,10 +280,11 @@ export function getSegmentVaryPathForRequest(
const originalVaryPath = tree.varyPath
if (fetchStrategy === FetchStrategy.RuntimeShell) {
// The Shell phase issues a runtime render with params omitted. The
// resulting entry is reusable across all concrete param values, so we
// key it at the shell vary path (every param substituted with Fallback).
return getShellSegmentVaryPath(originalVaryPath)
// The Shell phase issues a runtime render with non-root params omitted. The
// resulting entry is reusable across all concrete values of those params, so
// we key it at the precomputed shell vary path (every non-root param
// substituted with Fallback; root params keep their concrete value).
return tree.shellVaryPath
}
// Only page segments (and the special "metadata" segment, which is treated
......@@ -362,6 +373,7 @@ export function getFulfilledSegmentVaryPath(
original.id === null || varyParams.has(original.id)
? original.value
: Fallback,
isRootParam: original.isRootParam,
parent:
original.parent === null
? null
......@@ -370,23 +382,22 @@ export function getFulfilledSegmentVaryPath(
return clone as SegmentVaryPath
}
function getShellSegmentVaryPath(original: VaryPath): SegmentVaryPath {
export function getShellSegmentVaryPath(original: VaryPath): SegmentVaryPath {
// Re-keys a segment's vary path to identify the "App Shell" entry for this
// segment position — a reusable, param-free loading state that can be served
// for any concrete navigation to this segment. Every param node (path
// params, search params) is replaced with Fallback; only structural nodes
// (request keys, etc.) keep their concrete value.
//
// NOTE: For now, we treat root params the same as non-root params and
// forbid them from the shell. Root params change less frequently than
// other params, though, so caching the shell across root param values is
// a potential future optimization. One way to model that would be to
// evict the entire client cache whenever a root param change is detected.
// Then we would no longer need to include them in the cache key, which
// would be consistent with how we treat session-based data like cookies.
// segment position — a reusable loading state that can be served for any
// concrete navigation to this segment. The shell is rendered with params
// omitted, with one exception: root params (path params at or above the root
// layout) may be accessed during the shell render, so the shell varies on
// them. Accordingly, we keep the concrete value of structural nodes (request
// keys, etc.) and root param nodes, and replace every other param node (non-
// root path params and search params) with Fallback.
const clone: VaryPath = {
id: original.id,
value: original.id === null ? original.value : Fallback,
value:
original.id === null || original.isRootParam === true
? original.value
: Fallback,
isRootParam: original.isRootParam,
parent:
original.parent === null
? null
......
......@@ -12,7 +12,7 @@ describe('prepareFlightRouterStateForRequest', () => {
{},
['/some/url', ''],
'refetch',
PrefetchHint.IsRootLayout | 1,
PrefetchHint.IsRootLayoutOrAbove | 1,
]
const result = prepareFlightRouterStateForRequest(flightRouterState, true)
......@@ -129,19 +129,19 @@ describe('prepareFlightRouterStateForRequest', () => {
})
describe('optional fields preservation', () => {
it('should preserve prefetchHints with IsRootLayout', () => {
it('should preserve prefetchHints with IsRootLayoutOrAbove', () => {
const flightRouterState: FlightRouterState = [
'segment',
{},
null,
null,
PrefetchHint.IsRootLayout,
PrefetchHint.IsRootLayoutOrAbove,
]
const result = prepareFlightRouterStateForRequest(flightRouterState)
const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded[4]).toBe(PrefetchHint.IsRootLayout)
expect(decoded[4]).toBe(PrefetchHint.IsRootLayoutOrAbove)
})
it('should preserve prefetchHints with SegmentHasLoadingBoundary', () => {
......@@ -250,7 +250,8 @@ describe('prepareFlightRouterStateForRequest', () => {
},
['/dashboard/url', ''],
'refetch',
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary,
PrefetchHint.IsRootLayoutOrAbove |
PrefetchHint.SegmentHasLoadingBoundary,
],
sidebar: [
['slug', 'user-123', 'd', null],
......@@ -261,7 +262,8 @@ describe('prepareFlightRouterStateForRequest', () => {
},
['/main/url', ''],
'inside-shared-layout',
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary,
PrefetchHint.IsRootLayoutOrAbove |
PrefetchHint.SegmentHasLoadingBoundary,
]
const result = prepareFlightRouterStateForRequest(complexState)
......@@ -272,7 +274,8 @@ describe('prepareFlightRouterStateForRequest', () => {
expect(decoded[2]).toBeNull() // URL stripped
expect(decoded[3]).toBe('inside-shared-layout') // server marker preserved
expect(decoded[4]).toBe(
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary
PrefetchHint.IsRootLayoutOrAbove |
PrefetchHint.SegmentHasLoadingBoundary
) // prefetchHints preserved
// Children route checks
......@@ -280,7 +283,8 @@ describe('prepareFlightRouterStateForRequest', () => {
expect(childrenRoute[2]).toBeNull() // URL stripped
expect(childrenRoute[3]).toBe('refetch') // server marker preserved
expect(childrenRoute[4]).toBe(
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary
PrefetchHint.IsRootLayoutOrAbove |
PrefetchHint.SegmentHasLoadingBoundary
) // prefetchHints preserved
// Modal route checks
......
......@@ -51,7 +51,7 @@ async function createFlightRouterStateFromLoaderTreeImpl(
// compute the other hints below. In the future this should be a build
// error, but for now we gracefully degrade.
//
// TODO: Move more of the hints computation (IsRootLayout, instant config,
// TODO: Move more of the hints computation (IsRootLayoutOrAbove, instant config,
// loading boundary detection) into the build-time measurement step in
// collectPrefetchHints, so this function only needs to union the
// precomputed bitmask rather than re-derive hints on every render.
......@@ -89,10 +89,14 @@ async function createFlightRouterStateFromLoaderTreeImpl(
}
}
// Mark the first segment that has a layout as the "root" layout
if (!didFindRootLayout && typeof layout !== 'undefined') {
didFindRootLayout = true
prefetchHints |= PrefetchHint.IsRootLayout
// Mark every segment at or above the root layout (i.e. until we descend past
// the first segment that has a layout).
if (!didFindRootLayout) {
prefetchHints |= PrefetchHint.IsRootLayoutOrAbove
if (typeof layout !== 'undefined') {
// This segment is the root layout; its descendants are below it.
didFindRootLayout = true
}
}
const isInstant =
......@@ -177,9 +181,12 @@ export async function createFlightRouterStateFromLoaderTree(
isStaticGeneration: boolean,
isBuildTimePrerendering: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any
searchParams: any,
// Whether a root layout was already found above this loader tree slice, so a
// slice that starts below the root layout doesn't mark a sub-layout as the
// root layout.
didFindRootLayout: boolean = false
): Promise<FlightRouterState> {
const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl(
loaderTree,
hintTree,
......@@ -202,13 +209,14 @@ export async function createRouteTreePrefetch(
partialPrefetching: boolean | 'unstable_eager' | undefined,
isStaticGeneration: boolean,
isBuildTimePrerendering: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment
getDynamicParamFromSegment: GetDynamicParamFromSegment,
// See note on createFlightRouterStateFromLoaderTree's didFindRootLayout.
didFindRootLayout: boolean = false
): Promise<FlightRouterState> {
// Search params should not be added to page segment's cache key during a
// route tree prefetch request, because they do not affect the structure of
// the route. The client cache has its own logic to handle search params.
const searchParams = {}
const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl(
loaderTree,
hintTree,
......
......@@ -17,7 +17,7 @@ const validFixtures = [
},
null,
null,
0b10000, // PrefetchHint.IsRootLayout
0b10000, // PrefetchHint.IsRootLayoutOrAbove
],
[
['a', 'b', 'c', null],
......
......@@ -167,7 +167,8 @@ export async function walkTreeWithFlightRouterState({
partialPrefetching,
isStaticGeneration,
isBuildTimePrerendering,
getDynamicParamFromSegment
getDynamicParamFromSegment,
rootLayoutIncluded
)
: await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter,
......@@ -178,7 +179,8 @@ export async function walkTreeWithFlightRouterState({
isStaticGeneration,
isBuildTimePrerendering,
getDynamicParamFromSegment,
query
query,
rootLayoutIncluded
)
return [
......@@ -220,7 +222,8 @@ export async function walkTreeWithFlightRouterState({
isStaticGeneration,
isBuildTimePrerendering,
getDynamicParamFromSegment,
query
query,
rootLayoutIncluded
)
return [
[
......@@ -253,7 +256,8 @@ export async function walkTreeWithFlightRouterState({
isStaticGeneration,
isBuildTimePrerendering,
getDynamicParamFromSegment,
query
query,
rootLayoutIncluded
)
// Create component tree using the slice of the loaderTree
......
......@@ -194,8 +194,10 @@ export const enum PrefetchHint {
// A descendant segment (but not this one) has a loading.tsx boundary.
// Propagates upward so the root reflects the entire subtree.
SubtreeHasLoadingBoundary = 0b01000,
// This segment is the root layout of the application.
IsRootLayout = 0b10000,
// This segment is at or above the application's root layout — the root layout
// segment itself and all of its ancestors. A dynamic param in one of these
// segments is a "root param".
IsRootLayoutOrAbove = 0b10000,
// This segment's response includes its parent's data inlined into it.
// Set at build time by the segment size measurement pass.
ParentInlinedIntoSelf = 0b100000,
......@@ -245,7 +247,7 @@ export const StaticPrefetchDisabled =
/**
* The subset of PrefetchHint bits that propagate upward from a child segment to
* its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary
* or IsRootLayout). Used to clear stale propagated bits before re-deriving them
* or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them
* from a node's children.
*/
export const SubtreePrefetchHints =
......
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