Unverified Commit 90fbbf3a authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[metadata] Move metadata rendering adjacent to page component (#74262)

parent fca73585
...@@ -700,8 +700,10 @@ function createPendingCacheNode( ...@@ -700,8 +700,10 @@ function createPendingCacheNode(
rsc: createDeferredRsc() as React.ReactNode, rsc: createDeferredRsc() as React.ReactNode,
head: isLeafSegment head: isLeafSegment
? [ ? [
// TODO: change head back to ReactNode when metadata
// is stably rendered in body
createDeferredRsc() as React.ReactNode, createDeferredRsc() as React.ReactNode,
createDeferredRsc() as React.ReactNode, null,
] ]
: [null, null], : [null, null],
} }
...@@ -805,13 +807,12 @@ function finishPendingCacheNode( ...@@ -805,13 +807,12 @@ function finishPendingCacheNode(
// a pending promise that needs to be resolved with the dynamic head from // a pending promise that needs to be resolved with the dynamic head from
// the server. // the server.
const head = cacheNode.head const head = cacheNode.head
// Handle head[0] - viewport and head[1] - metadata // TODO: change head back to ReactNode when metadata
// is stably rendered in body
// Handle head[0] - viewport
if (isDeferredRsc(head[0])) { if (isDeferredRsc(head[0])) {
head[0].resolve(dynamicHead[0]) head[0].resolve(dynamicHead[0])
} }
if (isDeferredRsc(head[1])) {
head[1].resolve(dynamicHead[1])
}
} }
export function abortTask(task: Task, error: any): void { export function abortTask(task: Task, error: any): void {
......
...@@ -31,6 +31,7 @@ function resolveViewportLayout(viewport: Viewport) { ...@@ -31,6 +31,7 @@ function resolveViewportLayout(viewport: Viewport) {
export function ViewportMeta({ viewport }: { viewport: ResolvedViewport }) { export function ViewportMeta({ viewport }: { viewport: ResolvedViewport }) {
return MetaFilter([ return MetaFilter([
<meta charSet="utf-8" />,
Meta({ name: 'viewport', content: resolveViewportLayout(viewport) }), Meta({ name: 'viewport', content: resolveViewportLayout(viewport) }),
...(viewport.themeColor ...(viewport.themeColor
? viewport.themeColor.map((themeColor) => ? viewport.themeColor.map((themeColor) =>
...@@ -51,7 +52,6 @@ export function BasicMeta({ metadata }: { metadata: ResolvedMetadata }) { ...@@ -51,7 +52,6 @@ export function BasicMeta({ metadata }: { metadata: ResolvedMetadata }) {
: undefined : undefined
return MetaFilter([ return MetaFilter([
<meta charSet="utf-8" />,
metadata.title !== null && metadata.title.absolute ? ( metadata.title !== null && metadata.title.absolute ? (
<title>{metadata.title.absolute}</title> <title>{metadata.title.absolute}</title>
) : null, ) : null,
......
...@@ -467,6 +467,16 @@ async function generateDynamicRSCPayload( ...@@ -467,6 +467,16 @@ async function generateDynamicRSCPayload(
MetadataBoundary, MetadataBoundary,
ViewportBoundary, ViewportBoundary,
}) })
const MetadataComponent = () => {
return (
<React.Fragment key={flightDataPathMetadataKey}>
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={requestId} />
</React.Fragment>
)
}
flightData = ( flightData = (
await walkTreeWithFlightRouterState({ await walkTreeWithFlightRouterState({
ctx, ctx,
...@@ -481,10 +491,7 @@ async function generateDynamicRSCPayload( ...@@ -481,10 +491,7 @@ async function generateDynamicRSCPayload(
{/* Adding requestId as react key to make metadata remount for each render */} {/* Adding requestId as react key to make metadata remount for each render */}
<ViewportTree key={requestId} /> <ViewportTree key={requestId} />
</React.Fragment>, </React.Fragment>,
<React.Fragment key={flightDataPathMetadataKey}> null,
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={requestId} />
</React.Fragment>,
], ],
injectedCSS: new Set(), injectedCSS: new Set(),
injectedJS: new Set(), injectedJS: new Set(),
...@@ -493,6 +500,7 @@ async function generateDynamicRSCPayload( ...@@ -493,6 +500,7 @@ async function generateDynamicRSCPayload(
getViewportReady, getViewportReady,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
MetadataComponent,
}) })
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
} }
...@@ -766,6 +774,15 @@ async function getRSCPayload( ...@@ -766,6 +774,15 @@ async function getRSCPayload(
const preloadCallbacks: PreloadCallbacks = [] const preloadCallbacks: PreloadCallbacks = []
function MetadataComponent() {
return (
<React.Fragment key={flightDataPathMetadataKey}>
{/* Not add requestId as react key to ensure segment prefetch could result consistently if nothing changed */}
<MetadataTree />
</React.Fragment>
)
}
const seedData = await createComponentTree({ const seedData = await createComponentTree({
ctx, ctx,
loaderTree: tree, loaderTree: tree,
...@@ -779,6 +796,7 @@ async function getRSCPayload( ...@@ -779,6 +796,7 @@ async function getRSCPayload(
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts, authInterrupts: ctx.renderOpts.experimental.authInterrupts,
MetadataComponent,
}) })
// When the `vary` response header is present with `Next-URL`, that means there's a chance // When the `vary` response header is present with `Next-URL`, that means there's a chance
...@@ -788,13 +806,6 @@ async function getRSCPayload( ...@@ -788,13 +806,6 @@ async function getRSCPayload(
const couldBeIntercepted = const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL) typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL)
const initialHeadMetadata = (
<React.Fragment key={flightDataPathMetadataKey}>
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={ctx.requestId} />
</React.Fragment>
)
const initialHeadViewport = ( const initialHeadViewport = (
<React.Fragment key={flightDataPathViewportKey}> <React.Fragment key={flightDataPathViewportKey}>
<NonIndex ctx={ctx} /> <NonIndex ctx={ctx} />
...@@ -825,7 +836,7 @@ async function getRSCPayload( ...@@ -825,7 +836,7 @@ async function getRSCPayload(
[ [
initialTree, initialTree,
seedData, seedData,
[initialHeadViewport, initialHeadMetadata], [initialHeadViewport, null],
isPossiblyPartialHead, isPossiblyPartialHead,
] as FlightDataPath, ] as FlightDataPath,
], ],
...@@ -892,6 +903,7 @@ async function getErrorRSCPayload( ...@@ -892,6 +903,7 @@ async function getErrorRSCPayload(
<MetadataTree key={requestId} /> <MetadataTree key={requestId} />
</React.Fragment> </React.Fragment>
) )
const initialHeadViewport = ( const initialHeadViewport = (
<React.Fragment key={flightDataPathViewportKey}> <React.Fragment key={flightDataPathViewportKey}>
<NonIndex ctx={ctx} /> <NonIndex ctx={ctx} />
...@@ -911,11 +923,11 @@ async function getErrorRSCPayload( ...@@ -911,11 +923,11 @@ async function getErrorRSCPayload(
// For metadata notFound error there's no global not found boundary on top // For metadata notFound error there's no global not found boundary on top
// so we create a not found page with AppRouter // so we create a not found page with AppRouter
const initialSeedData: CacheNodeSeedData = [ const seedData: CacheNodeSeedData = [
initialTree[0], initialTree[0],
<html id="__next_error__"> <html id="__next_error__">
<head></head> <head>{initialHeadMetadata}</head>
<body></body> <body />
</html>, </html>,
{}, {},
null, null,
...@@ -937,8 +949,8 @@ async function getErrorRSCPayload( ...@@ -937,8 +949,8 @@ async function getErrorRSCPayload(
f: [ f: [
[ [
initialTree, initialTree,
initialSeedData, seedData,
[initialHeadViewport, initialHeadMetadata], [initialHeadViewport, null],
isPossiblyPartialHead, isPossiblyPartialHead,
] as FlightDataPath, ] as FlightDataPath,
], ],
......
...@@ -18,6 +18,7 @@ import type { LoadingModuleData } from '../../shared/lib/app-router-context.shar ...@@ -18,6 +18,7 @@ import type { LoadingModuleData } from '../../shared/lib/app-router-context.shar
import type { Params } from '../request/params' import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external' import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { OUTLET_BOUNDARY_NAME } from '../../lib/metadata/metadata-constants' import { OUTLET_BOUNDARY_NAME } from '../../lib/metadata/metadata-constants'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
/** /**
* Use the provided loader tree to create the React Component tree. * Use the provided loader tree to create the React Component tree.
...@@ -35,6 +36,7 @@ export function createComponentTree(props: { ...@@ -35,6 +36,7 @@ export function createComponentTree(props: {
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean authInterrupts: boolean
MetadataComponent: React.ComponentType<{}>
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
return getTracer().trace( return getTracer().trace(
NextNodeServerSpan.createComponentTree, NextNodeServerSpan.createComponentTree,
...@@ -70,6 +72,7 @@ async function createComponentTreeInternal({ ...@@ -70,6 +72,7 @@ async function createComponentTreeInternal({
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts, authInterrupts,
MetadataComponent,
}: { }: {
loaderTree: LoaderTree loaderTree: LoaderTree
parentParams: Params parentParams: Params
...@@ -83,6 +86,7 @@ async function createComponentTreeInternal({ ...@@ -83,6 +86,7 @@ async function createComponentTreeInternal({
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean authInterrupts: boolean
MetadataComponent: React.ComponentType<{}>
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
const { const {
renderOpts: { nextConfigOutput, experimental }, renderOpts: { nextConfigOutput, experimental },
...@@ -221,27 +225,6 @@ async function createComponentTreeInternal({ ...@@ -221,27 +225,6 @@ async function createComponentTreeInternal({
}) })
: [] : []
const notFoundElement = NotFound ? (
<>
{notFoundStyles}
<NotFound />
</>
) : undefined
const forbiddenElement = Forbidden ? (
<>
{forbiddenStyles}
<Forbidden />
</>
) : undefined
const unauthorizedElement = Unauthorized ? (
<>
{unauthorizedStyles}
<Unauthorized />
</>
) : undefined
let dynamic = layoutOrPageMod?.dynamic let dynamic = layoutOrPageMod?.dynamic
if (nextConfigOutput === 'export') { if (nextConfigOutput === 'export') {
...@@ -409,7 +392,35 @@ async function createComponentTreeInternal({ ...@@ -409,7 +392,35 @@ async function createComponentTreeInternal({
workStore.rootParams = currentParams workStore.rootParams = currentParams
} }
// // Only render metadata on the actual SSR'd segment not the `default` segment,
// as it's used as a placeholder for navigation.
const metadata =
actualSegment !== DEFAULT_SEGMENT_KEY ? <MetadataComponent /> : undefined
const notFoundElement = NotFound ? (
<>
{metadata}
{notFoundStyles}
<NotFound />
</>
) : undefined
const forbiddenElement = Forbidden ? (
<>
{metadata}
{forbiddenStyles}
<Forbidden />
</>
) : undefined
const unauthorizedElement = Unauthorized ? (
<>
{metadata}
{unauthorizedStyles}
<Unauthorized />
</>
) : undefined
// TODO: Combine this `map` traversal with the loop below that turns the array // TODO: Combine this `map` traversal with the loop below that turns the array
// into an object. // into an object.
const parallelRouteMap = await Promise.all( const parallelRouteMap = await Promise.all(
...@@ -504,7 +515,8 @@ async function createComponentTreeInternal({ ...@@ -504,7 +515,8 @@ async function createComponentTreeInternal({
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
authInterrupts: authInterrupts, authInterrupts,
MetadataComponent,
}) })
childCacheNodeSeedData = seedData childCacheNodeSeedData = seedData
...@@ -657,6 +669,7 @@ async function createComponentTreeInternal({ ...@@ -657,6 +669,7 @@ async function createComponentTreeInternal({
return [ return [
actualSegment, actualSegment,
<React.Fragment key={cacheNodeKey}> <React.Fragment key={cacheNodeKey}>
{metadata}
{pageElement} {pageElement}
{layerAssets} {layerAssets}
<OutletBoundary> <OutletBoundary>
...@@ -792,6 +805,7 @@ async function createComponentTreeInternal({ ...@@ -792,6 +805,7 @@ async function createComponentTreeInternal({
notFound={ notFound={
NotFound ? ( NotFound ? (
<> <>
{metadata}
{layerAssets} {layerAssets}
<SegmentComponent params={params}> <SegmentComponent params={params}>
{notFoundStyles} {notFoundStyles}
......
...@@ -40,6 +40,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -40,6 +40,7 @@ export async function walkTreeWithFlightRouterState({
getMetadataReady, getMetadataReady,
ctx, ctx,
preloadCallbacks, preloadCallbacks,
MetadataComponent,
}: { }: {
loaderTreeToFilter: LoaderTree loaderTreeToFilter: LoaderTree
parentParams: { [key: string]: string | string[] } parentParams: { [key: string]: string | string[] }
...@@ -54,6 +55,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -54,6 +55,7 @@ export async function walkTreeWithFlightRouterState({
getViewportReady: () => Promise<void> getViewportReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
MetadataComponent: React.ComponentType<{}>
}): Promise<FlightDataPath[]> { }): Promise<FlightDataPath[]> {
const { const {
renderOpts: { nextFontManifest, experimental }, renderOpts: { nextFontManifest, experimental },
...@@ -202,6 +204,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -202,6 +204,7 @@ export async function walkTreeWithFlightRouterState({
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
authInterrupts: experimental.authInterrupts, authInterrupts: experimental.authInterrupts,
MetadataComponent,
} }
) )
...@@ -261,6 +264,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -261,6 +264,7 @@ export async function walkTreeWithFlightRouterState({
getViewportReady, getViewportReady,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
MetadataComponent,
}) })
for (const subPath of subPaths) { for (const subPath of subPaths) {
......
...@@ -439,6 +439,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -439,6 +439,7 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}>
<__next_metadata_boundary__>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}> <Page params={Promise} searchParams={Promise}>
> <table> > <table>
...@@ -894,6 +895,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -894,6 +895,7 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}>
<__next_metadata_boundary__>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}> <Page params={Promise} searchParams={Promise}>
<div> <div>
...@@ -914,6 +916,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -914,6 +916,7 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}>
<__next_metadata_boundary__>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}> <Page params={Promise} searchParams={Promise}>
<div> <div>
......
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