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( ...@@ -346,7 +346,7 @@ function createServerComponentsRenderer(
appUsingSizeAdjustment: appUsingSizeAdjustment, appUsingSizeAdjustment: appUsingSizeAdjustment,
}) })
const { Component: ComponentTree, styles } = await createComponentTree({ const { seedData, styles } = await createComponentTree({
ctx, ctx,
createSegmentPath: (child) => child, createSegmentPath: (child) => child,
loaderTree: loaderTreeToRender, loaderTree: loaderTreeToRender,
...@@ -359,7 +359,7 @@ function createServerComponentsRenderer( ...@@ -359,7 +359,7 @@ function createServerComponentsRenderer(
asNotFound: props.asNotFound, asNotFound: props.asNotFound,
metadataOutlet: <MetadataOutlet />, metadataOutlet: <MetadataOutlet />,
}) })
const componentTree = seedData[2]
return ( return (
<> <>
{styles} {styles}
...@@ -367,7 +367,15 @@ function createServerComponentsRenderer( ...@@ -367,7 +367,15 @@ function createServerComponentsRenderer(
buildId={ctx.renderOpts.buildId} buildId={ctx.renderOpts.buildId}
assetPrefix={ctx.assetPrefix} assetPrefix={ctx.assetPrefix}
initialCanonicalUrl={urlPathname} initialCanonicalUrl={urlPathname}
// This is the router state tree.
initialTree={initialTree} 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={ initialHead={
<> <>
{ctx.res.statusCode > 400 && ( {ctx.res.statusCode > 400 && (
...@@ -379,7 +387,7 @@ function createServerComponentsRenderer( ...@@ -379,7 +387,7 @@ function createServerComponentsRenderer(
} }
globalErrorComponent={GlobalError} globalErrorComponent={GlobalError}
> >
<ComponentTree /> {componentTree}
</AppRouter> </AppRouter>
</> </>
) )
......
import type { FlightSegmentPath } from './types' import type { FlightSegmentPath, CacheNodeSeedData } from './types'
import React from 'react' import React from 'react'
import { isClientReference } from '../../lib/client-reference' import { isClientReference } from '../../lib/client-reference'
import { getLayoutOrPageModule } from '../lib/app-dir-module' import { getLayoutOrPageModule } from '../lib/app-dir-module'
...@@ -41,7 +41,7 @@ export async function createComponentTree({ ...@@ -41,7 +41,7 @@ export async function createComponentTree({
metadataOutlet?: React.ReactNode metadataOutlet?: React.ReactNode
ctx: AppRenderContext ctx: AppRenderContext
}): Promise<{ }): Promise<{
Component: React.ComponentType seedData: CacheNodeSeedData
styles: React.ReactNode styles: React.ReactNode
}> { }> {
const { const {
...@@ -286,9 +286,17 @@ export async function createComponentTree({ ...@@ -286,9 +286,17 @@ export async function createComponentTree({
const actualSegment = segmentParam ? segmentParam.treeSegment : segment 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 // 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( const parallelRouteMap = await Promise.all(
Object.keys(parallelRoutes).map( Object.keys(parallelRoutes).map(
async (parallelRouteKey): Promise<[string, React.ReactNode]> => { async (
parallelRouteKey
): Promise<[string, React.ReactNode, CacheNodeSeedData | null]> => {
const isChildrenRouteKey = parallelRouteKey === 'children' const isChildrenRouteKey = parallelRouteKey === 'children'
const currentSegmentPath: FlightSegmentPath = firstItem const currentSegmentPath: FlightSegmentPath = firstItem
? [parallelRouteKey] ? [parallelRouteKey]
...@@ -306,6 +314,7 @@ export async function createComponentTree({ ...@@ -306,6 +314,7 @@ export async function createComponentTree({
// We also want to bail out if there's no Loading component in the tree. // We also want to bail out if there's no Loading component in the tree.
let currentStyles = undefined let currentStyles = undefined
let initialChildNode = null let initialChildNode = null
let childCacheNodeSeedData = null
const childPropSegment = addSearchParamsIfPageSegment( const childPropSegment = addSearchParamsIfPageSegment(
childSegmentParam ? childSegmentParam.treeSegment : childSegment, childSegmentParam ? childSegmentParam.treeSegment : childSegment,
query query
...@@ -317,7 +326,7 @@ export async function createComponentTree({ ...@@ -317,7 +326,7 @@ export async function createComponentTree({
) )
) { ) {
// Create the child component // Create the child component
const { Component: ChildComponent, styles: childComponentStyles } = const { seedData, styles: childComponentStyles } =
await createComponentTree({ await createComponentTree({
createSegmentPath: (child) => { createSegmentPath: (child) => {
return createSegmentPath([...currentSegmentPath, ...child]) return createSegmentPath([...currentSegmentPath, ...child])
...@@ -334,7 +343,8 @@ export async function createComponentTree({ ...@@ -334,7 +343,8 @@ export async function createComponentTree({
}) })
currentStyles = childComponentStyles currentStyles = childComponentStyles
initialChildNode = <ChildComponent /> initialChildNode = seedData[2]
childCacheNodeSeedData = seedData
} }
// This is turned back into an object below. // This is turned back into an object below.
...@@ -367,24 +377,32 @@ export async function createComponentTree({ ...@@ -367,24 +377,32 @@ export async function createComponentTree({
childPropSegment={childPropSegment} childPropSegment={childPropSegment}
styles={currentStyles} styles={currentStyles}
/>, />,
childCacheNodeSeedData,
] ]
} }
) )
) )
// Convert the parallel route map into an object after all promises have been resolved. // Convert the parallel route map into an object after all promises have been resolved.
const parallelRouteComponents = parallelRouteMap.reduce( let parallelRouteProps: { [key: string]: React.ReactNode } = {}
(list, [parallelRouteKey, Comp]) => { let parallelRouteCacheNodeSeedData: {
list[parallelRouteKey] = Comp [key: string]: CacheNodeSeedData | null
return list } = {}
}, for (const parallelRoute of parallelRouteMap) {
{} as { [key: string]: React.ReactNode } 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 // 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) { if (!Component) {
return { 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, styles: layerAssets,
} }
} }
...@@ -416,7 +434,7 @@ export async function createComponentTree({ ...@@ -416,7 +434,7 @@ export async function createComponentTree({
} }
const props = { const props = {
...parallelRouteComponents, ...parallelRouteProps,
...notFoundComponent, ...notFoundComponent,
// TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list. // 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 // Params are always the current params that apply to the layout
...@@ -435,6 +453,9 @@ export async function createComponentTree({ ...@@ -435,6 +453,9 @@ export async function createComponentTree({
} }
// Eagerly execute layout/page component to trigger fetches early. // 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) { if (!isClientComponent) {
Component = await Promise.resolve().then(() => Component = await Promise.resolve().then(() =>
preloadComponent(Component, props) preloadComponent(Component, props)
...@@ -442,21 +463,22 @@ export async function createComponentTree({ ...@@ -442,21 +463,22 @@ export async function createComponentTree({
} }
return { return {
Component: () => { seedData: [
return ( actualSegment,
<> parallelRouteCacheNodeSeedData,
{isPage ? metadataOutlet : null} <>
{/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */} {isPage ? metadataOutlet : null}
{isPage && isClientComponent ? ( {/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */}
<StaticGenerationSearchParamsBailoutProvider {isPage && isClientComponent ? (
propsForComponent={props} <StaticGenerationSearchParamsBailoutProvider
Component={Component} propsForComponent={props}
isStaticGeneration={staticGenerationStore.isStaticGeneration} Component={Component}
/> isStaticGeneration={staticGenerationStore.isStaticGeneration}
) : ( />
<Component {...props} /> ) : (
)} <Component {...props} />
{/* This null is currently critical. The wrapped Component can render null and if there was not fragment )}
{/* 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 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 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 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({ ...@@ -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 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. 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 */} TODO-APP update router to use a Symbol for partial tree detection */}
{null} {null}
</> </>,
) ],
},
styles: layerAssets, styles: layerAssets,
} }
} }
...@@ -62,6 +62,21 @@ export type FlightSegmentPath = ...@@ -62,6 +62,21 @@ export type FlightSegmentPath =
parallelRouterKey: string 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 = export type FlightDataPath =
// Uses `any` as repeating pattern can't be typed. // Uses `any` as repeating pattern can't be typed.
| any[] | any[]
......
...@@ -136,9 +136,12 @@ export async function walkTreeWithFlightRouterState({ ...@@ -136,9 +136,12 @@ export async function walkTreeWithFlightRouterState({
shouldSkipComponentTree shouldSkipComponentTree
? null ? null
: // Create component tree using the slice of the loaderTree : // 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 () => { React.createElement(async () => {
const { Component } = await createComponentTree( const { seedData } = await createComponentTree(
// This ensures flightRouterPath is valid and filters down the tree // This ensures flightRouterPath is valid and filters down the tree
{ {
ctx, ctx,
...@@ -155,8 +158,8 @@ export async function walkTreeWithFlightRouterState({ ...@@ -155,8 +158,8 @@ export async function walkTreeWithFlightRouterState({
metadataOutlet, metadataOutlet,
} }
) )
const componentNode = seedData[2]
return <Component /> return componentNode
}), }),
shouldSkipComponentTree shouldSkipComponentTree
? null ? 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