Unverified Commit 68e74b44 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Lift subtree data out of React tree (#58569)

Refactors createComponentTree to return a top-level tree of all the
subtree data in the entire response. Although we were already collecting
this data, it's passed to the client as a prop LayoutRouter, which means
it can only be unwrapped by rendering the React tree.

Instead, we will hoist all the subtree data (i.e. the React nodes that
represent the nested layouts) into a top-level object that can be
immediately unwrapped by the client when it processes the response.

Then, the client will use this tree to eagerly populate the cache nodes,
rather than waiting for the LayoutRouter to lazily populate the cache
during render, like we do today.

This PR does not implement the client-side changes yet; it only creates
the new data structure, which I've named CacheNodeSeedData. The rest
will come in subsequent PRs.

---------
Co-authored-by: 's avatarZack Tanner <zacktanner@gmail.com>
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 6984ac4b
......@@ -346,7 +346,7 @@ function createServerComponentsRenderer(
appUsingSizeAdjustment: appUsingSizeAdjustment,
})
const { Component: ComponentTree, styles } = await createComponentTree({
const { seedData, styles } = await createComponentTree({
ctx,
createSegmentPath: (child) => child,
loaderTree: loaderTreeToRender,
......@@ -359,7 +359,7 @@ function createServerComponentsRenderer(
asNotFound: props.asNotFound,
metadataOutlet: <MetadataOutlet />,
})
const componentTree = seedData[2]
return (
<>
{styles}
......@@ -367,7 +367,15 @@ function createServerComponentsRenderer(
buildId={ctx.renderOpts.buildId}
assetPrefix={ctx.assetPrefix}
initialCanonicalUrl={urlPathname}
// 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}
initialHead={
<>
{ctx.res.statusCode > 400 && (
......@@ -379,7 +387,7 @@ function createServerComponentsRenderer(
}
globalErrorComponent={GlobalError}
>
<ComponentTree />
{componentTree}
</AppRouter>
</>
)
......
import type { FlightSegmentPath } from './types'
import type { FlightSegmentPath, CacheNodeSeedData } from './types'
import React from 'react'
import { isClientReference } from '../../lib/client-reference'
import { getLayoutOrPageModule } from '../lib/app-dir-module'
......@@ -41,7 +41,7 @@ export async function createComponentTree({
metadataOutlet?: React.ReactNode
ctx: AppRenderContext
}): Promise<{
Component: React.ComponentType
seedData: CacheNodeSeedData
styles: React.ReactNode
}> {
const {
......@@ -286,9 +286,17 @@ export async function createComponentTree({
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.
const parallelRouteMap = await Promise.all(
Object.keys(parallelRoutes).map(
async (parallelRouteKey): Promise<[string, React.ReactNode]> => {
async (
parallelRouteKey
): Promise<[string, React.ReactNode, CacheNodeSeedData | null]> => {
const isChildrenRouteKey = parallelRouteKey === 'children'
const currentSegmentPath: FlightSegmentPath = firstItem
? [parallelRouteKey]
......@@ -306,6 +314,7 @@ export async function createComponentTree({
// 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
......@@ -317,7 +326,7 @@ export async function createComponentTree({
)
) {
// Create the child component
const { Component: ChildComponent, styles: childComponentStyles } =
const { seedData, styles: childComponentStyles } =
await createComponentTree({
createSegmentPath: (child) => {
return createSegmentPath([...currentSegmentPath, ...child])
......@@ -334,7 +343,8 @@ export async function createComponentTree({
})
currentStyles = childComponentStyles
initialChildNode = <ChildComponent />
initialChildNode = seedData[2]
childCacheNodeSeedData = seedData
}
// This is turned back into an object below.
......@@ -367,24 +377,32 @@ export async function createComponentTree({
childPropSegment={childPropSegment}
styles={currentStyles}
/>,
childCacheNodeSeedData,
]
}
)
)
// Convert the parallel route map into an object after all promises have been resolved.
const parallelRouteComponents = parallelRouteMap.reduce(
(list, [parallelRouteKey, Comp]) => {
list[parallelRouteKey] = Comp
return list
},
{} as { [key: string]: React.ReactNode }
)
let parallelRouteProps: { [key: string]: React.ReactNode } = {}
let parallelRouteCacheNodeSeedData: {
[key: string]: CacheNodeSeedData | null
} = {}
for (const parallelRoute of parallelRouteMap) {
const [parallelRouteKey, parallelRouteProp, flightData] = parallelRoute
parallelRouteProps[parallelRouteKey] = parallelRouteProp
parallelRouteCacheNodeSeedData[parallelRouteKey] = flightData
}
// 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 {
Component: () => <>{parallelRouteComponents.children}</>,
// 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}</>],
styles: layerAssets,
}
}
......@@ -416,7 +434,7 @@ export async function createComponentTree({
}
const props = {
...parallelRouteComponents,
...parallelRouteProps,
...notFoundComponent,
// TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list.
// Params are always the current params that apply to the layout
......@@ -435,6 +453,9 @@ 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)
......@@ -442,21 +463,22 @@ export async function createComponentTree({
}
return {
Component: () => {
return (
<>
{isPage ? metadataOutlet : null}
{/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */}
{isPage && isClientComponent ? (
<StaticGenerationSearchParamsBailoutProvider
propsForComponent={props}
Component={Component}
isStaticGeneration={staticGenerationStore.isStaticGeneration}
/>
) : (
<Component {...props} />
)}
{/* This null is currently critical. The wrapped Component can render null and if there was not fragment
seedData: [
actualSegment,
parallelRouteCacheNodeSeedData,
<>
{isPage ? metadataOutlet : null}
{/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */}
{isPage && isClientComponent ? (
<StaticGenerationSearchParamsBailoutProvider
propsForComponent={props}
Component={Component}
isStaticGeneration={staticGenerationStore.isStaticGeneration}
/>
) : (
<Component {...props} />
)}
{/* This null is currently critical. The wrapped Component can render null and if there was not fragment
surrounding it this would look like a pending tree data state on the client which will cause an errror
and break the app. Long-term we need to move away from using null as a partial tree identifier since it
is a valid return type for the components we wrap. Once we make this change we can safely remove the
......@@ -464,10 +486,9 @@ export async function createComponentTree({
If the Component above renders null the actual treedata will look like `[null, null]`. If we remove the extra
null it will look like `null` (the array is elided) and this is what confuses the client router.
TODO-APP update router to use a Symbol for partial tree detection */}
{null}
</>
)
},
{null}
</>,
],
styles: layerAssets,
}
}
......@@ -62,6 +62,21 @@ export type FlightSegmentPath =
parallelRouterKey: string
]
/**
* Represents a tree of segments and the Flight data (i.e. React nodes) that
* correspond to each one. The tree is isomorphic to the FlightRouterState;
* however in the future we want to be able to fetch arbitrary partial segments
* without having to fetch all its children. So this response format will
* likely change.
*/
export type CacheNodeSeedData = [
segment: Segment,
parallelRoutes: {
[parallelRouterKey: string]: CacheNodeSeedData | null
} | null,
node: React.ReactNode | null
]
export type FlightDataPath =
// Uses `any` as repeating pattern can't be typed.
| any[]
......
......@@ -136,9 +136,12 @@ export async function walkTreeWithFlightRouterState({
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 { Component } = await createComponentTree(
const { seedData } = await createComponentTree(
// This ensures flightRouterPath is valid and filters down the tree
{
ctx,
......@@ -155,8 +158,8 @@ export async function walkTreeWithFlightRouterState({
metadataOutlet,
}
)
return <Component />
const componentNode = seedData[2]
return componentNode
}),
shouldSkipComponentTree
? null
......
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