Unverified Commit 616f6fa0 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[backport][metadata] render streaming metadata on the top level (#80566)

parent 3ab8db73
......@@ -22,27 +22,16 @@ function findHeadInCacheImpl(
// First try the 'children' parallel route if it exists
// when starting from the "root", this corresponds with the main page component
if (parallelRoutes.children) {
const [segment, childParallelRoutes] = parallelRoutes.children
const childSegmentMap = cache.parallelRoutes.get('children')
if (childSegmentMap) {
const cacheKey = createRouterCacheKey(segment)
const cacheNode = childSegmentMap.get(cacheKey)
if (cacheNode) {
const item = findHeadInCacheImpl(
cacheNode,
childParallelRoutes,
keyPrefix + '/' + cacheKey
)
if (item) return item
}
}
}
const parallelRoutesKeys = Object.keys(parallelRoutes).filter(
(key) => key !== 'children'
)
// if we didn't find metadata in the page slot, check the other parallel routes
for (const key in parallelRoutes) {
if (key === 'children') continue // already checked above
// if we are at the root, we need to check the children slot first
if ('children' in parallelRoutes) {
parallelRoutesKeys.unshift('children')
}
for (const key of parallelRoutesKeys) {
const [segment, childParallelRoutes] = parallelRoutes[key]
const childSegmentMap = cache.parallelRoutes.get(key)
if (!childSegmentMap) {
......
......@@ -206,9 +206,11 @@ export function createMetadataComponents({
const promise = resolveFinalMetadata()
if (serveStreamingMetadata) {
return (
<Suspense fallback={null}>
<AsyncMetadata promise={promise} />
</Suspense>
<div hidden>
<Suspense fallback={null}>
<AsyncMetadata promise={promise} />
</Suspense>
</div>
)
}
const metadataState = await promise
......
......@@ -242,6 +242,8 @@ interface ParseRequestHeadersOptions {
}
const flightDataPathHeadKey = 'h'
const getFlightViewportKey = (requestId: string) => requestId + 'v'
const getFlightMetadataKey = (requestId: string) => requestId + 'm'
interface ParsedRequestHeaders {
/**
......@@ -333,30 +335,6 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
]
}
function createDivergedMetadataComponents(
Metadata: React.ComponentType,
serveStreamingMetadata: boolean
): {
StaticMetadata: React.ComponentType<{}>
StreamingMetadata: React.ComponentType<{}> | null
} {
function EmptyMetadata() {
return null
}
const StreamingMetadata: React.ComponentType | null = serveStreamingMetadata
? Metadata
: null
const StaticMetadata: React.ComponentType<{}> = serveStreamingMetadata
? EmptyMetadata
: Metadata
return {
StaticMetadata,
StreamingMetadata,
}
}
/**
* Returns a function that parses the dynamic segment and return the associated value.
*/
......@@ -524,14 +502,6 @@ async function generateDynamicRSCPayload(
serveStreamingMetadata,
})
const { StreamingMetadata, StaticMetadata } =
createDivergedMetadataComponents(() => {
return (
// Adding requestId as react key to make metadata remount for each render
<MetadataTree key={requestId} />
)
}, serveStreamingMetadata)
flightData = (
await walkTreeWithFlightRouterState({
ctx,
......@@ -548,9 +518,9 @@ async function generateDynamicRSCPayload(
isPossibleServerAction={ctx.isPossibleServerAction}
/>
{/* Adding requestId as react key to make metadata remount for each render */}
<ViewportTree key={requestId} />
{StreamingMetadata ? <StreamingMetadata /> : null}
<StaticMetadata />
<ViewportTree key={getFlightViewportKey(requestId)} />
{/* Not add requestId as react key to ensure segment prefetch could result consistently if nothing changed */}
<MetadataTree key={getFlightMetadataKey(requestId)} />
</React.Fragment>
),
injectedCSS: new Set(),
......@@ -854,14 +824,6 @@ async function getRSCPayload(
const preloadCallbacks: PreloadCallbacks = []
const { StreamingMetadata, StaticMetadata } =
createDivergedMetadataComponents(() => {
return (
// Not add requestId as react key to ensure segment prefetch could result consistently if nothing changed
<MetadataTree />
)
}, serveStreamingMetadata)
const seedData = await createComponentTree({
ctx,
loaderTree: tree,
......@@ -875,7 +837,6 @@ async function getRSCPayload(
missingSlots,
preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
StreamingMetadata,
StreamingMetadataOutlet,
})
......@@ -893,8 +854,9 @@ async function getRSCPayload(
statusCode={ctx.res.statusCode}
isPossibleServerAction={ctx.isPossibleServerAction}
/>
<ViewportTree key={ctx.requestId} />
<StaticMetadata />
<ViewportTree key={getFlightViewportKey(ctx.requestId)} />
{/* Not add requestId as react key to ensure segment prefetch could result consistently if nothing changed */}
<MetadataTree />
</React.Fragment>
)
......@@ -981,16 +943,8 @@ async function getErrorRSCPayload(
serveStreamingMetadata: serveStreamingMetadata,
})
const { StreamingMetadata, StaticMetadata } =
createDivergedMetadataComponents(
() => (
<React.Fragment key={flightDataPathHeadKey}>
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={requestId} />
</React.Fragment>
),
serveStreamingMetadata
)
// {/* Adding requestId as react key to make metadata remount for each render */}
const metadata = <MetadataTree key={getFlightMetadataKey(requestId)} />
const initialHead = (
<React.Fragment key={flightDataPathHeadKey}>
......@@ -1000,12 +954,11 @@ async function getErrorRSCPayload(
isPossibleServerAction={ctx.isPossibleServerAction}
/>
{/* Adding requestId as react key to make metadata remount for each render */}
<ViewportTree key={requestId} />
<ViewportTree key={getFlightViewportKey(requestId)} />
{process.env.NODE_ENV === 'development' && (
<meta name="next-error" content="not-found" />
)}
{StreamingMetadata ? <StreamingMetadata /> : null}
<StaticMetadata />
{metadata}
</React.Fragment>
)
......@@ -1025,10 +978,7 @@ async function getErrorRSCPayload(
const seedData: CacheNodeSeedData = [
initialTree[0],
<html id="__next_error__">
<head>
{StreamingMetadata ? <StreamingMetadata /> : null}
<StaticMetadata />
</head>
<head>{metadata}</head>
<body>
{process.env.NODE_ENV !== 'production' && err ? (
<template
......
......@@ -39,7 +39,6 @@ export function createComponentTree(props: {
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
StreamingMetadata: React.ComponentType | null
StreamingMetadataOutlet: React.ComponentType
}): Promise<CacheNodeSeedData> {
return getTracer().trace(
......@@ -76,7 +75,6 @@ async function createComponentTreeInternal({
missingSlots,
preloadCallbacks,
authInterrupts,
StreamingMetadata,
StreamingMetadataOutlet,
}: {
loaderTree: LoaderTree
......@@ -91,7 +89,6 @@ async function createComponentTreeInternal({
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
StreamingMetadata: React.ComponentType | null
StreamingMetadataOutlet: React.ComponentType | null
}): Promise<CacheNodeSeedData> {
const {
......@@ -388,7 +385,6 @@ async function createComponentTreeInternal({
// Resolve the segment param
const actualSegment = segmentParam ? segmentParam.treeSegment : segment
const metadata = StreamingMetadata ? <StreamingMetadata /> : undefined
// Use the same condition to render metadataOutlet as metadata
const metadataOutlet = StreamingMetadataOutlet ? (
......@@ -511,7 +507,6 @@ async function createComponentTreeInternal({
missingSlots,
preloadCallbacks,
authInterrupts,
StreamingMetadata: isChildrenRouteKey ? StreamingMetadata : null,
// `StreamingMetadataOutlet` is used to conditionally throw. In the case of parallel routes we will have more than one page
// but we only want to throw on the first one.
StreamingMetadataOutlet: isChildrenRouteKey
......@@ -694,12 +689,6 @@ async function createComponentTreeInternal({
actualSegment,
<React.Fragment key={cacheNodeKey}>
{pageElement}
{/*
* The order here matters since a parent might call findDOMNode().
* findDOMNode() will return the first child if multiple children are rendered.
* But React will hoist metadata into <head> which breaks scroll handling.
*/}
{metadata}
{layerAssets}
<OutletBoundary>
<MetadataOutlet ready={getViewportReady} />
......
......@@ -202,7 +202,6 @@ export async function walkTreeWithFlightRouterState({
getMetadataReady,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
StreamingMetadata: null,
StreamingMetadataOutlet,
}
)
......
......@@ -6,8 +6,8 @@ import World3 from 'app-cjs-esm-package/entry'
export default function Index() {
return (
<div>
<p>
Hello {World1}+{World2}+{World3}
</div>
</p>
)
}
......@@ -4,8 +4,8 @@ import World3 from 'app-cjs-esm-package/entry'
export default function Page() {
return (
<div>
<p>
Hello {World1}+{World2}+{World3}
</div>
</p>
)
}
......@@ -28,15 +28,13 @@ describe('esm-externals', () => {
it('should return the correct SSR HTML', async () => {
const $ = await next.render$(url)
const body = $('body > div > div').html()
const body = $('body p').html()
expect(normalize(body)).toEqual(expectedHtml)
})
it('should render the correct page', async () => {
const browser = await next.browser(url)
expect(await browser.elementByCss('body > div').text()).toEqual(
expectedText
)
expect(await browser.elementByCss('body p').text()).toEqual(expectedText)
})
})
......@@ -54,13 +52,13 @@ describe('esm-externals', () => {
it('should return the correct SSR HTML', async () => {
const $ = await next.render$(url)
const body = $('body > div').html()
const body = $('body > p').html()
expect(normalize(body)).toEqual(expectedHtml)
})
it('should render the correct page', async () => {
const browser = await next.browser(url)
expect(await browser.elementByCss('body > div').text()).toEqual(
expect(await browser.elementByCss('body > p').text()).toEqual(
expectedText
)
})
......
......@@ -13,8 +13,8 @@ export async function getStaticProps() {
export default function Index({ worlds }) {
return (
<div>
<p>
Hello {World1}+{World2}+{World3}+{worlds}
</div>
</p>
)
}
......@@ -13,8 +13,8 @@ export function getServerSideProps() {
export default function Index({ worlds }) {
return (
<div>
<p>
Hello {World1}+{World2}+{World3}+{worlds}
</div>
</p>
)
}
......@@ -7,8 +7,8 @@ const worlds = 'World+World+World'
export default function Index() {
return (
<div>
<p>
Hello {World1}+{World2}+{World3}+{worlds}
</div>
</p>
)
}
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