Unverified Commit 642ad12c authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Seed CacheNodes immediately after receiving response (#58669)

## Based on #58666

*I submitted this stack as separate PRs so I could run CI but I want to
land them as a single unit. So I've left all but this last one in draft
mode. You can review them commit-by-commit.*

We render nested layouts in parallel on the server. This means we should
be able to create a CacheNode entry for every layout in the tree as soon
as the Flight response is received by the client, even before the nested
layouts have streamed in. Currently, we wait until the nested layouts
start rendering before we write them into the cache, which prevents us
from performing certain optimizations. That's because the CacheNodes are
sent as a prop to LayoutRouter; the only way to unwrap the CacheNode is
to wait for LayoutRouter to render.

In previous PRs, I updated the server to create a top-level data
structure that contains all the CacheNodes for the entire tree. This PR
updates the client side to receive the nodes and write them into the
cache.

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 9471fb85
......@@ -255,14 +255,14 @@ function Router({
initialHead,
initialTree,
initialCanonicalUrl,
children,
initialSeedData,
assetPrefix,
}: AppRouterProps) {
const initialState = useMemo(
() =>
createInitialRouterState({
buildId,
children,
initialSeedData,
initialCanonicalUrl,
initialTree,
initialParallelRoutes,
......@@ -270,7 +270,7 @@ function Router({
location: !isServer ? window.location : null,
initialHead,
}),
[buildId, children, initialCanonicalUrl, initialTree, initialHead]
[buildId, initialSeedData, initialCanonicalUrl, initialTree, initialHead]
)
const [reducerState, dispatch, sync] =
useReducerWithReduxDevtools(initialState)
......
......@@ -314,7 +314,6 @@ function InnerLayoutRouter({
parallelRouterKey,
url,
childNodes,
initialChildNode,
segmentPath,
tree,
// TODO-APP: implement `<Offscreen>` when available.
......@@ -324,7 +323,6 @@ function InnerLayoutRouter({
parallelRouterKey: string
url: string
childNodes: ChildSegmentMap
initialChildNode: React.ReactNode | null
segmentPath: FlightSegmentPath
tree: FlightRouterState
isActive: boolean
......@@ -340,39 +338,6 @@ function InnerLayoutRouter({
// Read segment path from the parallel router cache node.
let childNode = childNodes.get(cacheKey)
// If initialChildNode is available this means it's the Flight / SSR case.
// TODO: `null` is a valid React Node, so technically we should use some other
// value besides `null` to indicate that the tree is partial. However, we're
// about to remove all the cases that lead to a partial tree, so this soon
// won't be an issue.
if (initialChildNode !== null) {
if (!childNode) {
// Add the segment's subTreeData to the cache.
// This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode.
// TODO: We should seed all the CacheNodes as soon as the Flight payload
// is received. We already collect them eagerly on the server, so we
// shouldn't need to wait until the render phase to write them into
// the cache. Requires refactoring the Flight response type. Then we can
// delete this code.
childNode = {
status: CacheStates.READY,
data: null,
subTreeData: initialChildNode,
parallelRoutes: new Map(),
}
childNodes.set(cacheKey, childNode)
} else {
if (childNode.status === CacheStates.LAZY_INITIALIZED) {
// @ts-expect-error we're changing it's type!
childNode.status = CacheStates.READY
// @ts-expect-error
childNode.subTreeData = initialChildNode
}
}
}
// When childNode is not available during rendering client-side we need to fetch it from the server.
if (!childNode || childNode.status === CacheStates.LAZY_INITIALIZED) {
/**
......@@ -503,8 +468,6 @@ function LoadingBoundary({
export default function OuterLayoutRouter({
parallelRouterKey,
segmentPath,
initialChildNode,
childPropSegment,
error,
errorStyles,
errorScripts,
......@@ -521,8 +484,6 @@ export default function OuterLayoutRouter({
}: {
parallelRouterKey: string
segmentPath: FlightSegmentPath
initialChildNode: React.ReactNode | null
childPropSegment: Segment
error: ErrorComponent
errorStyles: React.ReactNode | undefined
errorScripts: React.ReactNode | undefined
......@@ -570,10 +531,6 @@ export default function OuterLayoutRouter({
<>
{styles}
{preservedSegments.map((preservedSegment) => {
const isChildPropSegment = matchSegment(
preservedSegment,
childPropSegment
)
const preservedSegmentValue = getSegmentValue(preservedSegment)
const cacheKey = createRouterCacheKey(preservedSegment)
......@@ -612,9 +569,6 @@ export default function OuterLayoutRouter({
url={url}
tree={tree}
childNodes={childNodesForParallelRouter!}
initialChildNode={
isChildPropSegment ? initialChildNode : null
}
segmentPath={segmentPath}
cacheKey={cacheKey}
isActive={
......
......@@ -11,21 +11,22 @@ export function applyFlightData(
wasPrefetched: boolean = false
): boolean {
// The one before last item is the router state tree patch
const [treePatch, subTreeData, head /* , cacheNodeSeedData */] =
flightDataPath.slice(-4)
const [treePatch, cacheNodeSeedData, head] = flightDataPath.slice(-3)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData === null) {
if (cacheNodeSeedData === null) {
return false
}
if (flightDataPath.length === 4) {
if (flightDataPath.length === 3) {
const subTreeData = cacheNodeSeedData[2]
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(
cache,
existingCache,
treePatch,
cacheNodeSeedData,
head,
wasPrefetched
)
......
......@@ -33,11 +33,10 @@ const getFlightData = (): FlightData => {
children: ['', {}],
},
],
<h1>About Page!</h1>,
['about', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
}
......@@ -53,8 +52,8 @@ describe('applyRouterStatePatchToTree', () => {
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const [treePatch /*, subTreeData, head*/] = flightDataPath.slice(-4)
const flightSegmentPath = flightDataPath.slice(0, -5)
const [treePatch /*, cacheNodeSeedData, head*/] = flightDataPath.slice(-3)
const flightSegmentPath = flightDataPath.slice(0, -4)
const newRouterStateTree = applyRouterStatePatchToTree(
['', ...flightSegmentPath],
......
......@@ -37,7 +37,7 @@ describe('createInitialRouterState', () => {
buildId,
initialTree,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -48,7 +48,7 @@ describe('createInitialRouterState', () => {
buildId,
initialTree,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......
import type { ReactNode } from 'react'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type { FlightRouterState } from '../../../server/app-render/types'
import type {
FlightRouterState,
CacheNodeSeedData,
} from '../../../server/app-render/types'
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import { createHrefFromUrl } from './create-href-from-url'
......@@ -11,7 +14,7 @@ export interface InitialRouterStateParameters {
buildId: string
initialTree: FlightRouterState
initialCanonicalUrl: string
children: ReactNode
initialSeedData: CacheNodeSeedData
initialParallelRoutes: CacheNode['parallelRoutes']
isServer: boolean
location: Location | null
......@@ -21,24 +24,32 @@ export interface InitialRouterStateParameters {
export function createInitialRouterState({
buildId,
initialTree,
children,
initialSeedData,
initialCanonicalUrl,
initialParallelRoutes,
isServer,
location,
initialHead,
}: InitialRouterStateParameters) {
const subTreeData = initialSeedData[2]
const cache: CacheNode = {
status: CacheStates.READY,
data: null,
subTreeData: children,
subTreeData: subTreeData,
// 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,
}
// When the cache hasn't been seeded yet we fill the cache with the head.
if (initialParallelRoutes === null || initialParallelRoutes.size === 0) {
fillLazyItemsTillLeafWithHead(cache, undefined, initialTree, initialHead)
fillLazyItemsTillLeafWithHead(
cache,
undefined,
initialTree,
initialSeedData,
initialHead
)
}
return {
......
......@@ -17,7 +17,7 @@ const getFlightData = (): FlightData => {
children: ['', {}],
},
],
<h1>SubTreeData Injected!</h1>,
['about', null, <h1>SubTreeData Injected!</h1>],
<>
<title>Head Injected!</title>
</>,
......
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type { FlightDataPath } from '../../../server/app-render/types'
import type {
FlightDataPath,
CacheNodeSeedData,
} from '../../../server/app-render/types'
import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import { createRouterCacheKey } from './create-router-cache-key'
......@@ -14,7 +17,7 @@ export function fillCacheWithNewSubTreeData(
flightDataPath: FlightDataPath,
wasPrefetched?: boolean
): void {
const isLastEntry = flightDataPath.length <= 6
const isLastEntry = flightDataPath.length <= 5
const [parallelRouteKey, segment] = flightDataPath
const cacheKey = createRouterCacheKey(segment)
......@@ -43,10 +46,12 @@ export function fillCacheWithNewSubTreeData(
!childCacheNode.data ||
childCacheNode === existingChildCacheNode
) {
const seedData: CacheNodeSeedData = flightDataPath[3]
const subTreeData = seedData[2]
childCacheNode = {
status: CacheStates.READY,
data: null,
subTreeData: flightDataPath[3],
subTreeData,
// Ensure segments other than the one we got data for are preserved.
parallelRoutes: existingChildCacheNode
? new Map(existingChildCacheNode.parallelRoutes)
......@@ -65,6 +70,7 @@ export function fillCacheWithNewSubTreeData(
childCacheNode,
existingChildCacheNode,
flightDataPath[2],
seedData,
flightDataPath[4],
wasPrefetched
)
......
......@@ -26,11 +26,10 @@ const getFlightData = (): FlightData => {
null,
true,
],
<h1>About Page!</h1>,
['', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
}
......@@ -88,9 +87,14 @@ describe('fillLazyItemsTillLeafWithHead', () => {
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [treePatch, _subTreeData, head] = flightDataPath.slice(-4)
fillLazyItemsTillLeafWithHead(cache, existingCache, treePatch, head)
const [treePatch, cacheNodeSeedData, head] = flightDataPath.slice(-3)
fillLazyItemsTillLeafWithHead(
cache,
existingCache,
treePatch,
cacheNodeSeedData,
head
)
const expectedCache: CacheNode = {
data: null,
......
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type { FlightRouterState } from '../../../server/app-render/types'
import type {
FlightRouterState,
CacheNodeSeedData,
} from '../../../server/app-render/types'
import { createRouterCacheKey } from './create-router-cache-key'
export function fillLazyItemsTillLeafWithHead(
newCache: CacheNode,
existingCache: CacheNode | undefined,
routerState: FlightRouterState,
cacheNodeSeedData: CacheNodeSeedData | null,
head: React.ReactNode,
wasPrefetched?: boolean
): void {
......@@ -21,26 +25,58 @@ export function fillLazyItemsTillLeafWithHead(
const segmentForParallelRoute = parallelRouteState[0]
const cacheKey = createRouterCacheKey(segmentForParallelRoute)
// TODO: We should traverse the cacheNodeSeedData tree instead of the router
// state tree. Ideally, they would always be the same shape, but because of
// the loading.js pattern, cacheNodeSeedData sometimes only represents a
// partial tree. That's why this node is sometimes null. Once PPR lands,
// loading.js will no longer have special behavior and we can traverse the
// data tree instead.
//
// We should also consider merging the router state tree and the data tree
// in the response format, so that we don't have to send the keys twice.
// Then the client can convert them into separate representations.
const parallelSeedData =
cacheNodeSeedData !== null &&
cacheNodeSeedData[1] !== null &&
cacheNodeSeedData[1][key] !== undefined
? cacheNodeSeedData[1][key]
: null
if (existingCache) {
const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
const existingCacheNode = parallelRouteCacheNode.get(cacheKey)
const newCacheNode: CacheNode =
wasPrefetched && existingCacheNode
? ({
status: existingCacheNode.status,
data: existingCacheNode.data,
subTreeData: existingCacheNode.subTreeData,
parallelRoutes: new Map(existingCacheNode.parallelRoutes),
} as CacheNode)
: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
}
let newCacheNode: CacheNode
if (parallelSeedData !== null) {
// New data was sent from the server.
const seedNode = parallelSeedData[2]
newCacheNode = {
status: CacheStates.READY,
data: null,
subTreeData: seedNode,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
}
} else if (wasPrefetched && existingCacheNode) {
// No new data was sent from the server, but the existing cache node
// was prefetched, so we should reuse that.
newCacheNode = {
status: existingCacheNode.status,
data: existingCacheNode.data,
subTreeData: existingCacheNode.subTreeData,
parallelRoutes: new Map(existingCacheNode.parallelRoutes),
} as CacheNode
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
}
}
// Overrides the cache key with the new cache node.
parallelRouteCacheNode.set(cacheKey, newCacheNode)
// Traverse deeper to apply the head / fill lazy items till the head.
......@@ -48,6 +84,7 @@ export function fillLazyItemsTillLeafWithHead(
newCacheNode,
existingCacheNode,
parallelRouteState,
parallelSeedData ? parallelSeedData : null,
head,
wasPrefetched
)
......@@ -57,11 +94,25 @@ export function fillLazyItemsTillLeafWithHead(
}
}
const newCacheNode: CacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
let newCacheNode: CacheNode
if (parallelSeedData !== null) {
// New data was sent from the server.
const seedNode = parallelSeedData[2]
newCacheNode = {
status: CacheStates.READY,
data: null,
subTreeData: seedNode,
parallelRoutes: new Map(),
}
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
}
const existingParallelRoutes = newCache.parallelRoutes.get(key)
......@@ -75,6 +126,7 @@ export function fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
parallelRouteState,
parallelSeedData,
head,
wasPrefetched
)
......
......@@ -18,11 +18,10 @@ const getFlightData = (): FlightData => {
children: ['', {}],
},
],
<h1>About Page!</h1>,
['about', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
}
......@@ -80,7 +79,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const flightSegmentPath = flightDataPath.slice(0, -3)
// @ts-expect-error TODO-APP: investigate why this is not a TS error in router-reducer.
cache.status = CacheStates.READY
......
......@@ -59,7 +59,7 @@ function fastRefreshReducerImpl(
for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 4) {
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('REFRESH FAILED')
return state
......
......@@ -28,11 +28,10 @@ const flightData: FlightData = [
children: ['__PAGE__', {}],
},
],
<h1>About Page!</h1>,
['about', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
......@@ -57,14 +56,17 @@ const demographicsFlightData: FlightData = [
null,
true,
],
<html>
<head></head>
<body>Root layout from response</body>
</html>,
[
'',
null,
<html>
<head></head>
<body>Root layout from response</body>
</html>,
],
<>
<title>Demographics Head</title>
</>,
null,
],
]
......@@ -173,7 +175,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -375,7 +377,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -386,7 +388,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -567,7 +569,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -578,7 +580,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -726,7 +728,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -737,7 +739,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -885,7 +887,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -896,7 +898,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking#hash', 'https://localhost') as any,
......@@ -1048,7 +1050,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -1063,7 +1065,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -1338,7 +1340,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/parallel-tab-bar', 'https://localhost') as any,
......@@ -1349,7 +1351,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/parallel-tab-bar', 'https://localhost') as any,
......@@ -1554,7 +1556,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking#hash', 'https://localhost') as any,
......@@ -1704,7 +1706,7 @@ describe('navigateReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......
......@@ -175,10 +175,10 @@ export function navigateReducer(
for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice(
0,
-5
-4
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-4)[0] as FlightRouterState
const treePatch = flightDataPath.slice(-3)[0] as FlightRouterState
// TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath]
......
......@@ -23,11 +23,10 @@ jest.mock('../fetch-server-response', () => {
children: ['', {}],
},
],
<h1>About Page!</h1>,
['about', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
return {
......@@ -118,7 +117,7 @@ describe('prefetchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -260,7 +259,7 @@ describe('prefetchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -271,7 +270,7 @@ describe('prefetchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......
......@@ -27,16 +27,19 @@ jest.mock('../fetch-server-response', () => {
null,
true,
],
<html>
<head></head>
<body>
<h1>Linking Page!</h1>
</body>
</html>,
[
'',
null,
<html>
<head></head>
<body>
<h1>Linking Page!</h1>
</body>
</html>,
],
<>
<title>Linking page!</title>
</>,
null,
],
]
return {
......@@ -125,7 +128,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -275,7 +278,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -286,7 +289,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -463,7 +466,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -474,7 +477,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -697,7 +700,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -710,7 +713,7 @@ describe('refreshReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......
......@@ -57,8 +57,8 @@ export function refreshReducer(
cache.data = null
for (const flightDataPath of flightData) {
// FlightDataPath with more than four items means unexpected Flight data was returned
if (flightDataPath.length !== 4) {
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('REFRESH FAILED')
return state
......@@ -95,10 +95,11 @@ export function refreshReducer(
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-3)
const [cacheNodeSeedData, head] = flightDataPath.slice(-2)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
if (cacheNodeSeedData !== null) {
const subTreeData = cacheNodeSeedData[2]
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(
......@@ -106,6 +107,7 @@ export function refreshReducer(
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined,
treePatch,
cacheNodeSeedData,
head
)
mutable.cache = cache
......
......@@ -84,7 +84,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -239,7 +239,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......@@ -249,7 +249,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
......
......@@ -206,7 +206,7 @@ export function serverActionReducer(
for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 4) {
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('SERVER ACTION APPLY FAILED')
return state
......@@ -235,7 +235,9 @@ export function serverActionReducer(
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-3)
const [cacheNodeSeedData, head] = flightDataPath.slice(-2)
const subTreeData =
cacheNodeSeedData !== null ? cacheNodeSeedData[2] : null
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
......@@ -246,6 +248,7 @@ export function serverActionReducer(
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined,
treePatch,
cacheNodeSeedData,
head
)
mutable.cache = cache
......
......@@ -26,11 +26,10 @@ jest.mock('../fetch-server-response', () => {
children: ['', {}],
},
],
<h1>About Page!</h1>,
['about', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
return {
......@@ -58,11 +57,10 @@ const flightDataForPatch: FlightData = [
children: ['', {}],
},
],
<h1>Somewhere Page!</h1>,
['somewhere-else', null, <h1>Somewhere Page!</h1>],
<>
<title>Somewhere page!</title>
</>,
null,
],
]
......@@ -150,7 +148,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking/about', 'https://localhost') as any,
......@@ -330,7 +328,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking/about', 'https://localhost') as any,
......@@ -341,7 +339,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking/about', 'https://localhost') as any,
......@@ -518,7 +516,7 @@ describe('serverPatchReducer', () => {
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL(initialCanonicalUrl, 'https://localhost') as any,
......
......@@ -49,10 +49,10 @@ export function serverPatchReducer(
let currentCache = state.cache
for (const flightDataPath of flightData) {
// Slices off the last segment (which is at -5) as it doesn't exist in the tree yet
const flightSegmentPath = flightDataPath.slice(0, -5)
// Slices off the last segment (which is at -4) as it doesn't exist in the tree yet
const flightSegmentPath = flightDataPath.slice(0, -4)
const [treePatch] = flightDataPath.slice(-4, -3)
const [treePatch] = flightDataPath.slice(-3, -2)
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
['', ...flightSegmentPath],
......
......@@ -35,11 +35,10 @@ describe('shouldHardNavigate', () => {
children: ['', {}],
},
],
<h1>About Page!</h1>,
['about', null, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
null,
],
]
}
......@@ -51,7 +50,7 @@ describe('shouldHardNavigate', () => {
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const flightSegmentPath = flightDataPath.slice(0, -3)
const result = shouldHardNavigate(
['', ...flightSegmentPath],
......@@ -95,8 +94,7 @@ describe('shouldHardNavigate', () => {
children: ['', {}],
},
],
null,
null,
[['id', '123', 'd'], null, null],
null,
],
]
......@@ -109,7 +107,7 @@ describe('shouldHardNavigate', () => {
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const flightSegmentPath = flightDataPath.slice(0, -3)
const result = shouldHardNavigate(
['', ...flightSegmentPath],
......@@ -153,8 +151,7 @@ describe('shouldHardNavigate', () => {
children: ['', {}],
},
],
null,
null,
[['id', '123', 'd'], null, null],
null,
],
]
......@@ -167,7 +164,7 @@ describe('shouldHardNavigate', () => {
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const flightSegmentPath = flightDataPath.slice(0, -3)
const result = shouldHardNavigate(
['', ...flightSegmentPath],
......
......@@ -7,6 +7,7 @@ import type {
FlightSegmentPath,
RenderOpts,
Segment,
CacheNodeSeedData,
} from './types'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { RequestStore } from '../../client/components/request-async-storage.external'
......@@ -359,7 +360,7 @@ function createServerComponentsRenderer(
asNotFound: props.asNotFound,
metadataOutlet: <MetadataOutlet />,
})
const componentTree = seedData[2]
return (
<>
{styles}
......@@ -370,12 +371,7 @@ function createServerComponentsRenderer(
// This is the router state tree.
initialTree={initialTree}
// This is the tree of React nodes that are seeded into the cache
// TODO: This will be passed as a prop in a later PR. Then we will use
// this prop to populate the cache nodes as soon as the app router
// receives the response. This will replace the `initialChildNode`
// that's currently passed to Layout Router.
//
// cacheNodeSeedData={seedData}
initialSeedData={seedData}
initialHead={
<>
{ctx.res.statusCode > 400 && (
......@@ -386,9 +382,7 @@ function createServerComponentsRenderer(
</>
}
globalErrorComponent={GlobalError}
>
{componentTree}
</AppRouter>
/>
</>
)
}, options)
......@@ -923,6 +917,14 @@ async function renderToHTMLOrFlightImpl(
// 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 = [
initialTree[0],
null,
<html id="__next_error__">
<head></head>
<body></body>
</html>,
]
return (
<AppRouter
buildId={buildId}
......@@ -931,12 +933,8 @@ async function renderToHTMLOrFlightImpl(
initialTree={initialTree}
initialHead={head}
globalErrorComponent={GlobalError}
>
<html id="__next_error__">
<head></head>
<body></body>
</html>
</AppRouter>
initialSeedData={initialSeedData}
/>
)
},
{
......
......@@ -4,8 +4,6 @@ import { isClientReference } from '../../lib/client-reference'
import { getLayoutOrPageModule } from '../lib/app-dir-module'
import type { LoaderTree } from '../lib/app-dir-module'
import { interopDefault } from './interop-default'
import { preloadComponent } from './preload-component'
import { addSearchParamsIfPageSegment } from './create-flight-router-state-from-loader-tree'
import { parseLoaderTree } from './parse-loader-tree'
import type { CreateSegmentPath, AppRenderContext } from './app-render'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
......@@ -57,7 +55,6 @@ export async function createComponentTree({
},
pagePath,
getDynamicParamFromSegment,
query,
isPrefetch,
searchParamsProps,
} = ctx
......@@ -285,13 +282,9 @@ export async function createComponentTree({
// Resolve the segment param
const actualSegment = segmentParam ? segmentParam.treeSegment : segment
// This happens outside of rendering in order to eagerly kick off data fetching for layouts / the page further down
// TODO: Once we're done refactoring the Flight response type so that all the
// tree nodes are passed at the root of the response, we'll no longer need to
// do anything extra to preload the nested layouts; all of the child nodes will
// automatically be rendered in parallel by React. Then, to simplify the code,
// we should combine this `map` traversal with the loop below that turns
// the array into an object.
//
// TODO: Combine this `map` traversal with the loop below that turns the array
// into an object.
const parallelRouteMap = await Promise.all(
Object.keys(parallelRoutes).map(
async (
......@@ -304,8 +297,6 @@ export async function createComponentTree({
const parallelRoute = parallelRoutes[parallelRouteKey]
const childSegment = parallelRoute[0]
const childSegmentParam = getDynamicParamFromSegment(childSegment)
const notFoundComponent =
NotFound && isChildrenRouteKey ? <NotFound /> : undefined
......@@ -313,12 +304,7 @@ export async function createComponentTree({
// otherwise we keep rendering for the prefetch.
// We also want to bail out if there's no Loading component in the tree.
let currentStyles = undefined
let initialChildNode = null
let childCacheNodeSeedData = null
const childPropSegment = addSearchParamsIfPageSegment(
childSegmentParam ? childSegmentParam.treeSegment : childSegment,
query
)
let childCacheNodeSeedData: CacheNodeSeedData | null = null
if (
!(
isPrefetch &&
......@@ -343,7 +329,6 @@ export async function createComponentTree({
})
currentStyles = childComponentStyles
initialChildNode = seedData[2]
childCacheNodeSeedData = seedData
}
......@@ -370,11 +355,6 @@ export async function createComponentTree({
templateScripts={templateScripts}
notFound={notFoundComponent}
notFoundStyles={notFoundStyles}
// TODO: This prop will soon by removed and instead we'll return all
// the child nodes in the entire tree at the top level of the
// Flight response.
initialChildNode={initialChildNode}
childPropSegment={childPropSegment}
styles={currentStyles}
/>,
childCacheNodeSeedData,
......@@ -397,12 +377,16 @@ export async function createComponentTree({
// When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component
if (!Component) {
return {
// TODO: I don't think the extra fragment is necessary. React treats top
// level fragments as transparent, i.e. the runtime behavior should be
// identical even without it. But maybe there's some findDOMNode-related
// reason that I'm not aware of, so I'm leaving it as-is out of extreme
// caution, for now.
seedData: [actualSegment, null, <>{parallelRouteProps.children}</>],
seedData: [
actualSegment,
parallelRouteCacheNodeSeedData,
// TODO: I don't think the extra fragment is necessary. React treats top
// level fragments as transparent, i.e. the runtime behavior should be
// identical even without it. But maybe there's some findDOMNode-related
// reason that I'm not aware of, so I'm leaving it as-is out of extreme
// caution, for now.
<>{parallelRouteProps.children}</>,
],
styles: layerAssets,
}
}
......@@ -452,16 +436,6 @@ export async function createComponentTree({
})(),
}
// Eagerly execute layout/page component to trigger fetches early.
// TODO: We can delete this once we start passing the nested layouts at the
// top-level of the Flight response, because React will render them in
// parallel automatically.
if (!isClientComponent) {
Component = await Promise.resolve().then(() =>
preloadComponent(Component, props)
)
}
return {
seedData: [
actualSegment,
......
......@@ -86,9 +86,8 @@ export type FlightDataPath =
...FlightSegmentPath[],
/* segment of the rendered slice: */ Segment,
/* treePatch */ FlightRouterState,
/* subTreeData: */ React.ReactNode | null, // Can be null during prefetch if there's no loading component
/* head */ React.ReactNode | null,
/* cacheNodeSeedData */ null
/* cacheNodeSeedData */ CacheNodeSeedData, // Can be null during prefetch if there's no loading component
/* head */ React.ReactNode | null
]
/**
......
......@@ -122,68 +122,56 @@ export async function walkTreeWithFlightRouterState({
flightRouterState &&
canSegmentBeOverridden(actualSegment, flightRouterState[0])
? flightRouterState[0]
: null
: actualSegment
return [
[
overriddenSegment ?? actualSegment,
createFlightRouterStateFromLoaderTree(
// Create router state using the slice of the loaderTree
loaderTreeToFilter,
getDynamicParamFromSegment,
query
),
shouldSkipComponentTree
? null
: // Create component tree using the slice of the loaderTree
// TODO: Not sure why this ts error started happening, after a
// seemingly innocuous change. But I'm also not sure why this extra
// wrapper element exists. We should just remove it.
// @ts-expect-error: Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method.
React.createElement(async () => {
const { seedData } = await createComponentTree(
// This ensures flightRouterPath is valid and filters down the tree
{
ctx,
createSegmentPath,
loaderTree: loaderTreeToFilter,
parentParams: currentParams,
firstItem: isFirst,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded,
asNotFound,
metadataOutlet,
}
)
const componentNode = seedData[2]
return componentNode
}),
shouldSkipComponentTree
? null
: (() => {
const { layoutOrPagePath } = parseLoaderTree(loaderTreeToFilter)
const layerAssets = getLayerAssets({
ctx,
layoutOrPagePath,
injectedCSS: new Set(injectedCSS),
injectedJS: new Set(injectedJS),
injectedFontPreloadTags: new Set(injectedFontPreloadTags),
})
const routerState = createFlightRouterStateFromLoaderTree(
// Create router state using the slice of the loaderTree
loaderTreeToFilter,
getDynamicParamFromSegment,
query
)
return (
<>
{layerAssets}
{rscPayloadHead}
</>
)
})(),
null,
],
]
if (shouldSkipComponentTree) {
// Send only the router state
return [[overriddenSegment, routerState, null, null]]
} else {
// Create component tree using the slice of the loaderTree
const { seedData } = await createComponentTree(
// This ensures flightRouterPath is valid and filters down the tree
{
ctx,
createSegmentPath,
loaderTree: loaderTreeToFilter,
parentParams: currentParams,
firstItem: isFirst,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded,
asNotFound,
metadataOutlet,
}
)
// Create head
const { layoutOrPagePath } = parseLoaderTree(loaderTreeToFilter)
const layerAssets = getLayerAssets({
ctx,
layoutOrPagePath,
injectedCSS: new Set(injectedCSS),
injectedJS: new Set(injectedJS),
injectedFontPreloadTags: new Set(injectedFontPreloadTags),
})
const head = (
<>
{layerAssets}
{rscPayloadHead}
</>
)
return [[overriddenSegment, routerState, seedData, head]]
}
}
// If we are not rendering on this level we need to check if the current
......
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