Unverified Commit 08ae81fa authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] Fix loading.js not being counted as a suspense boundary (#90292)

Fixes a bug where a loading.js isn't properly considered as providing a
suspense boundary for a page. This is because we're placing the boundary
around the segment component itself, but it should be rendered above the
`LoadingBoundary` that is rendered around it (in `OuterLayoutRouter`).

This PR reworks the boundary placement logic to insert the boundary
above ErrorBoundary/LoadingBoundary (but below TemplateContext). It's a
little bit tricky to communicate this from `instant-validation` to the
client router. Instead of placing the boundary directly like before, we
now add a context to the innermost parent segment
(`PlaceValidationBoundaryBelowThisLevel`) and then the
`OuterLayoutRouter`s for the segments below see this context value and
add the validation boundary (`RenderValidationBoundaryAtThisLevel`)
parent 67bb800f
...@@ -694,6 +694,17 @@ export default function OuterLayoutRouter({ ...@@ -694,6 +694,17 @@ export default function OuterLayoutRouter({
use(unresolvedThenable) as never use(unresolvedThenable) as never
} }
let maybeValidationBoundaryId: string | null = null
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_DEV_SERVER
) {
const { InstantValidationBoundaryContext } =
require('../../server/app-render/instant-validation/boundary') as typeof import('../../server/app-render/instant-validation/boundary')
maybeValidationBoundaryId = use(InstantValidationBoundaryContext)
}
const activeSegment = activeTree[0] const activeSegment = activeTree[0]
const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null
const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params
...@@ -779,54 +790,68 @@ export default function OuterLayoutRouter({ ...@@ -779,54 +790,68 @@ export default function OuterLayoutRouter({
const isVirtual = debugName === undefined const isVirtual = debugName === undefined
const debugNameToDisplay = isVirtual ? undefined : debugNameContext const debugNameToDisplay = isVirtual ? undefined : debugNameContext
let child = ( let templateValue = (
<TemplateContext.Provider <ScrollAndMaybeFocusHandler segmentPath={segmentPath}>
key={stateKey} <ErrorBoundary
value={ errorComponent={error}
<ScrollAndMaybeFocusHandler segmentPath={segmentPath}> errorStyles={errorStyles}
<ErrorBoundary errorScripts={errorScripts}
errorComponent={error} >
errorStyles={errorStyles} <LoadingBoundary
errorScripts={errorScripts} name={debugNameToDisplay}
// TODO: The loading module data for a segment is stored on the
// parent, then applied to each of that parent segment's
// parallel route slots. In the simple case where there's only
// one parallel route (the `children` slot), this is no
// different from if the loading module data were stored on the
// child directly. But I'm not sure this actually makes sense
// when there are multiple parallel routes. It's not a huge
// issue because you always have the option to define a narrower
// loading boundary for a particular slot. But this sort of
// smells like an implementation accident to me.
loading={parentLoadingData}
>
<HTTPAccessFallbackBoundary
notFound={notFound}
forbidden={forbidden}
unauthorized={unauthorized}
> >
<LoadingBoundary <RedirectBoundary>
name={debugNameToDisplay} <InnerLayoutRouter
// TODO: The loading module data for a segment is stored on the url={url}
// parent, then applied to each of that parent segment's tree={tree}
// parallel route slots. In the simple case where there's only params={params}
// one parallel route (the `children` slot), this is no cacheNode={cacheNode}
// different from if the loading module data were stored on the segmentPath={segmentPath}
// child directly. But I'm not sure this actually makes sense debugNameContext={childDebugNameContext}
// when there are multiple parallel routes. It's not a huge isActive={isActive && stateKey === activeStateKey}
// issue because you always have the option to define a narrower />
// loading boundary for a particular slot. But this sort of {segmentBoundaryTriggerNode}
// smells like an implementation accident to me. </RedirectBoundary>
loading={parentLoadingData} </HTTPAccessFallbackBoundary>
> </LoadingBoundary>
<HTTPAccessFallbackBoundary </ErrorBoundary>
notFound={notFound} {segmentViewStateNode}
forbidden={forbidden} </ScrollAndMaybeFocusHandler>
unauthorized={unauthorized} )
>
<RedirectBoundary> if (
<InnerLayoutRouter typeof window === 'undefined' &&
url={url} process.env.__NEXT_CACHE_COMPONENTS &&
tree={tree} process.env.__NEXT_DEV_SERVER &&
params={params} typeof maybeValidationBoundaryId === 'string'
cacheNode={cacheNode} ) {
segmentPath={segmentPath} const { RenderValidationBoundaryAtThisLevel } =
debugNameContext={childDebugNameContext} require('../../server/app-render/instant-validation/boundary') as typeof import('../../server/app-render/instant-validation/boundary')
isActive={isActive && stateKey === activeStateKey} templateValue = (
/> <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>
{segmentBoundaryTriggerNode} {templateValue}
</RedirectBoundary> </RenderValidationBoundaryAtThisLevel>
</HTTPAccessFallbackBoundary> )
</LoadingBoundary> }
</ErrorBoundary>
{segmentViewStateNode} let child = (
</ScrollAndMaybeFocusHandler> <TemplateContext.Provider key={stateKey} value={templateValue}>
}
>
{templateStyles} {templateStyles}
{templateScripts} {templateScripts}
{template} {template}
......
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
'use client' 'use client'
import type { ReactNode } from 'react' import { createContext, type ReactNode } from 'react'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants' import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
import { InvariantError } from '../../../shared/lib/invariant-error' import { InvariantError } from '../../../shared/lib/invariant-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external' import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
...@@ -55,7 +56,46 @@ const NameSpace = { ...@@ -55,7 +56,46 @@ const NameSpace = {
}, },
} }
export const InstantValidationBoundary = type BoundaryPlacement =
| null // do not place here
| string // boundaryId -- place here
export const InstantValidationBoundaryContext =
createContext<BoundaryPlacement>(null)
export function PlaceValidationBoundaryBelowThisLevel({
id,
children,
}: {
id: string
children: ReactNode
}) {
return (
// OuterLayoutRouter will see this and render a `RenderValidationBoundaryAtThisLevel`.
<InstantValidationBoundaryContext value={id}>
{children}
</InstantValidationBoundaryContext>
)
}
export function RenderValidationBoundaryAtThisLevel({
id,
children,
}: {
id: string
children: ReactNode
}) {
// We got a boundaryId from the context. Clear the context so that the children don't render another boundary.
return (
<InstantValidationBoundary id={id}>
<InstantValidationBoundaryContext value={null}>
{children}
</InstantValidationBoundaryContext>
</InstantValidationBoundary>
)
}
const InstantValidationBoundary =
// We use slice(0) to trick the bundler into not inlining/minifying the function // We use slice(0) to trick the bundler into not inlining/minifying the function
// so it retains the name inferred from the namespace object // so it retains the name inferred from the namespace object
NameSpace[ NameSpace[
......
...@@ -18,7 +18,7 @@ import { ...@@ -18,7 +18,7 @@ import {
import { getDigestForWellKnownError } from '../create-error-handler' import { getDigestForWellKnownError } from '../create-error-handler'
import { import {
// NOTE: we're in the server layer, so this is a client reference // NOTE: we're in the server layer, so this is a client reference
InstantValidationBoundary, PlaceValidationBoundaryBelowThisLevel,
} from './boundary' } from './boundary'
import type { ValidationBoundaryTracking } from './boundary-tracking' import type { ValidationBoundaryTracking } from './boundary-tracking'
import { import {
...@@ -200,24 +200,6 @@ export async function findNavigationsToValidate( ...@@ -200,24 +200,6 @@ export async function findNavigationsToValidate(
if (instantConfig === false) { if (instantConfig === false) {
navigationParents = [] navigationParents = []
} else { } else {
// If the page itself has a prefetch config, then
// make sure we always validate a navigation from its parent
// to ensure `__PAGE__?p=foo -> __PAGE__?p=bar` works.
//
// This is relevant if the parent layout is implicit, as in
// my-segment/
// loading.tsx
// page.tsx
// because the above code for layouts wouldn't add it.
// TODO: what if this is runtime-prefetched? how does that affect a search-param navigation?
// TODO: this can cause double validation if the parent segment is empty
// but we have a parent layout that'd be validated
if (parentPath === null) {
throw new InvariantError('A page must have a root layout')
}
if (!navigationParents.includes(parentPath)) {
navigationParents.push(parentPath)
}
const task: ValidationTask = { const task: ValidationTask = {
target: segmentPath, target: segmentPath,
parents: navigationParents, parents: navigationParents,
...@@ -878,8 +860,7 @@ function createValidationSeedData( ...@@ -878,8 +860,7 @@ function createValidationSeedData(
async function createSeedDataFromValidationTreeImpl( async function createSeedDataFromValidationTreeImpl(
routeTree: RouteTree, routeTree: RouteTree,
state: TraversalState, state: TraversalState
parentState: TraversalState | null
) { ) {
const { path, slots } = routeTree const { path, slots } = routeTree
...@@ -965,28 +946,28 @@ function createValidationSeedData( ...@@ -965,28 +946,28 @@ function createValidationSeedData(
// We place the validation boundary right below the shared parent segment // We place the validation boundary right below the shared parent segment
// This means that a dynamic hole is accepted as long as it has a Suspense boundary // This means that a dynamic hole is accepted as long as it has a Suspense boundary
// in the new subtree (i.e. it wouldn't block the navigation). // in the new subtree (i.e. it wouldn't block the navigation).
const isValidationBoundary = const isInnermostSharedParent =
state.kind === 'new-tree' && state.kind === 'shared-tree' && nextState.kind === 'new-tree'
parentState &&
parentState.kind === 'shared-tree'
if (isValidationBoundary) { if (isInnermostSharedParent) {
debug?.( debug?.(
` ['${path}' is in the new subtree, adding validation boundary around it]` ` ['${path}' is the innermost shared parent, adding validation boundary below it]`
) )
const boundaryId = path const boundaryId = path
boundaryState.expectedIds.add(boundaryId) boundaryState.expectedIds.add(boundaryId)
segmentData = { segmentData = {
...segmentData, ...segmentData,
node: ( node: (
// bundled in the server layer // When we wrap the node in a context provider,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx // the first OuterLayoutRouter inside it will see it and place a validation boundary.
<InstantValidationBoundary
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer
<PlaceValidationBoundaryBelowThisLevel
id={boundaryId} id={boundaryId}
key="c" /* matching `cacheNodeKey` */ key="c" /* matching `cacheNodeKey` */
> >
{segmentData.node} {segmentData.node}
</InstantValidationBoundary> </PlaceValidationBoundaryBelowThisLevel>
), ),
} }
} }
...@@ -997,8 +978,7 @@ function createValidationSeedData( ...@@ -997,8 +978,7 @@ function createValidationSeedData(
slotsSeedData[parallelRouteKey] = slotsSeedData[parallelRouteKey] =
await createSeedDataFromValidationTreeImpl( await createSeedDataFromValidationTreeImpl(
slots[parallelRouteKey], slots[parallelRouteKey],
nextState, nextState
state
) )
} }
} }
...@@ -1008,8 +988,7 @@ function createValidationSeedData( ...@@ -1008,8 +988,7 @@ function createValidationSeedData(
return createSeedDataFromValidationTreeImpl( return createSeedDataFromValidationTreeImpl(
rootRouteTree, rootRouteTree,
// Root layouts are always shared. Navigating to a new root layout is an MPA navigation. // Root layouts are always shared. Navigating to a new root layout is an MPA navigation.
{ kind: 'shared-tree' }, { kind: 'shared-tree' }
null
) )
} }
......
...@@ -88,7 +88,13 @@ export default async function Page() { ...@@ -88,7 +88,13 @@ export default async function Page() {
<DebugLinks href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinks href="/suspense-in-root/static/invalid-only-loading-around-dynamic" /> <DebugLinks href="/suspense-in-root/static/valid-only-loading-around-dynamic" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-only-loading-around-dynamic-higher" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-dynamic-layout-with-loading" />
</li> </li>
<li> <li>
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-runtime" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-runtime" />
......
import { connection } from 'next/server'
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default async function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout has a dynamic hole without a suspense. There's a
loading.js at this level, but loading.js goes below the layout, so
this should fail validation.
</p>
<Dynamic />
</div>
<hr />
{children}
</>
)
}
async function Dynamic() {
await connection()
return 'Dynamic content from layout'
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<p>
This page doesn't wrap runtime/dynamic components in suspense, but it
has a loading.tsx, so these are fine.
</p>
<div>
<Runtime />
</div>
<div>
<Dynamic />
</div>
</main>
)
}
async function Runtime() {
await cookies()
return <div id="runtime-content">Runtime content from page</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
...@@ -7,10 +7,9 @@ export default async function Page() { ...@@ -7,10 +7,9 @@ export default async function Page() {
return ( return (
<main> <main>
<p> <p>
This page doesn't wrap runtime/dynamic components in suspense, so This page doesn't wrap runtime/dynamic components in suspense, but it
despite having a loading.tsx (which is equivalent to a suspense boundary has a loading.tsx above it. a self-navigation with a different search
in a parent layout), it shouldn't pass validation, because a param value would block, but we accept that.
self-navigation would block.
</p> </p>
<div> <div>
<Runtime /> <Runtime />
......
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>
This page doesn't wrap runtime/dynamic components in suspense, but it
has a loading.tsx. a self-navigation with a different search param value
would block, but we accept that.
</p>
<div>
<Runtime />
</div>
<div>
<Dynamic />
</div>
</main>
)
}
async function Runtime() {
await cookies()
return <div id="runtime-content">Runtime content from page</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
...@@ -759,20 +759,34 @@ describe('instant validation', () => { ...@@ -759,20 +759,34 @@ describe('instant validation', () => {
await expectNoValidationErrors(browser, await browser.url()) await expectNoValidationErrors(browser, await browser.url())
}) })
it('invalid - missing suspense around dynamic (with loading.js)', async () => { it('valid - no suspense needed around dynamic in page if loading.js is present', async () => {
const browser = await navigateTo( const browser = await navigateTo(
'/suspense-in-root/static/invalid-only-loading-around-dynamic' '/suspense-in-root/static/valid-only-loading-around-dynamic'
)
await expectNoValidationErrors(browser, await browser.url())
})
it('valid - no suspense needed around dynamic in page if loading.js is present in a non-layout segment above', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/valid-only-loading-around-dynamic-higher'
)
await expectNoValidationErrors(browser, await browser.url())
})
it('invalid - loading.js covers page, but not layout at the same level', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/invalid-dynamic-layout-with-loading'
) )
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
{ {
"cause": [ "cause": [
{ {
"label": "Caused by: Instant Validation", "label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (4:33) @ unstable_instant "source": "app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (4:33) @ unstable_instant
> 4 | export const unstable_instant = { prefetch: 'static' } > 4 | export const unstable_instant = { prefetch: 'static' }
| ^", | ^",
"stack": [ "stack": [
"unstable_instant app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (4:33)", "unstable_instant app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (4:33)",
"Set.forEach <anonymous>", "Set.forEach <anonymous>",
], ],
}, },
...@@ -792,12 +806,12 @@ describe('instant validation', () => { ...@@ -792,12 +806,12 @@ describe('instant validation', () => {
Learn more: https://nextjs.org/docs/messages/blocking-route", Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Blocking Route", "label": "Blocking Route",
"source": "app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (31:19) @ Dynamic "source": "app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (24:19) @ Dynamic
> 31 | await connection() > 24 | await connection()
| ^", | ^",
"stack": [ "stack": [
"Dynamic app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (31:19)", "Dynamic app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (24:19)",
"Page app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (19:9)", "Layout app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (15:9)",
], ],
} }
`) `)
......
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