Unverified Commit 81ce3af8 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Segment Cache] Hard nav when root layout changes (#76163)

The highest-level layout in a route tree is referred to as the "root"
layout. When it changes, we perform a full-page (MPA-style) navigation.

To implement this for the Segment Cache, I moved the
`isNavigatingToNewRootLayout` check from `navigateReducer` into
`startPPRNavigation`.

Rather than run the `isNavigatingToNewRootLayout` check on every
navigation, I combined it with the route tree traversal we already
perform when diffing the tree on navigation. In the common case,
navigation happens inside the root layout. If we discover a root layout
before the first new segment is reached, we don't have to do anything
extra.

The only special case is when a root parameter changes. Although this
triggers a re-render of that segment, it shouldn't cause the root layout
to be treated as different for the purposes of deciding whether to
trigger an MPA navigation. It's only in this case where we need to
switch to a different tree traversal (isNavigatingToNewRootLayout).
parent 9fd557ff
...@@ -14,6 +14,7 @@ import { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment' ...@@ -14,6 +14,7 @@ import { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments' import { matchSegment } from '../match-segments'
import { createRouterCacheKey } from './create-router-cache-key' import { createRouterCacheKey } from './create-router-cache-key'
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'
// This is yet another tree type that is used to track pending promises that // This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of // need to be fulfilled once the dynamic data is received. The terminal nodes of
...@@ -21,7 +22,7 @@ import type { FetchServerResponseResult } from './fetch-server-response' ...@@ -21,7 +22,7 @@ import type { FetchServerResponseResult } from './fetch-server-response'
// request. We can't use the Cache Node tree or Route State tree directly // request. We can't use the Cache Node tree or Route State tree directly
// because those include reused nodes, too. This tree is discarded as soon as // because those include reused nodes, too. This tree is discarded as soon as
// the navigation response is received. // the navigation response is received.
export type Task = { type SPANavigationTask = {
// The router state that corresponds to the tree that this Task represents. // The router state that corresponds to the tree that this Task represents.
route: FlightRouterState route: FlightRouterState
// The CacheNode that corresponds to the tree that this Task represents. If // The CacheNode that corresponds to the tree that this Task represents. If
...@@ -34,9 +35,27 @@ export type Task = { ...@@ -34,9 +35,27 @@ export type Task = {
// If all the segments are static, then this will be null, and no server // If all the segments are static, then this will be null, and no server
// request is required. // request is required.
dynamicRequestTree: FlightRouterState | null dynamicRequestTree: FlightRouterState | null
children: Map<string, Task> | null children: Map<string, SPANavigationTask> | null
} }
// A special type used to bail out and trigger a full-page navigation.
type MPANavigationTask = {
// MPA tasks are distinguised from SPA tasks by having a null `route`.
route: null
node: null
dynamicRequestTree: null
children: null
}
const MPA_NAVIGATION_TASK: MPANavigationTask = {
route: null,
node: null,
dynamicRequestTree: null,
children: null,
}
export type Task = SPANavigationTask | MPANavigationTask
// Creates a new Cache Node tree (i.e. copy-on-write) that represents the // Creates a new Cache Node tree (i.e. copy-on-write) that represents the
// optimistic result of a navigation, using both the current Cache Node tree and // optimistic result of a navigation, using both the current Cache Node tree and
// data that was prefetched prior to navigation. // data that was prefetched prior to navigation.
...@@ -66,10 +85,30 @@ export type Task = { ...@@ -66,10 +85,30 @@ export type Task = {
// //
// A return value of `null` means there were no changes, and the previous tree // A return value of `null` means there were no changes, and the previous tree
// can be reused without initiating a server request. // can be reused without initiating a server request.
export function updateCacheNodeOnNavigation( export function startPPRNavigation(
oldCacheNode: CacheNode,
oldRouterState: FlightRouterState,
newRouterState: FlightRouterState,
prefetchData: CacheNodeSeedData | null,
prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean
): Task | null {
return updateCacheNodeOnNavigation(
oldCacheNode,
oldRouterState,
newRouterState,
false,
prefetchData,
prefetchHead,
isPrefetchHeadPartial
)
}
function updateCacheNodeOnNavigation(
oldCacheNode: CacheNode, oldCacheNode: CacheNode,
oldRouterState: FlightRouterState, oldRouterState: FlightRouterState,
newRouterState: FlightRouterState, newRouterState: FlightRouterState,
didFindRootLayout: boolean,
prefetchData: CacheNodeSeedData | null, prefetchData: CacheNodeSeedData | null,
prefetchHead: HeadData | null, prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean isPrefetchHeadPartial: boolean
...@@ -79,6 +118,17 @@ export function updateCacheNodeOnNavigation( ...@@ -79,6 +118,17 @@ export function updateCacheNodeOnNavigation(
const newRouterStateChildren = newRouterState[1] const newRouterStateChildren = newRouterState[1]
const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null
if (!didFindRootLayout) {
// 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. See beginRenderingNewRouteTree for context.
const isRootLayout = newRouterState[4] === true
if (isRootLayout) {
// Found a matching root layout.
didFindRootLayout = true
}
}
const oldParallelRoutes = oldCacheNode.parallelRoutes const oldParallelRoutes = oldCacheNode.parallelRoutes
// Clone the current set of segment children, even if they aren't active in // Clone the current set of segment children, even if they aren't active in
...@@ -163,14 +213,17 @@ export function updateCacheNodeOnNavigation( ...@@ -163,14 +213,17 @@ export function updateCacheNodeOnNavigation(
taskChild = spawnReusedTask(oldRouterStateChild) taskChild = spawnReusedTask(oldRouterStateChild)
} else { } else {
// There's no currently active segment. Switch to the "create" path. // There's no currently active segment. Switch to the "create" path.
taskChild = createCacheNodeOnNavigation( taskChild = beginRenderingNewRouteTree(
oldRouterStateChild,
newRouterStateChild, newRouterStateChild,
didFindRootLayout,
prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchDataChild !== undefined ? prefetchDataChild : null,
prefetchHead, prefetchHead,
isPrefetchHeadPartial isPrefetchHeadPartial
) )
} }
} else if ( } else if (
oldRouterStateChild !== undefined &&
oldSegmentChild !== undefined && oldSegmentChild !== undefined &&
matchSegment(newSegmentChild, oldSegmentChild) matchSegment(newSegmentChild, oldSegmentChild)
) { ) {
...@@ -184,16 +237,18 @@ export function updateCacheNodeOnNavigation( ...@@ -184,16 +237,18 @@ export function updateCacheNodeOnNavigation(
oldCacheNodeChild, oldCacheNodeChild,
oldRouterStateChild, oldRouterStateChild,
newRouterStateChild, newRouterStateChild,
didFindRootLayout,
prefetchDataChild, prefetchDataChild,
prefetchHead, prefetchHead,
isPrefetchHeadPartial isPrefetchHeadPartial
) )
} else { } else {
// Either there's no existing Cache Node for this segment, or this // There's no existing Cache Node for this segment. Switch to the
// segment doesn't exist in the old Router State tree. Switch to the
// "create" path. // "create" path.
taskChild = createCacheNodeOnNavigation( taskChild = beginRenderingNewRouteTree(
oldRouterStateChild,
newRouterStateChild, newRouterStateChild,
didFindRootLayout,
prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchDataChild !== undefined ? prefetchDataChild : null,
prefetchHead, prefetchHead,
isPrefetchHeadPartial isPrefetchHeadPartial
...@@ -201,8 +256,10 @@ export function updateCacheNodeOnNavigation( ...@@ -201,8 +256,10 @@ export function updateCacheNodeOnNavigation(
} }
} else { } else {
// This is a new tree. Switch to the "create" path. // This is a new tree. Switch to the "create" path.
taskChild = createCacheNodeOnNavigation( taskChild = beginRenderingNewRouteTree(
oldRouterStateChild,
newRouterStateChild, newRouterStateChild,
didFindRootLayout,
prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchDataChild !== undefined ? prefetchDataChild : null,
prefetchHead, prefetchHead,
isPrefetchHeadPartial isPrefetchHeadPartial
...@@ -210,7 +267,14 @@ export function updateCacheNodeOnNavigation( ...@@ -210,7 +267,14 @@ export function updateCacheNodeOnNavigation(
} }
if (taskChild !== null) { if (taskChild !== null) {
// Something changed in the child tree. Keep track of the child task. // Recursively propagate up the child tasks.
if (taskChild.route === null) {
// One of the child tasks discovered a change to the root layout.
// Immediately unwind from this recursive traversal.
return MPA_NAVIGATION_TASK
}
if (taskChildren === null) { if (taskChildren === null) {
taskChildren = new Map() taskChildren = new Map()
} }
...@@ -283,12 +347,56 @@ export function updateCacheNodeOnNavigation( ...@@ -283,12 +347,56 @@ export function updateCacheNodeOnNavigation(
} }
} }
function beginRenderingNewRouteTree(
oldRouterState: FlightRouterState | void,
newRouterState: FlightRouterState,
didFindRootLayout: boolean,
prefetchData: CacheNodeSeedData | null,
possiblyPartialPrefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean
): Task {
if (!didFindRootLayout) {
// The route tree changed before we reached a layout. (The highest-level
// layout in a route tree is referred to as the "root" layout.) This could
// mean that we're navigating between two different root layouts. When this
// happens, we perform a full-page (MPA-style) navigation.
//
// However, the algorithm for deciding where to start rendering a route
// (i.e. the one performed in order to reach this function) is stricter
// than the one used to detect a change in the root layout. So just because
// we're re-rendering a segment outside of the root layout does not mean we
// should trigger a full-page navigation.
//
// Specifically, we handle dynamic parameters differently: two segments are
// considered the same even if their parameter values are different.
//
// 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.
// In the common case, this branch is skipped completely.
if (
oldRouterState === undefined ||
isNavigatingToNewRootLayout(oldRouterState, newRouterState)
) {
// The root layout changed. Perform a full-page navigation.
return MPA_NAVIGATION_TASK
}
}
return createCacheNodeOnNavigation(
newRouterState,
prefetchData,
possiblyPartialPrefetchHead,
isPrefetchHeadPartial
)
}
function createCacheNodeOnNavigation( function createCacheNodeOnNavigation(
routerState: FlightRouterState, routerState: FlightRouterState,
prefetchData: CacheNodeSeedData | null, prefetchData: CacheNodeSeedData | null,
possiblyPartialPrefetchHead: HeadData | null, possiblyPartialPrefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean isPrefetchHeadPartial: boolean
): Task { ): SPANavigationTask {
// Same traversal as updateCacheNodeNavigation, but we switch to this path // Same traversal as updateCacheNodeNavigation, but we switch to this path
// once we reach the part of the tree that was not in the previous route. We // once we reach the part of the tree that was not in the previous route. We
// don't need to diff against the old tree, we just need to create a new one. // don't need to diff against the old tree, we just need to create a new one.
...@@ -424,7 +532,7 @@ function spawnPendingTask( ...@@ -424,7 +532,7 @@ function spawnPendingTask(
prefetchData: CacheNodeSeedData | null, prefetchData: CacheNodeSeedData | null,
prefetchHead: HeadData | null, prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean isPrefetchHeadPartial: boolean
): Task { ): SPANavigationTask {
// Create a task that will later be fulfilled by data from the server. // Create a task that will later be fulfilled by data from the server.
// Clone the prefetched route tree and the `refetch` marker to it. We'll send // Clone the prefetched route tree and the `refetch` marker to it. We'll send
...@@ -480,7 +588,7 @@ function spawnReusedTask(reusedRouterState: FlightRouterState): Task { ...@@ -480,7 +588,7 @@ function spawnReusedTask(reusedRouterState: FlightRouterState): Task {
// This does _not_ create a new tree; it modifies the existing one in place. // This does _not_ create a new tree; it modifies the existing one in place.
// Which means it must follow the Suspense rules of cache safety. // Which means it must follow the Suspense rules of cache safety.
export function listenForDynamicRequest( export function listenForDynamicRequest(
task: Task, task: SPANavigationTask,
responsePromise: Promise<FetchServerResponseResult> responsePromise: Promise<FetchServerResponseResult>
) { ) {
responsePromise.then( responsePromise.then(
...@@ -528,7 +636,7 @@ export function listenForDynamicRequest( ...@@ -528,7 +636,7 @@ export function listenForDynamicRequest(
} }
function writeDynamicDataIntoPendingTask( function writeDynamicDataIntoPendingTask(
rootTask: Task, rootTask: SPANavigationTask,
segmentPath: FlightSegmentPath, segmentPath: FlightSegmentPath,
serverRouterState: FlightRouterState, serverRouterState: FlightRouterState,
dynamicData: CacheNodeSeedData, dynamicData: CacheNodeSeedData,
...@@ -576,7 +684,7 @@ function writeDynamicDataIntoPendingTask( ...@@ -576,7 +684,7 @@ function writeDynamicDataIntoPendingTask(
} }
function finishTaskUsingDynamicDataPayload( function finishTaskUsingDynamicDataPayload(
task: Task, task: SPANavigationTask,
serverRouterState: FlightRouterState, serverRouterState: FlightRouterState,
dynamicData: CacheNodeSeedData, dynamicData: CacheNodeSeedData,
dynamicHead: HeadData dynamicHead: HeadData
...@@ -802,7 +910,7 @@ function finishPendingCacheNode( ...@@ -802,7 +910,7 @@ function finishPendingCacheNode(
} }
} }
export function abortTask(task: Task, error: any): void { export function abortTask(task: SPANavigationTask, error: any): void {
const cacheNode = task.node const cacheNode = task.node
if (cacheNode === null) { if (cacheNode === null) {
// This indicates the task is already complete. // This indicates the task is already complete.
......
...@@ -21,10 +21,7 @@ import { applyFlightData } from '../apply-flight-data' ...@@ -21,10 +21,7 @@ import { applyFlightData } from '../apply-flight-data'
import { prefetchQueue } from './prefetch-reducer' import { prefetchQueue } from './prefetch-reducer'
import { createEmptyCacheNode } from '../../app-router' import { createEmptyCacheNode } from '../../app-router'
import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment' import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
import { import { listenForDynamicRequest, startPPRNavigation } from '../ppr-navigations'
listenForDynamicRequest,
updateCacheNodeOnNavigation,
} from '../ppr-navigations'
import { import {
getOrCreatePrefetchCacheEntry, getOrCreatePrefetchCacheEntry,
prunePrefetchCache, prunePrefetchCache,
...@@ -296,23 +293,19 @@ export function navigateReducer( ...@@ -296,23 +293,19 @@ export function navigateReducer(
} }
if (newTree !== null) { if (newTree !== null) {
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
if ( if (
// This is just a paranoid check. When a route is PPRed, the server // This is just a paranoid check. When a route is PPRed, the server
// will send back a static response that's rendered from // will send back a static response that's rendered from
// the root. If for some reason it doesn't, we fall back to the // the root. If for some reason it doesn't, we fall back to the
// non-PPR implementation. // non-PPR implementation.
// TODO: We should get rid of the else branch and do all navigations // TODO: We should get rid of the else branch and do all navigations
// via updateCacheNodeOnNavigation. The current structure is just // via startPPRNavigation. The current structure is just
// an incremental step. // an incremental step.
seedData && seedData &&
isRootRender && isRootRender &&
postponed postponed
) { ) {
const task = updateCacheNodeOnNavigation( const task = startPPRNavigation(
currentCache, currentCache,
currentTree, currentTree,
treePatch, treePatch,
...@@ -322,7 +315,12 @@ export function navigateReducer( ...@@ -322,7 +315,12 @@ export function navigateReducer(
) )
if (task !== null) { if (task !== null) {
// Use the tree computed by updateCacheNodeOnNavigation instead if (task.route === null) {
// Detected a change to the root layout. Perform an full-
// page navigation.
return handleExternalUrl(state, mutable, href, pendingPush)
}
// Use the tree computed by startPPRNavigation instead
// of the one computed by applyRouterStatePatchToTree. // of the one computed by applyRouterStatePatchToTree.
// TODO: We should remove applyRouterStatePatchToTree // TODO: We should remove applyRouterStatePatchToTree
// from the PPR path entirely. // from the PPR path entirely.
...@@ -379,6 +377,11 @@ export function navigateReducer( ...@@ -379,6 +377,11 @@ export function navigateReducer(
// given that PPR prefetches are always static and return the whole // given that PPR prefetches are always static and return the whole
// tree. Or in the meantime we could factor it out into a // tree. Or in the meantime we could factor it out into a
// separate function. // separate function.
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
const cache: CacheNode = createEmptyCacheNode() const cache: CacheNode = createEmptyCacheNode()
let applied = false let applied = false
......
...@@ -11,7 +11,7 @@ import type { ...@@ -11,7 +11,7 @@ import type {
import type { NormalizedFlightData } from '../../flight-data-helpers' import type { NormalizedFlightData } from '../../flight-data-helpers'
import { fetchServerResponse } from '../router-reducer/fetch-server-response' import { fetchServerResponse } from '../router-reducer/fetch-server-response'
import { import {
updateCacheNodeOnNavigation, startPPRNavigation,
listenForDynamicRequest, listenForDynamicRequest,
type Task as PPRNavigationTask, type Task as PPRNavigationTask,
} from '../router-reducer/ppr-navigations' } from '../router-reducer/ppr-navigations'
...@@ -82,7 +82,7 @@ export function navigate( ...@@ -82,7 +82,7 @@ export function navigate(
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null nextUrl: string | null
): AsyncNavigationResult | SuccessfulNavigationResult | NoOpNavigationResult { ): NavigationResult {
const now = Date.now() const now = Date.now()
const cacheKey = createCacheKey(url.href, nextUrl) const cacheKey = createCacheKey(url.href, nextUrl)
...@@ -129,17 +129,14 @@ function navigateUsingPrefetchedRouteTree( ...@@ -129,17 +129,14 @@ function navigateUsingPrefetchedRouteTree(
prefetchHead: HeadData | null, prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean, isPrefetchHeadPartial: boolean,
canonicalUrl: string canonicalUrl: string
): SuccessfulNavigationResult | NoOpNavigationResult { ): SuccessfulNavigationResult | NoOpNavigationResult | MPANavigationResult {
// Recursively construct a prefetch tree by reading from the Segment Cache. To // Recursively construct a prefetch tree by reading from the Segment Cache. To
// maintain compatibility, we output the same data structures as the old // maintain compatibility, we output the same data structures as the old
// prefetching implementation: FlightRouterState and CacheNodeSeedData. // prefetching implementation: FlightRouterState and CacheNodeSeedData.
// TODO: Eventually updateCacheNodeOnNavigation (or the equivalent) should // TODO: Eventually updateCacheNodeOnNavigation (or the equivalent) should
// read from the Segment Cache directly. It's only structured this way for now // read from the Segment Cache directly. It's only structured this way for now
// so we can share code with the old prefetching implementation. // so we can share code with the old prefetching implementation.
// TODO: Need to detect whether we're navigating to a new root layout, i.e. const task = startPPRNavigation(
// reimplement the isNavigatingToNewRootLayout logic
// inside updateCacheNodeOnNavigation.
const task = updateCacheNodeOnNavigation(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
...@@ -169,12 +166,21 @@ function navigationTaskToResult( ...@@ -169,12 +166,21 @@ function navigationTaskToResult(
task: PPRNavigationTask, task: PPRNavigationTask,
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
canonicalUrl: string canonicalUrl: string
): SuccessfulNavigationResult { ): SuccessfulNavigationResult | MPANavigationResult {
const flightRouterState = task.route
if (flightRouterState === null) {
// When no router state is provided, it signals that we should perform an
// MPA navigation.
return {
tag: NavigationResultTag.MPA,
data: canonicalUrl,
}
}
const newCacheNode = task.node const newCacheNode = task.node
return { return {
tag: NavigationResultTag.Success, tag: NavigationResultTag.Success,
data: { data: {
flightRouterState: task.route, flightRouterState,
cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode, cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode,
canonicalUrl, canonicalUrl,
}, },
...@@ -308,7 +314,7 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -308,7 +314,7 @@ async function navigateDynamicallyWithNoPrefetch(
) )
// Now we proceed exactly as we would for normal navigation. // Now we proceed exactly as we would for normal navigation.
const task = updateCacheNodeOnNavigation( const task = startPPRNavigation(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
...@@ -318,7 +324,7 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -318,7 +324,7 @@ async function navigateDynamicallyWithNoPrefetch(
) )
if (task !== null) { if (task !== null) {
// In this case, we've already sent the dynamic request, so we don't // In this case, we've already sent the dynamic request, so we don't
// actually use the request tree created by `updateCacheNodeOnNavigation`, // actually use the request tree created by `startPPRNavigation`,
// except to check if it contains dynamic holes. // except to check if it contains dynamic holes.
// //
// This is almost always true, but it could be false if all the segment data // This is almost always true, but it could be false if all the segment data
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default async function Page() {
return (
<>
<p>
This link <em>should</em> trigger an MPA navigation, because it
navigates to a different root layout:
</p>
<p>
<Link href="/foo">/foo</Link>
</p>
</>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export function generateStaticParams() {
return [{ rootParam: 'foo' }, { rootParam: 'bar' }]
}
export default async function Page({ params }) {
const { rootParam } = params
const otherRootParam = rootParam === 'foo' ? 'bar' : 'foo'
return (
<>
<p>
<p>
This link <em>should not</em> trigger an MPA navigation, because it
only changes a root param:
</p>
<Link href={`/${otherRootParam}`}>/{otherRootParam}</Link>
</p>
<p>
<p>
This link <em>should</em> trigger an MPA navigation, because in
addition to changing a root param, it also navigates to a different
root layout:
</p>
<Link href={`/${otherRootParam}/inner`}>/{otherRootParam}/inner</Link>
</p>
</>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
return [{ rootParam: 'foo' }, { rootParam: 'bar' }]
}
export default async function Page() {
return <p>Content of inner page</p>
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: boolean
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('segment cache (MPA navigations)', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (isNextDev || skipped) {
test('ppr is disabled', () => {})
return
}
it('triggers MPA navigation when navigating to a different root layout', async () => {
const browser = await next.browser('/')
// Set an expando on the html element so we can detect if the page
// gets unloaded.
const html = await browser.elementByCss('html')
await html.evaluate((el) => (el.__expando = true))
// Navigate to a page with a different root layout.
const link = await browser.elementByCss(`a[href="/foo"]`)
await link.click()
// The expando should not be present because we did a full-page navigation.
const htmlAfterNav = await browser.elementByCss('html')
expect(await htmlAfterNav.evaluate((el) => el.__expando)).toBe(undefined)
})
it(
'triggers MPA navigation when navigating to a different root layout, ' +
'during a navigation where a root param also changed',
async () => {
// Testing this scenario because a root param change alone does not
// trigger an MPA navigation, but if an inner segment changes before the
// root layout, then we should trigger an MPA navigation. This case is
// handled slightly differently in the implementation than the case where
// there's no root param change.
const browser = await next.browser('/foo')
// Set an expando on the html element so we can detect if the page
// gets unloaded.
const html = await browser.elementByCss('html')
await html.evaluate((el) => (el.__expando = true))
// Navigate to a page with a different root layout.
const link = await browser.elementByCss(`a[href="/bar/inner"]`)
await link.click()
// The expando should not be present because we did a full-page navigation.
const htmlAfterNav = await browser.elementByCss('html')
expect(await htmlAfterNav.evaluate((el) => el.__expando)).toBe(undefined)
}
)
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
dynamicIO: true,
clientSegmentCache: true,
},
}
module.exports = nextConfig
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