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