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({
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 activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null
const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params
......@@ -779,54 +790,68 @@ export default function OuterLayoutRouter({
const isVirtual = debugName === undefined
const debugNameToDisplay = isVirtual ? undefined : debugNameContext
let child = (
<TemplateContext.Provider
key={stateKey}
value={
<ScrollAndMaybeFocusHandler segmentPath={segmentPath}>
<ErrorBoundary
errorComponent={error}
errorStyles={errorStyles}
errorScripts={errorScripts}
let templateValue = (
<ScrollAndMaybeFocusHandler segmentPath={segmentPath}>
<ErrorBoundary
errorComponent={error}
errorStyles={errorStyles}
errorScripts={errorScripts}
>
<LoadingBoundary
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
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}
>
<RedirectBoundary>
<InnerLayoutRouter
url={url}
tree={tree}
params={params}
cacheNode={cacheNode}
segmentPath={segmentPath}
debugNameContext={childDebugNameContext}
isActive={isActive && stateKey === activeStateKey}
/>
{segmentBoundaryTriggerNode}
</RedirectBoundary>
</HTTPAccessFallbackBoundary>
</LoadingBoundary>
</ErrorBoundary>
{segmentViewStateNode}
</ScrollAndMaybeFocusHandler>
}
>
<RedirectBoundary>
<InnerLayoutRouter
url={url}
tree={tree}
params={params}
cacheNode={cacheNode}
segmentPath={segmentPath}
debugNameContext={childDebugNameContext}
isActive={isActive && stateKey === activeStateKey}
/>
{segmentBoundaryTriggerNode}
</RedirectBoundary>
</HTTPAccessFallbackBoundary>
</LoadingBoundary>
</ErrorBoundary>
{segmentViewStateNode}
</ScrollAndMaybeFocusHandler>
)
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_DEV_SERVER &&
typeof maybeValidationBoundaryId === 'string'
) {
const { RenderValidationBoundaryAtThisLevel } =
require('../../server/app-render/instant-validation/boundary') as typeof import('../../server/app-render/instant-validation/boundary')
templateValue = (
<RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>
{templateValue}
</RenderValidationBoundaryAtThisLevel>
)
}
let child = (
<TemplateContext.Provider key={stateKey} value={templateValue}>
{templateStyles}
{templateScripts}
{template}
......
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
'use client'
import type { ReactNode } from 'react'
import { createContext, type ReactNode } from 'react'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
......@@ -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
// so it retains the name inferred from the namespace object
NameSpace[
......
......@@ -18,7 +18,7 @@ import {
import { getDigestForWellKnownError } from '../create-error-handler'
import {
// NOTE: we're in the server layer, so this is a client reference
InstantValidationBoundary,
PlaceValidationBoundaryBelowThisLevel,
} from './boundary'
import type { ValidationBoundaryTracking } from './boundary-tracking'
import {
......@@ -200,24 +200,6 @@ export async function findNavigationsToValidate(
if (instantConfig === false) {
navigationParents = []
} 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 = {
target: segmentPath,
parents: navigationParents,
......@@ -878,8 +860,7 @@ function createValidationSeedData(
async function createSeedDataFromValidationTreeImpl(
routeTree: RouteTree,
state: TraversalState,
parentState: TraversalState | null
state: TraversalState
) {
const { path, slots } = routeTree
......@@ -965,28 +946,28 @@ function createValidationSeedData(
// 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
// in the new subtree (i.e. it wouldn't block the navigation).
const isValidationBoundary =
state.kind === 'new-tree' &&
parentState &&
parentState.kind === 'shared-tree'
const isInnermostSharedParent =
state.kind === 'shared-tree' && nextState.kind === 'new-tree'
if (isValidationBoundary) {
if (isInnermostSharedParent) {
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
boundaryState.expectedIds.add(boundaryId)
segmentData = {
...segmentData,
node: (
// bundled in the server layer
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<InstantValidationBoundary
// When we wrap the node in a context provider,
// the first OuterLayoutRouter inside it will see it and place a validation boundary.
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer
<PlaceValidationBoundaryBelowThisLevel
id={boundaryId}
key="c" /* matching `cacheNodeKey` */
>
{segmentData.node}
</InstantValidationBoundary>
</PlaceValidationBoundaryBelowThisLevel>
),
}
}
......@@ -997,8 +978,7 @@ function createValidationSeedData(
slotsSeedData[parallelRouteKey] =
await createSeedDataFromValidationTreeImpl(
slots[parallelRouteKey],
nextState,
state
nextState
)
}
}
......@@ -1008,8 +988,7 @@ function createValidationSeedData(
return createSeedDataFromValidationTreeImpl(
rootRouteTree,
// Root layouts are always shared. Navigating to a new root layout is an MPA navigation.
{ kind: 'shared-tree' },
null
{ kind: 'shared-tree' }
)
}
......
......@@ -88,7 +88,13 @@ export default async function Page() {
<DebugLinks href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic" />
</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>
<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() {
return (
<main>
<p>
This page doesn't wrap runtime/dynamic components in suspense, so
despite having a loading.tsx (which is equivalent to a suspense boundary
in a parent layout), it shouldn't pass validation, because a
self-navigation would block.
This page doesn't wrap runtime/dynamic components in suspense, but it
has a loading.tsx above it. a self-navigation with a different search
param value would block, but we accept that.
</p>
<div>
<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', () => {
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(
'/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(`
{
"cause": [
{
"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' }
| ^",
"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>",
],
},
......@@ -792,12 +806,12 @@ describe('instant validation', () => {
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (31:19) @ Dynamic
> 31 | await connection()
"source": "app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (24:19) @ Dynamic
> 24 | await connection()
| ^",
"stack": [
"Dynamic app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (31:19)",
"Page app/suspense-in-root/static/invalid-only-loading-around-dynamic/page.tsx (19:9)",
"Dynamic app/suspense-in-root/static/invalid-dynamic-layout-with-loading/layout.tsx (24:19)",
"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