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