Unverified Commit 73cfb966 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Separate viewport and metadata in rsc and cache (#73867)

parent 2a791d1b
......@@ -145,7 +145,7 @@ export function createEmptyCacheNode(): CacheNode {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......
......@@ -549,7 +549,7 @@ export default function OuterLayoutRouter({
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......
......@@ -172,7 +172,7 @@ function fillNewTreeWithOnlyLoadingSegments(
// copy the layout but null the page segment as that's not meant to be used
rsc: segmentForParallelRoute.includes(PAGE_SEGMENT_KEY) ? null : rsc,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading,
......@@ -184,7 +184,7 @@ function fillNewTreeWithOnlyLoadingSegments(
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......
......@@ -16,7 +16,7 @@ describe('clearCacheNodeDataForSegmentPath', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......@@ -25,7 +25,7 @@ describe('clearCacheNodeDataForSegmentPath', () => {
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -38,7 +38,7 @@ describe('clearCacheNodeDataForSegmentPath', () => {
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -51,7 +51,7 @@ describe('clearCacheNodeDataForSegmentPath', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......@@ -70,52 +70,64 @@ describe('clearCacheNodeDataForSegmentPath', () => {
clearCacheNodeDataForSegmentPath(cache, existingCache, flightSegmentPath)
expect(cache).toMatchInlineSnapshot(`
{
"head": null,
"lazyData": null,
"loading": null,
"parallelRoutes": Map {
"children" => Map {
"linking" => {
"head": null,
"lazyData": null,
"loading": null,
"parallelRoutes": Map {
"children" => Map {
"" => {
"head": null,
"lazyData": null,
"loading": null,
"parallelRoutes": Map {},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": <React.Fragment>
Page
</React.Fragment>,
},
},
},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": <React.Fragment>
Linking
</React.Fragment>,
},
"dashboard" => {
"head": null,
"lazyData": null,
"loading": null,
"parallelRoutes": Map {},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": null,
},
},
},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": null,
}
{
"head": [
null,
null,
],
"lazyData": null,
"loading": null,
"parallelRoutes": Map {
"children" => Map {
"linking" => {
"head": [
null,
null,
],
"lazyData": null,
"loading": null,
"parallelRoutes": Map {
"children" => Map {
"" => {
"head": [
null,
null,
],
"lazyData": null,
"loading": null,
"parallelRoutes": Map {},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": <React.Fragment>
Page
</React.Fragment>,
},
},
},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": <React.Fragment>
Linking
</React.Fragment>,
},
"dashboard" => {
"head": [
null,
null,
],
"lazyData": null,
"loading": null,
"parallelRoutes": Map {},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": null,
},
},
},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": null,
}
`)
})
})
......@@ -40,7 +40,7 @@ export function clearCacheNodeDataForSegmentPath(
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......@@ -56,7 +56,7 @@ export function clearCacheNodeDataForSegmentPath(
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......
......@@ -59,7 +59,7 @@ describe('createInitialRouterState', () => {
lazyData: null,
rsc: children,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -81,7 +81,7 @@ describe('createInitialRouterState', () => {
prefetchRsc: null,
parallelRoutes: new Map(),
loading: null,
head: <title>Test</title>,
head: [null, <title>Test</title>],
prefetchHead: null,
},
],
......@@ -91,7 +91,7 @@ describe('createInitialRouterState', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
},
......
......@@ -48,7 +48,7 @@ export function createInitialRouterState({
lazyData: null,
rsc,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
// The cache gets seeded during the first render. `initialParallelRoutes` ensures the cache from the first render is there during the second render.
parallelRoutes: isServer ? new Map() : initialParallelRoutes,
......@@ -74,7 +74,8 @@ export function createInitialRouterState({
undefined,
initialTree,
initialSeedData,
initialHead
initialHead,
undefined
)
}
......
import React from 'react'
import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type { NormalizedFlightData } from '../../flight-data-helpers'
......@@ -11,7 +10,7 @@ const getFlightData = (): NormalizedFlightData[] => {
segment: 'about',
tree: ['about', { children: ['', {}] }],
seedData: ['about', <h1>SubTreeData Injected!</h1>, {}, null, false],
head: '<title>Head Injected!</title>',
head: [null, '<title>Head Injected!</title>'],
isHeadPartial: false,
isRootRender: false,
},
......@@ -24,7 +23,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -33,7 +32,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -46,7 +45,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -59,7 +58,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -90,7 +89,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -103,7 +102,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -117,7 +116,7 @@ describe('fillCacheWithNewSubtreeData', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -127,7 +126,7 @@ describe('fillCacheWithNewSubtreeData', () => {
'about',
{
lazyData: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -143,11 +142,12 @@ describe('fillCacheWithNewSubtreeData', () => {
parallelRoutes: new Map(),
prefetchHead: null,
loading: null,
head: (
head: [
null,
<>
<title>Head Injected!</title>
</>
),
</>,
],
},
],
]),
......
......@@ -71,7 +71,7 @@ function fillCacheHelper(
rsc:
fillLazyItems || incomingSegment !== PAGE_SEGMENT_KEY ? rsc : null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading,
parallelRoutes:
......
......@@ -39,7 +39,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......@@ -48,7 +48,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -61,7 +61,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -74,7 +74,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -100,19 +100,21 @@ describe('fillLazyItemsTillLeafWithHead', () => {
const flightDataPath = flightData[0]
const [treePatch, cacheNodeSeedData, head /*, isHeadPartial */] =
flightDataPath.slice(-4)
fillLazyItemsTillLeafWithHead(
cache,
existingCache,
treePatch,
cacheNodeSeedData,
head
head,
undefined
)
const expectedCache: CacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -125,7 +127,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -150,11 +152,12 @@ describe('fillLazyItemsTillLeafWithHead', () => {
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
head: (
head: [
null,
<>
<title>About page!</title>
</>
),
</>,
],
},
],
]),
......@@ -162,7 +165,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
]),
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
},
],
......@@ -172,7 +175,7 @@ describe('fillLazyItemsTillLeafWithHead', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type {
CacheNode,
HeadData,
} from '../../../shared/lib/app-router-context.shared-runtime'
import type {
FlightRouterState,
CacheNodeSeedData,
......@@ -14,8 +17,8 @@ export function fillLazyItemsTillLeafWithHead(
existingCache: CacheNode | undefined,
routerState: FlightRouterState,
cacheNodeSeedData: CacheNodeSeedData | null,
head: React.ReactNode,
prefetchEntry?: PrefetchCacheEntry
head: HeadData,
prefetchEntry: PrefetchCacheEntry | undefined
): void {
const isLastSegment = Object.keys(routerState[1]).length === 0
if (isLastSegment) {
......@@ -66,7 +69,7 @@ export function fillLazyItemsTillLeafWithHead(
// `prefetchRsc`. As an incremental step, we'll just de-opt to the
// old behavior — no PPR value.
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
......@@ -93,7 +96,7 @@ export function fillLazyItemsTillLeafWithHead(
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
loading: null,
......@@ -126,7 +129,7 @@ export function fillLazyItemsTillLeafWithHead(
lazyData: null,
rsc: seedNode,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading,
......@@ -138,7 +141,7 @@ export function fillLazyItemsTillLeafWithHead(
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
......
......@@ -12,7 +12,7 @@ const getFlightData = (): NormalizedFlightData[] => {
segment: 'about',
tree: ['about', { children: ['', {}] }],
seedData: ['about', <h1>About Page!</h1>, {}, null, false],
head: '<title>About page!</title>',
head: [null, '<title>About page!</title>'],
isHeadPartial: false,
isRootRender: false,
},
......@@ -25,7 +25,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -34,7 +34,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -47,7 +47,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -60,7 +60,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -100,7 +100,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
const expectedCache: CacheNode = {
lazyData: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -111,7 +111,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
'linking',
{
lazyData: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -126,7 +126,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
parallelRoutes: new Map(),
rsc: <React.Fragment>Page</React.Fragment>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
},
],
......
import React from 'react'
import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type { FlightRouterState } from '../../../server/app-render/types'
......@@ -9,7 +8,7 @@ describe('invalidateCacheByRouterState', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -18,7 +17,7 @@ describe('invalidateCacheByRouterState', () => {
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -31,7 +30,7 @@ describe('invalidateCacheByRouterState', () => {
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -44,7 +43,7 @@ describe('invalidateCacheByRouterState', () => {
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
......@@ -86,7 +85,7 @@ describe('invalidateCacheByRouterState', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([['children', new Map()]]),
......
......@@ -7,6 +7,7 @@ import type {
import type {
CacheNode,
ChildSegmentMap,
HeadData,
ReadyCacheNode,
} from '../../../shared/lib/app-router-context.shared-runtime'
import { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'
......@@ -70,7 +71,7 @@ export function updateCacheNodeOnNavigation(
oldRouterState: FlightRouterState,
newRouterState: FlightRouterState,
prefetchData: CacheNodeSeedData | null,
prefetchHead: React.ReactNode | null,
prefetchHead: HeadData,
isPrefetchHeadPartial: boolean
): Task | null {
// Diff the old and new trees to reuse the shared layouts.
......@@ -285,7 +286,7 @@ export function updateCacheNodeOnNavigation(
function createCacheNodeOnNavigation(
routerState: FlightRouterState,
prefetchData: CacheNodeSeedData | null,
possiblyPartialPrefetchHead: React.ReactNode | null,
possiblyPartialPrefetchHead: HeadData,
isPrefetchHeadPartial: boolean
): Task {
// Same traversal as updateCacheNodeNavigation, but we switch to this path
......@@ -386,7 +387,7 @@ function createCacheNodeOnNavigation(
// `prefetchRsc` field.
rsc,
prefetchRsc: null,
head: isLeafSegment ? possiblyPartialPrefetchHead : null,
head: isLeafSegment ? possiblyPartialPrefetchHead : [null, null],
prefetchHead: null,
loading,
parallelRoutes: cacheNodeChildren,
......@@ -531,7 +532,7 @@ function writeDynamicDataIntoPendingTask(
segmentPath: FlightSegmentPath,
serverRouterState: FlightRouterState,
dynamicData: CacheNodeSeedData,
dynamicHead: React.ReactNode
dynamicHead: HeadData
) {
// The data sent by the server represents only a subtree of the app. We need
// to find the part of the task tree that matches the server response, and
......@@ -578,7 +579,7 @@ function finishTaskUsingDynamicDataPayload(
task: Task,
serverRouterState: FlightRouterState,
dynamicData: CacheNodeSeedData,
dynamicHead: React.ReactNode
dynamicHead: HeadData
) {
if (task.dynamicRequestTree === null) {
// Everything in this subtree is already complete. Bail out.
......@@ -694,7 +695,12 @@ function createPendingCacheNode(
// Create a deferred promise. This will be fulfilled once the dynamic
// response is received from the server.
rsc: createDeferredRsc() as React.ReactNode,
head: isLeafSegment ? (createDeferredRsc() as React.ReactNode) : null,
head: isLeafSegment
? [
createDeferredRsc() as React.ReactNode,
createDeferredRsc() as React.ReactNode,
]
: [null, null],
}
}
......@@ -703,7 +709,7 @@ function finishPendingCacheNode(
taskState: FlightRouterState,
serverState: FlightRouterState,
dynamicData: CacheNodeSeedData,
dynamicHead: React.ReactNode
dynamicHead: HeadData
): void {
// Writes a dynamic response into an existing Cache Node tree. This does _not_
// create a new tree, it updates the existing tree in-place. So it must follow
......@@ -796,8 +802,12 @@ function finishPendingCacheNode(
// a pending promise that needs to be resolved with the dynamic head from
// the server.
const head = cacheNode.head
if (isDeferredRsc(head)) {
head.resolve(dynamicHead)
// Handle head[0] - viewport and head[1] - metadata
if (isDeferredRsc(head[0])) {
head[0].resolve(dynamicHead[0])
}
if (isDeferredRsc(head[1])) {
head[1].resolve(dynamicHead[1])
}
}
......@@ -880,7 +890,7 @@ function abortPendingCacheNode(
export function updateCacheNodeOnPopstateRestoration(
oldCacheNode: CacheNode,
routerState: FlightRouterState
) {
): ReadyCacheNode {
// A popstate navigation reads data from the local cache. It does not issue
// new network requests (unless the cache entries have been evicted). So, we
// update the cache to drop the prefetch data for any segment whose dynamic
......
......@@ -29,7 +29,7 @@ describe('findHeadInCache', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -42,7 +42,7 @@ describe('findHeadInCache', () => {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -53,7 +53,7 @@ describe('findHeadInCache', () => {
'about',
{
lazyData: null,
head: null,
head: [null, null],
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
......@@ -69,11 +69,12 @@ describe('findHeadInCache', () => {
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
head: (
head: [
null,
<>
<title>About page!</title>
</>
),
</>,
],
},
],
]),
......@@ -107,7 +108,8 @@ describe('findHeadInCache', () => {
expect(result).not.toBeNull()
const [cacheNode, key] = result!
expect(cacheNode.head).toMatchObject(
expect(cacheNode.head[0]).toBe(null)
expect(cacheNode.head[1]).toMatchObject(
<>
<title>About page!</title>
</>
......
......@@ -118,7 +118,8 @@ export function refreshReducer(
undefined,
treePatch,
cacheNodeSeedData,
head
head,
undefined
)
mutable.prefetchCache = new Map()
}
......
......@@ -333,7 +333,8 @@ export function serverActionReducer(
undefined,
treePatch,
cacheNodeSeedData,
head
head,
undefined
)
mutable.cache = cache
......
......@@ -3,7 +3,10 @@ import type {
RootTreePrefetch,
SegmentPrefetch,
} from '../../../server/app-render/collect-segment-data'
import type { LoadingModuleData } from '../../../shared/lib/app-router-context.shared-runtime'
import type {
HeadData,
LoadingModuleData,
} from '../../../shared/lib/app-router-context.shared-runtime'
import {
NEXT_DID_POSTPONE_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
......@@ -80,7 +83,7 @@ type PendingRouteCacheEntry = RouteCacheEntryShared & {
blockedTasks: Set<PrefetchTask> | null
canonicalUrl: null
tree: null
head: null
head: [null, null]
isHeadPartial: true
}
......@@ -89,7 +92,7 @@ type RejectedRouteCacheEntry = RouteCacheEntryShared & {
blockedTasks: Set<PrefetchTask> | null
canonicalUrl: null
tree: null
head: null
head: [null, null]
isHeadPartial: true
}
......@@ -98,7 +101,7 @@ export type FulfilledRouteCacheEntry = RouteCacheEntryShared & {
blockedTasks: null
canonicalUrl: string
tree: TreePrefetch
head: React.ReactNode | null
head: HeadData
isHeadPartial: boolean
}
......@@ -284,7 +287,7 @@ export function requestRouteCacheEntryFromCache(
status: EntryStatus.Pending,
blockedTasks: null,
tree: null,
head: null,
head: [null, null],
isHeadPartial: true,
// If the request takes longer than a minute, a subsequent request should
// retry instead of waiting for this one.
......@@ -424,7 +427,7 @@ function pingBlockedTasks(entry: {
function fulfillRouteCacheEntry(
entry: PendingRouteCacheEntry,
tree: TreePrefetch,
head: React.ReactNode,
head: HeadData,
isHeadPartial: boolean,
staleAt: number,
couldBeIntercepted: boolean,
......
......@@ -5,6 +5,7 @@ import type {
} from '../../../server/app-render/types'
import type {
CacheNode,
HeadData,
LoadingModuleData,
} from '../../../shared/lib/app-router-context.shared-runtime'
import type { NormalizedFlightData } from '../../flight-data-helpers'
......@@ -125,7 +126,7 @@ function navigateUsingPrefetchedRouteTree(
currentFlightRouterState: FlightRouterState,
prefetchFlightRouterState: FlightRouterState,
prefetchSeedData: CacheNodeSeedData | null,
prefetchHead: React.ReactNode | null,
prefetchHead: HeadData,
isPrefetchHeadPartial: boolean,
canonicalUrl: string
): SuccessfulNavigationResult | NoOpNavigationResult {
......@@ -307,7 +308,7 @@ async function navigateDynamicallyWithNoPrefetch(
// In our simulated prefetch payload, we pretend that there's no seed data
// nor a prefetch head.
const prefetchSeedData = null
const prefetchHead = null
const prefetchHead: [null, null] = [null, null]
const isPrefetchHeadPartial = true
const canonicalUrl = createCanonicalUrl(
......
......@@ -6,6 +6,7 @@ import type {
FlightSegmentPath,
Segment,
} from '../server/app-render/types'
import type { HeadData } from '../shared/lib/app-router-context.shared-runtime'
export type NormalizedFlightData = {
/**
......@@ -19,7 +20,7 @@ export type NormalizedFlightData = {
segment: Segment
tree: FlightRouterState
seedData: CacheNodeSeedData | null
head: React.ReactNode | null
head: HeadData
isHeadPartial: boolean
isRootRender: boolean
}
......@@ -31,10 +32,13 @@ export type NormalizedFlightData = {
export function getFlightDataPartsFromPath(
flightDataPath: FlightDataPath
): NormalizedFlightData {
// Pick the last 4 items from the `FlightDataPath` to get the [tree, seedData, [viewport, metadata], isHeadPartial].
const flightDataPathLength = 4
// tree, seedData, and head are *always* the last three items in the `FlightDataPath`.
const [tree, seedData, head, isHeadPartial] = flightDataPath.slice(-4)
const [tree, seedData, head, isHeadPartial] =
flightDataPath.slice(-flightDataPathLength)
// The `FlightSegmentPath` is everything except the last three items. For a root render, it won't be present.
const segmentPath = flightDataPath.slice(0, -4)
const segmentPath = flightDataPath.slice(0, -flightDataPathLength)
return {
// TODO: Unify these two segment path helpers. We are inconsistently pushing an empty segment ("")
......@@ -49,7 +53,7 @@ export function getFlightDataPartsFromPath(
seedData,
head,
isHeadPartial,
isRootRender: flightDataPath.length === 4,
isRootRender: flightDataPath.length === flightDataPathLength,
}
}
......
......@@ -67,16 +67,19 @@ export function createMetadataComponents({
workStore: WorkStore
MetadataBoundary: (props: { children: React.ReactNode }) => React.ReactNode
ViewportBoundary: (props: { children: React.ReactNode }) => React.ReactNode
}): [React.ComponentType, () => Promise<void>] {
function MetadataRoot() {
}): {
MetadataTree: React.ComponentType
ViewportTree: React.ComponentType
getMetadataReady: () => Promise<void>
getViewportReady: () => Promise<void>
} {
function ViewportTree() {
return (
<>
<MetadataBoundary>
<Metadata />
</MetadataBoundary>
<ViewportBoundary>
<Viewport />
</ViewportBoundary>
{/* This meta tag is for next/font which is still required to be blocking. */}
{appUsingSizeAdjustment ? (
<meta name="next-size-adjust" content="" />
) : null}
......@@ -84,6 +87,14 @@ export function createMetadataComponents({
)
}
function MetadataTree() {
return (
<MetadataBoundary>
<Metadata />
</MetadataBoundary>
)
}
async function viewport() {
return getResolvedViewport(
tree,
......@@ -156,13 +167,22 @@ export function createMetadataComponents({
}
Metadata.displayName = METADATA_BOUNDARY_NAME
async function getMetadataAndViewportReady(): Promise<void> {
await viewport()
async function getMetadataReady(): Promise<void> {
await metadata()
return undefined
}
return [MetadataRoot, getMetadataAndViewportReady]
async function getViewportReady(): Promise<void> {
await viewport()
return undefined
}
return {
ViewportTree,
MetadataTree,
getViewportReady,
getMetadataReady,
}
}
const getResolvedMetadata = cache(getResolvedMetadataImpl)
......
......@@ -223,7 +223,8 @@ interface ParseRequestHeadersOptions {
readonly isRoutePPREnabled: boolean
}
const flightDataPathHeadKey = 'h'
const flightDataPathMetadataKey = 'h'
const flightDataPathViewportKey = 'v'
interface ParsedRequestHeaders {
/**
......@@ -445,21 +446,22 @@ async function generateDynamicRSCPayload(
const preloadCallbacks: PreloadCallbacks = []
const searchParams = createServerSearchParamsForMetadata(query, workStore)
const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree: loaderTree,
searchParams,
metadataContext: createTrackedMetadataContext(
url.pathname,
ctx.renderOpts,
workStore
),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createServerParamsForMetadata,
workStore,
MetadataBoundary,
ViewportBoundary,
})
const { ViewportTree, MetadataTree, getViewportReady, getMetadataReady } =
createMetadataComponents({
tree: loaderTree,
searchParams,
metadataContext: createTrackedMetadataContext(
url.pathname,
ctx.renderOpts,
workStore
),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createServerParamsForMetadata,
workStore,
MetadataBoundary,
ViewportBoundary,
})
flightData = (
await walkTreeWithFlightRouterState({
ctx,
......@@ -467,17 +469,23 @@ async function generateDynamicRSCPayload(
parentParams: {},
flightRouterState,
// For flight, render metadata inside leaf page
rscPayloadHead: (
<React.Fragment key={flightDataPathHeadKey}>
rscHead: [
<React.Fragment key={flightDataPathViewportKey}>
{/* noindex needs to be blocking */}
<NonIndex ctx={ctx} />
{/* 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>
),
</React.Fragment>,
],
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
getViewportReady,
getMetadataReady,
preloadCallbacks,
})
......@@ -733,22 +741,23 @@ async function getRSCPayload(
)
const searchParams = createServerSearchParamsForMetadata(query, workStore)
const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree,
errorType: is404 ? 'not-found' : undefined,
searchParams,
metadataContext: createTrackedMetadataContext(
url.pathname,
ctx.renderOpts,
workStore
),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createServerParamsForMetadata,
workStore,
MetadataBoundary,
ViewportBoundary,
})
const { ViewportTree, MetadataTree, getViewportReady, getMetadataReady } =
createMetadataComponents({
tree,
errorType: is404 ? 'not-found' : undefined,
searchParams,
metadataContext: createTrackedMetadataContext(
url.pathname,
ctx.renderOpts,
workStore
),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createServerParamsForMetadata,
workStore,
MetadataBoundary,
ViewportBoundary,
})
const preloadCallbacks: PreloadCallbacks = []
......@@ -760,6 +769,7 @@ async function getRSCPayload(
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
getViewportReady,
getMetadataReady,
missingSlots,
preloadCallbacks,
......@@ -773,14 +783,20 @@ async function getRSCPayload(
const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL)
const initialHead = (
<React.Fragment key={flightDataPathHeadKey}>
<NonIndex ctx={ctx} />
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} />
<ViewportTree key={ctx.requestId} />
</React.Fragment>
)
const globalErrorStyles = await getGlobalErrorStyles(tree, ctx)
// Assume the head we're rendering contains only partial data if PPR is
......@@ -804,7 +820,7 @@ async function getRSCPayload(
[
initialTree,
seedData,
initialHead,
[initialHeadViewport, initialHeadMetadata],
isPossiblyPartialHead,
] as FlightDataPath,
],
......@@ -850,7 +866,7 @@ async function getErrorRSCPayload(
} = ctx
const searchParams = createServerSearchParamsForMetadata(query, workStore)
const [MetadataTree] = createMetadataComponents({
const { MetadataTree, ViewportTree } = createMetadataComponents({
tree,
searchParams,
// We create an untracked metadata context here because we can't postpone
......@@ -865,11 +881,17 @@ async function getErrorRSCPayload(
ViewportBoundary,
})
const initialHead = (
<React.Fragment key={flightDataPathHeadKey}>
<NonIndex ctx={ctx} />
const initialHeadMetadata = (
<React.Fragment key={flightDataPathMetadataKey}>
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={requestId} />
</React.Fragment>
)
const initialHeadViewport = (
<React.Fragment key={flightDataPathViewportKey}>
<NonIndex ctx={ctx} />
{/* Adding requestId as react key to make metadata remount for each render */}
<ViewportTree key={requestId} />
{process.env.NODE_ENV === 'development' && (
<meta name="next-error" content="not-found" />
)}
......@@ -911,7 +933,7 @@ async function getErrorRSCPayload(
[
initialTree,
initialSeedData,
initialHead,
[initialHeadViewport, initialHeadMetadata],
isPossiblyPartialHead,
] as FlightDataPath,
],
......
......@@ -17,14 +17,17 @@ import {
} from '../stream-utils/node-web-streams-helper'
import { UNDERSCORE_NOT_FOUND_ROUTE } from '../../api/constants'
import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'
import type { LoadingModuleData } from '../../shared/lib/app-router-context.shared-runtime'
import type {
HeadData,
LoadingModuleData,
} from '../../shared/lib/app-router-context.shared-runtime'
// Contains metadata about the route tree. The client must fetch this before
// it can fetch any actual segment data.
export type RootTreePrefetch = {
buildId: string
tree: TreePrefetch
head: React.ReactNode | null
head: HeadData
isHeadPartial: boolean
staleTime: number
}
......@@ -178,7 +181,7 @@ async function PrefetchTreeData({
}
const flightRouterState: FlightRouterState = flightDataPaths[0][0]
const seedData: CacheNodeSeedData = flightDataPaths[0][1]
const head: React.ReactNode | null = flightDataPaths[0][2]
const head: HeadData = flightDataPaths[0][2]
// Compute the route metadata tree by traversing the FlightRouterState. As we
// walk the tree, we will also spawn a task to produce a prefetch response for
......
......@@ -30,6 +30,7 @@ export function createComponentTree(props: {
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
getMetadataReady: () => Promise<void>
getViewportReady: () => Promise<void>
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
......@@ -63,6 +64,7 @@ async function createComponentTreeInternal({
injectedCSS,
injectedJS,
injectedFontPreloadTags,
getViewportReady,
getMetadataReady,
ctx,
missingSlots,
......@@ -75,6 +77,7 @@ async function createComponentTreeInternal({
injectedCSS: Set<string>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
getViewportReady: () => Promise<void>
getMetadataReady: () => Promise<void>
ctx: AppRenderContext
missingSlots?: Set<string>
......@@ -481,11 +484,14 @@ async function createComponentTreeInternal({
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
// getMetadataReady is used to conditionally throw. In the case of parallel routes we will have more than one page
// `getMetadataReady` and `getViewportReady` are 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.
getMetadataReady: isChildrenRouteKey
? getMetadataReady
: () => Promise.resolve(),
getViewportReady: isChildrenRouteKey
? getViewportReady
: () => Promise.resolve(),
ctx,
missingSlots,
preloadCallbacks,
......@@ -645,6 +651,7 @@ async function createComponentTreeInternal({
{pageElement}
{layerAssets}
<OutletBoundary>
<MetadataOutlet ready={getViewportReady} />
<MetadataOutlet ready={getMetadataReady} />
</OutletBoundary>
</React.Fragment>,
......
......@@ -104,7 +104,7 @@ export type FlightDataSegment = [
/* segment of the rendered slice: */ Segment,
/* treePatch */ FlightRouterState,
/* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component
/* head */ React.ReactNode | null,
/* head: [viewport, metadata] */ [React.ReactNode, React.ReactNode],
/* isHeadPartial */ boolean,
]
......
......@@ -20,6 +20,7 @@ import {
addSearchParamsIfPageSegment,
} from '../../shared/lib/segment'
import { createComponentTree } from './create-component-tree'
import type { HeadData } from '../../shared/lib/app-router-context.shared-runtime'
/**
* Use router state to decide at what common layout to render the page.
......@@ -30,11 +31,12 @@ export async function walkTreeWithFlightRouterState({
parentParams,
flightRouterState,
parentRendered,
rscPayloadHead,
rscHead,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded,
getViewportReady,
getMetadataReady,
ctx,
preloadCallbacks,
......@@ -43,12 +45,13 @@ export async function walkTreeWithFlightRouterState({
parentParams: { [key: string]: string | string[] }
flightRouterState?: FlightRouterState
parentRendered?: boolean
rscPayloadHead: React.ReactNode
rscHead: HeadData
injectedCSS: Set<string>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean
getMetadataReady: () => Promise<void>
getViewportReady: () => Promise<void>
ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks
}): Promise<FlightDataPath[]> {
......@@ -144,7 +147,7 @@ export async function walkTreeWithFlightRouterState({
overriddenSegment,
routerState,
null,
null,
[null, null],
false,
] satisfies FlightDataSegment,
]
......@@ -161,6 +164,7 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded,
getViewportReady,
getMetadataReady,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
......@@ -172,7 +176,7 @@ export async function walkTreeWithFlightRouterState({
overriddenSegment,
routerState,
seedData,
rscPayloadHead,
rscHead,
false,
] satisfies FlightDataSegment,
]
......@@ -216,11 +220,12 @@ export async function walkTreeWithFlightRouterState({
flightRouterState:
flightRouterState && flightRouterState[1][parallelRouteKey],
parentRendered: parentRendered || renderComponentsOnThisLevel,
rscPayloadHead,
rscHead,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
getViewportReady,
getMetadataReady,
preloadCallbacks,
})
......
......@@ -23,6 +23,9 @@ export type LoadingModuleData =
| [React.JSX.Element, React.ReactNode, React.ReactNode]
| null
/** metadata cache nodes: [viewport, metadata] */
export type HeadData = [React.ReactNode, React.ReactNode]
export type LazyCacheNode = {
/**
* When rsc is null, this is a lazily-initialized cache node.
......@@ -54,7 +57,8 @@ export type LazyCacheNode = {
lazyData: Promise<FetchServerResponseResult> | null
prefetchHead: React.ReactNode
head: React.ReactNode
head: HeadData
loading: LoadingModuleData | Promise<LoadingModuleData>
......@@ -96,7 +100,8 @@ export type ReadyCacheNode = {
*/
lazyData: null
prefetchHead: React.ReactNode
head: React.ReactNode
head: HeadData
loading: LoadingModuleData | Promise<LoadingModuleData>
......
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