Unverified Commit ceef7194 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix missing stylesheets when parallel routes are present (#66300)

This takes the `layerAssets` property from the previous PR and actually
renders it, replacing the previous style handling. This ensures that
when multiple page segments are rendered on screen, all of their
associated CSS files are loaded. The existing `findHeadInCache` method
only ever returns a single head node, which means it’d miss stylesheets.


Fixes #59308
Fixes #63465
parent 786a7035
...@@ -293,6 +293,7 @@ function Head({ ...@@ -293,6 +293,7 @@ function Head({
function Router({ function Router({
buildId, buildId,
initialHead, initialHead,
initialLayerAssets,
initialTree, initialTree,
initialCanonicalUrl, initialCanonicalUrl,
initialSeedData, initialSeedData,
...@@ -310,7 +311,7 @@ function Router({ ...@@ -310,7 +311,7 @@ function Router({
initialParallelRoutes, initialParallelRoutes,
location: !isServer ? window.location : null, location: !isServer ? window.location : null,
initialHead, initialHead,
initialLayerAssets: null, initialLayerAssets,
couldBeIntercepted, couldBeIntercepted,
}), }),
[ [
...@@ -319,6 +320,7 @@ function Router({ ...@@ -319,6 +320,7 @@ function Router({
initialCanonicalUrl, initialCanonicalUrl,
initialTree, initialTree,
initialHead, initialHead,
initialLayerAssets,
couldBeIntercepted, couldBeIntercepted,
] ]
) )
...@@ -657,10 +659,27 @@ function Router({ ...@@ -657,10 +659,27 @@ function Router({
head = null head = null
} }
// We use `useDeferredValue` to handle switching between the prefetched and
// final values. The second argument is returned on initial render, then it
// re-renders with the first argument. We only use the prefetched layer assets
// if they are available. Otherwise, we use the non-prefetched version.
const resolvedPrefetchLayerAssets =
cache.prefetchLayerAssets !== null
? cache.prefetchLayerAssets
: cache.layerAssets
const layerAssets = useDeferredValue(
cache.layerAssets,
// @ts-expect-error The second argument to `useDeferredValue` is only
// available in the experimental builds. When its disabled, it will always
// return `cache.layerAssets`.
resolvedPrefetchLayerAssets
)
let content = ( let content = (
<RedirectBoundary> <RedirectBoundary>
{head} {head}
{/* {cache.layerAssets} */} {layerAssets}
{cache.rsc} {cache.rsc}
<AppRouterAnnouncer tree={tree} /> <AppRouterAnnouncer tree={tree} />
</RedirectBoundary> </RedirectBoundary>
......
...@@ -456,6 +456,23 @@ function InnerLayoutRouter({ ...@@ -456,6 +456,23 @@ function InnerLayoutRouter({
} }
} }
// We use `useDeferredValue` to handle switching between the prefetched and
// final values. The second argument is returned on initial render, then it
// re-renders with the first argument. We only use the prefetched layer assets
// if they are available. Otherwise, we use the non-prefetched version.
const resolvedPrefetchLayerAssets =
childNode.prefetchLayerAssets !== null
? childNode.prefetchLayerAssets
: childNode.layerAssets
const layerAssets = useDeferredValue(
childNode.layerAssets,
// @ts-expect-error The second argument to `useDeferredValue` is only
// available in the experimental builds. When its disabled, it will always
// return `cache.layerAssets`.
resolvedPrefetchLayerAssets
)
// If we get to this point, then we know we have something we can render. // If we get to this point, then we know we have something we can render.
const subtree = ( const subtree = (
// The layout router context narrows down tree and childNodes at each level. // The layout router context narrows down tree and childNodes at each level.
...@@ -468,7 +485,7 @@ function InnerLayoutRouter({ ...@@ -468,7 +485,7 @@ function InnerLayoutRouter({
loading: childNode.loading, loading: childNode.loading,
}} }}
> >
{/* {childNode.layerAssets} */} {layerAssets}
{resolvedRsc} {resolvedRsc}
</LayoutRouterContext.Provider> </LayoutRouterContext.Provider>
) )
......
...@@ -482,34 +482,31 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) { ...@@ -482,34 +482,31 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) {
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL) typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL)
return ( return (
<> <AppRouter
{styles} buildId={ctx.renderOpts.buildId}
<AppRouter assetPrefix={ctx.assetPrefix}
buildId={ctx.renderOpts.buildId} initialCanonicalUrl={urlPathname}
assetPrefix={ctx.assetPrefix} // This is the router state tree.
initialCanonicalUrl={urlPathname} initialTree={initialTree}
// This is the router state tree. // This is the tree of React nodes that are seeded into the cache
initialTree={initialTree} initialSeedData={seedData}
// This is the tree of React nodes that are seeded into the cache couldBeIntercepted={couldBeIntercepted}
initialSeedData={seedData} initialHead={
couldBeIntercepted={couldBeIntercepted} <>
initialHead={ {typeof ctx.res.statusCode === 'number' &&
<> ctx.res.statusCode > 400 && (
{typeof ctx.res.statusCode === 'number' && <meta name="robots" content="noindex" />
ctx.res.statusCode > 400 && ( )}
<meta name="robots" content="noindex" /> {/* Adding requestId as react key to make metadata remount for each render */}
)} <MetadataTree key={ctx.requestId} />
{/* Adding requestId as react key to make metadata remount for each render */} </>
<MetadataTree key={ctx.requestId} /> }
</> initialLayerAssets={styles}
} globalErrorComponent={GlobalError}
initialLayerAssets={null} // This is used to provide debug information (when in development mode)
globalErrorComponent={GlobalError} // about which slots were not filled by page components while creating the component tree.
// This is used to provide debug information (when in development mode) missingSlots={missingSlots}
// about which slots were not filled by page components while creating the component tree. />
missingSlots={missingSlots}
/>
</>
) )
} }
......
...@@ -604,40 +604,38 @@ describe('Error overlay for hydration errors', () => { ...@@ -604,40 +604,38 @@ describe('Error overlay for hydration errors', () => {
if (isTurbopack) { if (isTurbopack) {
expect(fullPseudoHtml).toMatchInlineSnapshot(` expect(fullPseudoHtml).toMatchInlineSnapshot(`
"... "...
<NotFoundErrorBoundary pathname="/" notFound={[...]} notFoundStyles={[...]} asNotFound={undefined} missingSlots={Set}> <RedirectBoundary>
<RedirectBoundary> <RedirectErrorBoundary router={{...}}>
<RedirectErrorBoundary router={{...}}> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...> <ClientPageRoot props={{params:{}, ...}} Component={function Page}>
<ClientPageRoot props={{params:{}, ...}} Component={function Page}> <Page params={{}} searchParams={{}}>
<Page params={{}} searchParams={{}}> <div>
<div> <div>
<div> <div>
<div> <div>
<div> <Mismatch>
<Mismatch> <p>
<p> <span>
<span> + client
+ client - server"
- server"
`) `)
} else { } else {
expect(fullPseudoHtml).toMatchInlineSnapshot(` expect(fullPseudoHtml).toMatchInlineSnapshot(`
"... "...
<NotFoundErrorBoundary pathname="/" notFound={[...]} notFoundStyles={[...]} asNotFound={undefined} missingSlots={Set}> <RedirectBoundary>
<RedirectBoundary> <RedirectErrorBoundary router={{...}}>
<RedirectErrorBoundary router={{...}}> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...> <ClientPageRoot props={{params:{}, ...}} Component={function Page}>
<ClientPageRoot props={{params:{}, ...}} Component={function Page}> <Page params={{}} searchParams={{}}>
<Page params={{}} searchParams={{}}> <div>
<div> <div>
<div> <div>
<div> <div>
<div> <Mismatch>
<Mismatch> <p>
<p> <span>
<span> + client
+ client - server"
- server"
`) `)
} }
......
import styles from './style.module.css'
export default function Page() {
return (
<div className={styles.bgRed} id="slot">
Slot
</div>
)
}
export default function Page() {
return null
}
import { ReactNode } from 'react'
const RootLayout = ({
children,
foo,
}: {
children: ReactNode
foo: ReactNode
}) => {
return (
<html lang="en">
<body>
{children}
{foo}
</body>
</html>
)
}
export default RootLayout
import Link from 'next/link'
export const metadata = {
title: 'Nested Page',
}
export default function Page() {
return (
<div className="sub">
<p>Sub</p>
<Link href="/">Home</Link>
</div>
)
}
import Link from 'next/link'
import styles from './style.module.css'
export const metadata = {
title: 'Home Page',
}
export default function Home() {
return (
<main id="main" className={styles.bgBlue}>
<p>Main</p>
<Link href="/nested">Nested Page</Link>
</main>
)
}
import { nextTestSetup } from 'e2e-utils'
import type { BrowserInterface } from 'next-webdriver'
describe('parallel-routes-catchall-css', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function getChildrenBackgroundColor(browser: BrowserInterface) {
return browser.eval(
`window.getComputedStyle(document.getElementById('main')).backgroundColor`
)
}
async function getSlotBackgroundColor(browser: BrowserInterface) {
return browser.eval(
`window.getComputedStyle(document.getElementById('slot')).backgroundColor`
)
}
it('should properly load the Head content from multiple leaf segments', async () => {
const browser = await next.browser('/')
// the page background should be blue
expect(await getChildrenBackgroundColor(browser)).toBe('rgb(0, 0, 255)')
expect(await browser.elementByCss('title').text()).toBe('Home Page')
expect(await browser.elementsByCss('title')).toHaveLength(1)
// navigate to the page that matches a parallel route
await browser.elementByCss("[href='/nested']").click()
await browser.waitForElementByCss('#slot')
// the slot's background color should be red
expect(await getSlotBackgroundColor(browser)).toBe('rgb(255, 0, 0)')
// there should no longer be a main element
expect(await browser.hasElementByCssSelector('#main')).toBeFalsy()
// the slot background should still be red on a fresh load
await browser.refresh()
expect(await getSlotBackgroundColor(browser)).toBe('rgb(255, 0, 0)')
// when we navigate from the route that matched the catch-all, we should see the CSS for the main element
await browser.elementByCss("[href='/']").click()
await browser.waitForElementByCss('#main')
expect(await getChildrenBackgroundColor(browser)).toBe('rgb(0, 0, 255)')
})
})
...@@ -2415,6 +2415,15 @@ ...@@ -2415,6 +2415,15 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/parallel-routes-css/parallel-routes-css.test.ts": {
"passed": [],
"failed": [
"parallel-routes-catchall-css should properly load the Head content from multiple leaf segments"
],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/parallel-routes-layouts/parallel-routes-layouts.test.ts": { "test/e2e/app-dir/parallel-routes-layouts/parallel-routes-layouts.test.ts": {
"passed": [ "passed": [
"parallel-routes-layouts should properly render layouts for multiple slots" "parallel-routes-layouts should properly render layouts for multiple slots"
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