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
......@@ -21,10 +21,7 @@ import { applyFlightData } from '../apply-flight-data'
import { prefetchQueue } from './prefetch-reducer'
import { createEmptyCacheNode } from '../../app-router'
import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
import {
listenForDynamicRequest,
updateCacheNodeOnNavigation,
} from '../ppr-navigations'
import { listenForDynamicRequest, startPPRNavigation } from '../ppr-navigations'
import {
getOrCreatePrefetchCacheEntry,
prunePrefetchCache,
......@@ -296,23 +293,19 @@ export function navigateReducer(
}
if (newTree !== null) {
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
if (
// This is just a paranoid check. When a route is PPRed, the server
// will send back a static response that's rendered from
// the root. If for some reason it doesn't, we fall back to the
// non-PPR implementation.
// 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.
seedData &&
isRootRender &&
postponed
) {
const task = updateCacheNodeOnNavigation(
const task = startPPRNavigation(
currentCache,
currentTree,
treePatch,
......@@ -322,7 +315,12 @@ export function navigateReducer(
)
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.
// TODO: We should remove applyRouterStatePatchToTree
// from the PPR path entirely.
......@@ -379,6 +377,11 @@ export function navigateReducer(
// given that PPR prefetches are always static and return the whole
// tree. Or in the meantime we could factor it out into a
// separate function.
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
const cache: CacheNode = createEmptyCacheNode()
let applied = false
......
......@@ -11,7 +11,7 @@ import type {
import type { NormalizedFlightData } from '../../flight-data-helpers'
import { fetchServerResponse } from '../router-reducer/fetch-server-response'
import {
updateCacheNodeOnNavigation,
startPPRNavigation,
listenForDynamicRequest,
type Task as PPRNavigationTask,
} from '../router-reducer/ppr-navigations'
......@@ -82,7 +82,7 @@ export function navigate(
currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState,
nextUrl: string | null
): AsyncNavigationResult | SuccessfulNavigationResult | NoOpNavigationResult {
): NavigationResult {
const now = Date.now()
const cacheKey = createCacheKey(url.href, nextUrl)
......@@ -129,17 +129,14 @@ function navigateUsingPrefetchedRouteTree(
prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean,
canonicalUrl: string
): SuccessfulNavigationResult | NoOpNavigationResult {
): SuccessfulNavigationResult | NoOpNavigationResult | MPANavigationResult {
// Recursively construct a prefetch tree by reading from the Segment Cache. To
// maintain compatibility, we output the same data structures as the old
// prefetching implementation: FlightRouterState and CacheNodeSeedData.
// TODO: Eventually updateCacheNodeOnNavigation (or the equivalent) should
// read from the Segment Cache directly. It's only structured this way for now
// 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.
// reimplement the isNavigatingToNewRootLayout logic
// inside updateCacheNodeOnNavigation.
const task = updateCacheNodeOnNavigation(
const task = startPPRNavigation(
currentCacheNode,
currentFlightRouterState,
prefetchFlightRouterState,
......@@ -169,12 +166,21 @@ function navigationTaskToResult(
task: PPRNavigationTask,
currentCacheNode: CacheNode,
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
return {
tag: NavigationResultTag.Success,
data: {
flightRouterState: task.route,
flightRouterState,
cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode,
canonicalUrl,
},
......@@ -308,7 +314,7 @@ async function navigateDynamicallyWithNoPrefetch(
)
// Now we proceed exactly as we would for normal navigation.
const task = updateCacheNodeOnNavigation(
const task = startPPRNavigation(
currentCacheNode,
currentFlightRouterState,
prefetchFlightRouterState,
......@@ -318,7 +324,7 @@ async function navigateDynamicallyWithNoPrefetch(
)
if (task !== null) {
// 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.
//
// 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