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({ ...@@ -255,14 +255,14 @@ function Router({
initialHead, initialHead,
initialTree, initialTree,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData,
assetPrefix, assetPrefix,
}: AppRouterProps) { }: AppRouterProps) {
const initialState = useMemo( const initialState = useMemo(
() => () =>
createInitialRouterState({ createInitialRouterState({
buildId, buildId,
children, initialSeedData,
initialCanonicalUrl, initialCanonicalUrl,
initialTree, initialTree,
initialParallelRoutes, initialParallelRoutes,
...@@ -270,7 +270,7 @@ function Router({ ...@@ -270,7 +270,7 @@ function Router({
location: !isServer ? window.location : null, location: !isServer ? window.location : null,
initialHead, initialHead,
}), }),
[buildId, children, initialCanonicalUrl, initialTree, initialHead] [buildId, initialSeedData, initialCanonicalUrl, initialTree, initialHead]
) )
const [reducerState, dispatch, sync] = const [reducerState, dispatch, sync] =
useReducerWithReduxDevtools(initialState) useReducerWithReduxDevtools(initialState)
......
...@@ -314,7 +314,6 @@ function InnerLayoutRouter({ ...@@ -314,7 +314,6 @@ function InnerLayoutRouter({
parallelRouterKey, parallelRouterKey,
url, url,
childNodes, childNodes,
initialChildNode,
segmentPath, segmentPath,
tree, tree,
// TODO-APP: implement `<Offscreen>` when available. // TODO-APP: implement `<Offscreen>` when available.
...@@ -324,7 +323,6 @@ function InnerLayoutRouter({ ...@@ -324,7 +323,6 @@ function InnerLayoutRouter({
parallelRouterKey: string parallelRouterKey: string
url: string url: string
childNodes: ChildSegmentMap childNodes: ChildSegmentMap
initialChildNode: React.ReactNode | null
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
tree: FlightRouterState tree: FlightRouterState
isActive: boolean isActive: boolean
...@@ -340,39 +338,6 @@ function InnerLayoutRouter({ ...@@ -340,39 +338,6 @@ function InnerLayoutRouter({
// Read segment path from the parallel router cache node. // Read segment path from the parallel router cache node.
let childNode = childNodes.get(cacheKey) 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. // When childNode is not available during rendering client-side we need to fetch it from the server.
if (!childNode || childNode.status === CacheStates.LAZY_INITIALIZED) { if (!childNode || childNode.status === CacheStates.LAZY_INITIALIZED) {
/** /**
...@@ -503,8 +468,6 @@ function LoadingBoundary({ ...@@ -503,8 +468,6 @@ function LoadingBoundary({
export default function OuterLayoutRouter({ export default function OuterLayoutRouter({
parallelRouterKey, parallelRouterKey,
segmentPath, segmentPath,
initialChildNode,
childPropSegment,
error, error,
errorStyles, errorStyles,
errorScripts, errorScripts,
...@@ -521,8 +484,6 @@ export default function OuterLayoutRouter({ ...@@ -521,8 +484,6 @@ export default function OuterLayoutRouter({
}: { }: {
parallelRouterKey: string parallelRouterKey: string
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
initialChildNode: React.ReactNode | null
childPropSegment: Segment
error: ErrorComponent error: ErrorComponent
errorStyles: React.ReactNode | undefined errorStyles: React.ReactNode | undefined
errorScripts: React.ReactNode | undefined errorScripts: React.ReactNode | undefined
...@@ -570,10 +531,6 @@ export default function OuterLayoutRouter({ ...@@ -570,10 +531,6 @@ export default function OuterLayoutRouter({
<> <>
{styles} {styles}
{preservedSegments.map((preservedSegment) => { {preservedSegments.map((preservedSegment) => {
const isChildPropSegment = matchSegment(
preservedSegment,
childPropSegment
)
const preservedSegmentValue = getSegmentValue(preservedSegment) const preservedSegmentValue = getSegmentValue(preservedSegment)
const cacheKey = createRouterCacheKey(preservedSegment) const cacheKey = createRouterCacheKey(preservedSegment)
...@@ -612,9 +569,6 @@ export default function OuterLayoutRouter({ ...@@ -612,9 +569,6 @@ export default function OuterLayoutRouter({
url={url} url={url}
tree={tree} tree={tree}
childNodes={childNodesForParallelRouter!} childNodes={childNodesForParallelRouter!}
initialChildNode={
isChildPropSegment ? initialChildNode : null
}
segmentPath={segmentPath} segmentPath={segmentPath}
cacheKey={cacheKey} cacheKey={cacheKey}
isActive={ isActive={
......
...@@ -11,21 +11,22 @@ export function applyFlightData( ...@@ -11,21 +11,22 @@ export function applyFlightData(
wasPrefetched: boolean = false wasPrefetched: boolean = false
): boolean { ): boolean {
// The one before last item is the router state tree patch // The one before last item is the router state tree patch
const [treePatch, subTreeData, head /* , cacheNodeSeedData */] = const [treePatch, cacheNodeSeedData, head] = flightDataPath.slice(-3)
flightDataPath.slice(-4)
// Handles case where prefetch only returns the router tree patch without rendered components. // Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData === null) { if (cacheNodeSeedData === null) {
return false return false
} }
if (flightDataPath.length === 4) { if (flightDataPath.length === 3) {
const subTreeData = cacheNodeSeedData[2]
cache.status = CacheStates.READY cache.status = CacheStates.READY
cache.subTreeData = subTreeData cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead( fillLazyItemsTillLeafWithHead(
cache, cache,
existingCache, existingCache,
treePatch, treePatch,
cacheNodeSeedData,
head, head,
wasPrefetched wasPrefetched
) )
......
...@@ -33,11 +33,10 @@ const getFlightData = (): FlightData => { ...@@ -33,11 +33,10 @@ const getFlightData = (): FlightData => {
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>About Page!</h1>, ['about', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
} }
...@@ -53,8 +52,8 @@ describe('applyRouterStatePatchToTree', () => { ...@@ -53,8 +52,8 @@ describe('applyRouterStatePatchToTree', () => {
// Mirrors the way router-reducer values are passed in. // Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0] const flightDataPath = flightData[0]
const [treePatch /*, subTreeData, head*/] = flightDataPath.slice(-4) const [treePatch /*, cacheNodeSeedData, head*/] = flightDataPath.slice(-3)
const flightSegmentPath = flightDataPath.slice(0, -5) const flightSegmentPath = flightDataPath.slice(0, -4)
const newRouterStateTree = applyRouterStatePatchToTree( const newRouterStateTree = applyRouterStatePatchToTree(
['', ...flightSegmentPath], ['', ...flightSegmentPath],
......
...@@ -37,7 +37,7 @@ describe('createInitialRouterState', () => { ...@@ -37,7 +37,7 @@ describe('createInitialRouterState', () => {
buildId, buildId,
initialTree, initialTree,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -48,7 +48,7 @@ describe('createInitialRouterState', () => { ...@@ -48,7 +48,7 @@ describe('createInitialRouterState', () => {
buildId, buildId,
initialTree, initialTree,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
......
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import type { CacheNode } 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 { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import { createHrefFromUrl } from './create-href-from-url' import { createHrefFromUrl } from './create-href-from-url'
...@@ -11,7 +14,7 @@ export interface InitialRouterStateParameters { ...@@ -11,7 +14,7 @@ export interface InitialRouterStateParameters {
buildId: string buildId: string
initialTree: FlightRouterState initialTree: FlightRouterState
initialCanonicalUrl: string initialCanonicalUrl: string
children: ReactNode initialSeedData: CacheNodeSeedData
initialParallelRoutes: CacheNode['parallelRoutes'] initialParallelRoutes: CacheNode['parallelRoutes']
isServer: boolean isServer: boolean
location: Location | null location: Location | null
...@@ -21,24 +24,32 @@ export interface InitialRouterStateParameters { ...@@ -21,24 +24,32 @@ export interface InitialRouterStateParameters {
export function createInitialRouterState({ export function createInitialRouterState({
buildId, buildId,
initialTree, initialTree,
children, initialSeedData,
initialCanonicalUrl, initialCanonicalUrl,
initialParallelRoutes, initialParallelRoutes,
isServer, isServer,
location, location,
initialHead, initialHead,
}: InitialRouterStateParameters) { }: InitialRouterStateParameters) {
const subTreeData = initialSeedData[2]
const cache: CacheNode = { const cache: CacheNode = {
status: CacheStates.READY, status: CacheStates.READY,
data: null, 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. // 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, parallelRoutes: isServer ? new Map() : initialParallelRoutes,
} }
// When the cache hasn't been seeded yet we fill the cache with the head. // When the cache hasn't been seeded yet we fill the cache with the head.
if (initialParallelRoutes === null || initialParallelRoutes.size === 0) { if (initialParallelRoutes === null || initialParallelRoutes.size === 0) {
fillLazyItemsTillLeafWithHead(cache, undefined, initialTree, initialHead) fillLazyItemsTillLeafWithHead(
cache,
undefined,
initialTree,
initialSeedData,
initialHead
)
} }
return { return {
......
...@@ -17,7 +17,7 @@ const getFlightData = (): FlightData => { ...@@ -17,7 +17,7 @@ const getFlightData = (): FlightData => {
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>SubTreeData Injected!</h1>, ['about', null, <h1>SubTreeData Injected!</h1>],
<> <>
<title>Head Injected!</title> <title>Head Injected!</title>
</>, </>,
......
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } 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 { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head' import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import { createRouterCacheKey } from './create-router-cache-key' import { createRouterCacheKey } from './create-router-cache-key'
...@@ -14,7 +17,7 @@ export function fillCacheWithNewSubTreeData( ...@@ -14,7 +17,7 @@ export function fillCacheWithNewSubTreeData(
flightDataPath: FlightDataPath, flightDataPath: FlightDataPath,
wasPrefetched?: boolean wasPrefetched?: boolean
): void { ): void {
const isLastEntry = flightDataPath.length <= 6 const isLastEntry = flightDataPath.length <= 5
const [parallelRouteKey, segment] = flightDataPath const [parallelRouteKey, segment] = flightDataPath
const cacheKey = createRouterCacheKey(segment) const cacheKey = createRouterCacheKey(segment)
...@@ -43,10 +46,12 @@ export function fillCacheWithNewSubTreeData( ...@@ -43,10 +46,12 @@ export function fillCacheWithNewSubTreeData(
!childCacheNode.data || !childCacheNode.data ||
childCacheNode === existingChildCacheNode childCacheNode === existingChildCacheNode
) { ) {
const seedData: CacheNodeSeedData = flightDataPath[3]
const subTreeData = seedData[2]
childCacheNode = { childCacheNode = {
status: CacheStates.READY, status: CacheStates.READY,
data: null, data: null,
subTreeData: flightDataPath[3], subTreeData,
// Ensure segments other than the one we got data for are preserved. // Ensure segments other than the one we got data for are preserved.
parallelRoutes: existingChildCacheNode parallelRoutes: existingChildCacheNode
? new Map(existingChildCacheNode.parallelRoutes) ? new Map(existingChildCacheNode.parallelRoutes)
...@@ -65,6 +70,7 @@ export function fillCacheWithNewSubTreeData( ...@@ -65,6 +70,7 @@ export function fillCacheWithNewSubTreeData(
childCacheNode, childCacheNode,
existingChildCacheNode, existingChildCacheNode,
flightDataPath[2], flightDataPath[2],
seedData,
flightDataPath[4], flightDataPath[4],
wasPrefetched wasPrefetched
) )
......
...@@ -26,11 +26,10 @@ const getFlightData = (): FlightData => { ...@@ -26,11 +26,10 @@ const getFlightData = (): FlightData => {
null, null,
true, true,
], ],
<h1>About Page!</h1>, ['', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
} }
...@@ -88,9 +87,14 @@ describe('fillLazyItemsTillLeafWithHead', () => { ...@@ -88,9 +87,14 @@ describe('fillLazyItemsTillLeafWithHead', () => {
// Mirrors the way router-reducer values are passed in. // Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0] const flightDataPath = flightData[0]
// eslint-disable-next-line @typescript-eslint/no-unused-vars const [treePatch, cacheNodeSeedData, head] = flightDataPath.slice(-3)
const [treePatch, _subTreeData, head] = flightDataPath.slice(-4) fillLazyItemsTillLeafWithHead(
fillLazyItemsTillLeafWithHead(cache, existingCache, treePatch, head) cache,
existingCache,
treePatch,
cacheNodeSeedData,
head
)
const expectedCache: CacheNode = { const expectedCache: CacheNode = {
data: null, data: null,
......
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } 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' import { createRouterCacheKey } from './create-router-cache-key'
export function fillLazyItemsTillLeafWithHead( export function fillLazyItemsTillLeafWithHead(
newCache: CacheNode, newCache: CacheNode,
existingCache: CacheNode | undefined, existingCache: CacheNode | undefined,
routerState: FlightRouterState, routerState: FlightRouterState,
cacheNodeSeedData: CacheNodeSeedData | null,
head: React.ReactNode, head: React.ReactNode,
wasPrefetched?: boolean wasPrefetched?: boolean
): void { ): void {
...@@ -21,26 +25,58 @@ export function fillLazyItemsTillLeafWithHead( ...@@ -21,26 +25,58 @@ export function fillLazyItemsTillLeafWithHead(
const segmentForParallelRoute = parallelRouteState[0] const segmentForParallelRoute = parallelRouteState[0]
const cacheKey = createRouterCacheKey(segmentForParallelRoute) 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) { if (existingCache) {
const existingParallelRoutesCacheNode = const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key) existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) { if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode) let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
const existingCacheNode = parallelRouteCacheNode.get(cacheKey) const existingCacheNode = parallelRouteCacheNode.get(cacheKey)
const newCacheNode: CacheNode = let newCacheNode: CacheNode
wasPrefetched && existingCacheNode if (parallelSeedData !== null) {
? ({ // New data was sent from the server.
status: existingCacheNode.status, const seedNode = parallelSeedData[2]
data: existingCacheNode.data, newCacheNode = {
subTreeData: existingCacheNode.subTreeData, status: CacheStates.READY,
parallelRoutes: new Map(existingCacheNode.parallelRoutes), data: null,
} as CacheNode) subTreeData: seedNode,
: { parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
status: CacheStates.LAZY_INITIALIZED, }
data: null, } else if (wasPrefetched && existingCacheNode) {
subTreeData: null, // No new data was sent from the server, but the existing cache node
parallelRoutes: new Map(existingCacheNode?.parallelRoutes), // 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. // Overrides the cache key with the new cache node.
parallelRouteCacheNode.set(cacheKey, newCacheNode) parallelRouteCacheNode.set(cacheKey, newCacheNode)
// Traverse deeper to apply the head / fill lazy items till the head. // Traverse deeper to apply the head / fill lazy items till the head.
...@@ -48,6 +84,7 @@ export function fillLazyItemsTillLeafWithHead( ...@@ -48,6 +84,7 @@ export function fillLazyItemsTillLeafWithHead(
newCacheNode, newCacheNode,
existingCacheNode, existingCacheNode,
parallelRouteState, parallelRouteState,
parallelSeedData ? parallelSeedData : null,
head, head,
wasPrefetched wasPrefetched
) )
...@@ -57,11 +94,25 @@ export function fillLazyItemsTillLeafWithHead( ...@@ -57,11 +94,25 @@ export function fillLazyItemsTillLeafWithHead(
} }
} }
const newCacheNode: CacheNode = { let newCacheNode: CacheNode
status: CacheStates.LAZY_INITIALIZED, if (parallelSeedData !== null) {
data: null, // New data was sent from the server.
subTreeData: null, const seedNode = parallelSeedData[2]
parallelRoutes: new Map(), 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) const existingParallelRoutes = newCache.parallelRoutes.get(key)
...@@ -75,6 +126,7 @@ export function fillLazyItemsTillLeafWithHead( ...@@ -75,6 +126,7 @@ export function fillLazyItemsTillLeafWithHead(
newCacheNode, newCacheNode,
undefined, undefined,
parallelRouteState, parallelRouteState,
parallelSeedData,
head, head,
wasPrefetched wasPrefetched
) )
......
...@@ -18,11 +18,10 @@ const getFlightData = (): FlightData => { ...@@ -18,11 +18,10 @@ const getFlightData = (): FlightData => {
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>About Page!</h1>, ['about', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
} }
...@@ -80,7 +79,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => { ...@@ -80,7 +79,7 @@ describe('invalidateCacheBelowFlightSegmentPath', () => {
// Mirrors the way router-reducer values are passed in. // Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0] 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. // @ts-expect-error TODO-APP: investigate why this is not a TS error in router-reducer.
cache.status = CacheStates.READY cache.status = CacheStates.READY
......
...@@ -59,7 +59,7 @@ function fastRefreshReducerImpl( ...@@ -59,7 +59,7 @@ function fastRefreshReducerImpl(
for (const flightDataPath of flightData) { for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned // 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 // TODO-APP: handle this case better
console.log('REFRESH FAILED') console.log('REFRESH FAILED')
return state return state
......
...@@ -28,11 +28,10 @@ const flightData: FlightData = [ ...@@ -28,11 +28,10 @@ const flightData: FlightData = [
children: ['__PAGE__', {}], children: ['__PAGE__', {}],
}, },
], ],
<h1>About Page!</h1>, ['about', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
...@@ -57,14 +56,17 @@ const demographicsFlightData: FlightData = [ ...@@ -57,14 +56,17 @@ const demographicsFlightData: FlightData = [
null, null,
true, true,
], ],
<html> [
<head></head> '',
<body>Root layout from response</body> null,
</html>, <html>
<head></head>
<body>Root layout from response</body>
</html>,
],
<> <>
<title>Demographics Head</title> <title>Demographics Head</title>
</>, </>,
null,
], ],
] ]
...@@ -173,7 +175,7 @@ describe('navigateReducer', () => { ...@@ -173,7 +175,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -375,7 +377,7 @@ describe('navigateReducer', () => { ...@@ -375,7 +377,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -386,7 +388,7 @@ describe('navigateReducer', () => { ...@@ -386,7 +388,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -567,7 +569,7 @@ describe('navigateReducer', () => { ...@@ -567,7 +569,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -578,7 +580,7 @@ describe('navigateReducer', () => { ...@@ -578,7 +580,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -726,7 +728,7 @@ describe('navigateReducer', () => { ...@@ -726,7 +728,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -737,7 +739,7 @@ describe('navigateReducer', () => { ...@@ -737,7 +739,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -885,7 +887,7 @@ describe('navigateReducer', () => { ...@@ -885,7 +887,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -896,7 +898,7 @@ describe('navigateReducer', () => { ...@@ -896,7 +898,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking#hash', 'https://localhost') as any, location: new URL('/linking#hash', 'https://localhost') as any,
...@@ -1048,7 +1050,7 @@ describe('navigateReducer', () => { ...@@ -1048,7 +1050,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -1063,7 +1065,7 @@ describe('navigateReducer', () => { ...@@ -1063,7 +1065,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -1338,7 +1340,7 @@ describe('navigateReducer', () => { ...@@ -1338,7 +1340,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/parallel-tab-bar', 'https://localhost') as any, location: new URL('/parallel-tab-bar', 'https://localhost') as any,
...@@ -1349,7 +1351,7 @@ describe('navigateReducer', () => { ...@@ -1349,7 +1351,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/parallel-tab-bar', 'https://localhost') as any, location: new URL('/parallel-tab-bar', 'https://localhost') as any,
...@@ -1554,7 +1556,7 @@ describe('navigateReducer', () => { ...@@ -1554,7 +1556,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking#hash', 'https://localhost') as any, location: new URL('/linking#hash', 'https://localhost') as any,
...@@ -1704,7 +1706,7 @@ describe('navigateReducer', () => { ...@@ -1704,7 +1706,7 @@ describe('navigateReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
......
...@@ -175,10 +175,10 @@ export function navigateReducer( ...@@ -175,10 +175,10 @@ export function navigateReducer(
for (const flightDataPath of flightData) { for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice( const flightSegmentPath = flightDataPath.slice(
0, 0,
-5 -4
) as unknown as FlightSegmentPath ) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch // 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 '' // TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath] const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath]
......
...@@ -23,11 +23,10 @@ jest.mock('../fetch-server-response', () => { ...@@ -23,11 +23,10 @@ jest.mock('../fetch-server-response', () => {
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>About Page!</h1>, ['about', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
return { return {
...@@ -118,7 +117,7 @@ describe('prefetchReducer', () => { ...@@ -118,7 +117,7 @@ describe('prefetchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -260,7 +259,7 @@ describe('prefetchReducer', () => { ...@@ -260,7 +259,7 @@ describe('prefetchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -271,7 +270,7 @@ describe('prefetchReducer', () => { ...@@ -271,7 +270,7 @@ describe('prefetchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
......
...@@ -27,16 +27,19 @@ jest.mock('../fetch-server-response', () => { ...@@ -27,16 +27,19 @@ jest.mock('../fetch-server-response', () => {
null, null,
true, true,
], ],
<html> [
<head></head> '',
<body> null,
<h1>Linking Page!</h1> <html>
</body> <head></head>
</html>, <body>
<h1>Linking Page!</h1>
</body>
</html>,
],
<> <>
<title>Linking page!</title> <title>Linking page!</title>
</>, </>,
null,
], ],
] ]
return { return {
...@@ -125,7 +128,7 @@ describe('refreshReducer', () => { ...@@ -125,7 +128,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -275,7 +278,7 @@ describe('refreshReducer', () => { ...@@ -275,7 +278,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -286,7 +289,7 @@ describe('refreshReducer', () => { ...@@ -286,7 +289,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -463,7 +466,7 @@ describe('refreshReducer', () => { ...@@ -463,7 +466,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -474,7 +477,7 @@ describe('refreshReducer', () => { ...@@ -474,7 +477,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -697,7 +700,7 @@ describe('refreshReducer', () => { ...@@ -697,7 +700,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -710,7 +713,7 @@ describe('refreshReducer', () => { ...@@ -710,7 +713,7 @@ describe('refreshReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
......
...@@ -57,8 +57,8 @@ export function refreshReducer( ...@@ -57,8 +57,8 @@ export function refreshReducer(
cache.data = null cache.data = null
for (const flightDataPath of flightData) { for (const flightDataPath of flightData) {
// FlightDataPath with more than four items means unexpected Flight data was returned // 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 // TODO-APP: handle this case better
console.log('REFRESH FAILED') console.log('REFRESH FAILED')
return state return state
...@@ -95,10 +95,11 @@ export function refreshReducer( ...@@ -95,10 +95,11 @@ export function refreshReducer(
} }
// The one before last item is the router state tree patch // 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. // 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.status = CacheStates.READY
cache.subTreeData = subTreeData cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead( fillLazyItemsTillLeafWithHead(
...@@ -106,6 +107,7 @@ export function refreshReducer( ...@@ -106,6 +107,7 @@ export function refreshReducer(
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache. // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, undefined,
treePatch, treePatch,
cacheNodeSeedData,
head head
) )
mutable.cache = cache mutable.cache = cache
......
...@@ -84,7 +84,7 @@ describe('serverPatchReducer', () => { ...@@ -84,7 +84,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -239,7 +239,7 @@ describe('serverPatchReducer', () => { ...@@ -239,7 +239,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
...@@ -249,7 +249,7 @@ describe('serverPatchReducer', () => { ...@@ -249,7 +249,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking', 'https://localhost') as any, location: new URL('/linking', 'https://localhost') as any,
......
...@@ -206,7 +206,7 @@ export function serverActionReducer( ...@@ -206,7 +206,7 @@ export function serverActionReducer(
for (const flightDataPath of flightData) { for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned // 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 // TODO-APP: handle this case better
console.log('SERVER ACTION APPLY FAILED') console.log('SERVER ACTION APPLY FAILED')
return state return state
...@@ -235,7 +235,9 @@ export function serverActionReducer( ...@@ -235,7 +235,9 @@ export function serverActionReducer(
} }
// The one before last item is the router state tree patch // 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. // Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) { if (subTreeData !== null) {
...@@ -246,6 +248,7 @@ export function serverActionReducer( ...@@ -246,6 +248,7 @@ export function serverActionReducer(
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache. // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, undefined,
treePatch, treePatch,
cacheNodeSeedData,
head head
) )
mutable.cache = cache mutable.cache = cache
......
...@@ -26,11 +26,10 @@ jest.mock('../fetch-server-response', () => { ...@@ -26,11 +26,10 @@ jest.mock('../fetch-server-response', () => {
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>About Page!</h1>, ['about', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
return { return {
...@@ -58,11 +57,10 @@ const flightDataForPatch: FlightData = [ ...@@ -58,11 +57,10 @@ const flightDataForPatch: FlightData = [
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>Somewhere Page!</h1>, ['somewhere-else', null, <h1>Somewhere Page!</h1>],
<> <>
<title>Somewhere page!</title> <title>Somewhere page!</title>
</>, </>,
null,
], ],
] ]
...@@ -150,7 +148,7 @@ describe('serverPatchReducer', () => { ...@@ -150,7 +148,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking/about', 'https://localhost') as any, location: new URL('/linking/about', 'https://localhost') as any,
...@@ -330,7 +328,7 @@ describe('serverPatchReducer', () => { ...@@ -330,7 +328,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking/about', 'https://localhost') as any, location: new URL('/linking/about', 'https://localhost') as any,
...@@ -341,7 +339,7 @@ describe('serverPatchReducer', () => { ...@@ -341,7 +339,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL('/linking/about', 'https://localhost') as any, location: new URL('/linking/about', 'https://localhost') as any,
...@@ -518,7 +516,7 @@ describe('serverPatchReducer', () => { ...@@ -518,7 +516,7 @@ describe('serverPatchReducer', () => {
initialTree, initialTree,
initialHead: null, initialHead: null,
initialCanonicalUrl, initialCanonicalUrl,
children, initialSeedData: ['', null, children],
initialParallelRoutes, initialParallelRoutes,
isServer: false, isServer: false,
location: new URL(initialCanonicalUrl, 'https://localhost') as any, location: new URL(initialCanonicalUrl, 'https://localhost') as any,
......
...@@ -49,10 +49,10 @@ export function serverPatchReducer( ...@@ -49,10 +49,10 @@ export function serverPatchReducer(
let currentCache = state.cache let currentCache = state.cache
for (const flightDataPath of flightData) { for (const flightDataPath of flightData) {
// Slices off the last segment (which is at -5) as it doesn't exist in the tree yet // Slices off the last segment (which is at -4) as it doesn't exist in the tree yet
const flightSegmentPath = flightDataPath.slice(0, -5) const flightSegmentPath = flightDataPath.slice(0, -4)
const [treePatch] = flightDataPath.slice(-4, -3) const [treePatch] = flightDataPath.slice(-3, -2)
const newTree = applyRouterStatePatchToTree( const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove '' // TODO-APP: remove ''
['', ...flightSegmentPath], ['', ...flightSegmentPath],
......
...@@ -35,11 +35,10 @@ describe('shouldHardNavigate', () => { ...@@ -35,11 +35,10 @@ describe('shouldHardNavigate', () => {
children: ['', {}], children: ['', {}],
}, },
], ],
<h1>About Page!</h1>, ['about', null, <h1>About Page!</h1>],
<> <>
<title>About page!</title> <title>About page!</title>
</>, </>,
null,
], ],
] ]
} }
...@@ -51,7 +50,7 @@ describe('shouldHardNavigate', () => { ...@@ -51,7 +50,7 @@ describe('shouldHardNavigate', () => {
// Mirrors the way router-reducer values are passed in. // Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0] const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4) const flightSegmentPath = flightDataPath.slice(0, -3)
const result = shouldHardNavigate( const result = shouldHardNavigate(
['', ...flightSegmentPath], ['', ...flightSegmentPath],
...@@ -95,8 +94,7 @@ describe('shouldHardNavigate', () => { ...@@ -95,8 +94,7 @@ describe('shouldHardNavigate', () => {
children: ['', {}], children: ['', {}],
}, },
], ],
null, [['id', '123', 'd'], null, null],
null,
null, null,
], ],
] ]
...@@ -109,7 +107,7 @@ describe('shouldHardNavigate', () => { ...@@ -109,7 +107,7 @@ describe('shouldHardNavigate', () => {
// Mirrors the way router-reducer values are passed in. // Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0] const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4) const flightSegmentPath = flightDataPath.slice(0, -3)
const result = shouldHardNavigate( const result = shouldHardNavigate(
['', ...flightSegmentPath], ['', ...flightSegmentPath],
...@@ -153,8 +151,7 @@ describe('shouldHardNavigate', () => { ...@@ -153,8 +151,7 @@ describe('shouldHardNavigate', () => {
children: ['', {}], children: ['', {}],
}, },
], ],
null, [['id', '123', 'd'], null, null],
null,
null, null,
], ],
] ]
...@@ -167,7 +164,7 @@ describe('shouldHardNavigate', () => { ...@@ -167,7 +164,7 @@ describe('shouldHardNavigate', () => {
// Mirrors the way router-reducer values are passed in. // Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0] const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4) const flightSegmentPath = flightDataPath.slice(0, -3)
const result = shouldHardNavigate( const result = shouldHardNavigate(
['', ...flightSegmentPath], ['', ...flightSegmentPath],
......
...@@ -7,6 +7,7 @@ import type { ...@@ -7,6 +7,7 @@ import type {
FlightSegmentPath, FlightSegmentPath,
RenderOpts, RenderOpts,
Segment, Segment,
CacheNodeSeedData,
} from './types' } from './types'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type { RequestStore } from '../../client/components/request-async-storage.external'
...@@ -359,7 +360,7 @@ function createServerComponentsRenderer( ...@@ -359,7 +360,7 @@ function createServerComponentsRenderer(
asNotFound: props.asNotFound, asNotFound: props.asNotFound,
metadataOutlet: <MetadataOutlet />, metadataOutlet: <MetadataOutlet />,
}) })
const componentTree = seedData[2]
return ( return (
<> <>
{styles} {styles}
...@@ -370,12 +371,7 @@ function createServerComponentsRenderer( ...@@ -370,12 +371,7 @@ function createServerComponentsRenderer(
// This is the router state tree. // This is the router state tree.
initialTree={initialTree} initialTree={initialTree}
// This is the tree of React nodes that are seeded into the cache // 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 initialSeedData={seedData}
// 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 && (
...@@ -386,9 +382,7 @@ function createServerComponentsRenderer( ...@@ -386,9 +382,7 @@ function createServerComponentsRenderer(
</> </>
} }
globalErrorComponent={GlobalError} globalErrorComponent={GlobalError}
> />
{componentTree}
</AppRouter>
</> </>
) )
}, options) }, options)
...@@ -923,6 +917,14 @@ async function renderToHTMLOrFlightImpl( ...@@ -923,6 +917,14 @@ async function renderToHTMLOrFlightImpl(
// For metadata notFound error there's no global not found boundary on top // For metadata notFound error there's no global not found boundary on top
// so we create a not found page with AppRouter // 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 ( return (
<AppRouter <AppRouter
buildId={buildId} buildId={buildId}
...@@ -931,12 +933,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -931,12 +933,8 @@ async function renderToHTMLOrFlightImpl(
initialTree={initialTree} initialTree={initialTree}
initialHead={head} initialHead={head}
globalErrorComponent={GlobalError} globalErrorComponent={GlobalError}
> initialSeedData={initialSeedData}
<html id="__next_error__"> />
<head></head>
<body></body>
</html>
</AppRouter>
) )
}, },
{ {
......
...@@ -4,8 +4,6 @@ import { isClientReference } from '../../lib/client-reference' ...@@ -4,8 +4,6 @@ import { isClientReference } from '../../lib/client-reference'
import { getLayoutOrPageModule } from '../lib/app-dir-module' import { getLayoutOrPageModule } from '../lib/app-dir-module'
import type { LoaderTree } from '../lib/app-dir-module' import type { LoaderTree } from '../lib/app-dir-module'
import { interopDefault } from './interop-default' 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 { parseLoaderTree } from './parse-loader-tree'
import type { CreateSegmentPath, AppRenderContext } from './app-render' import type { CreateSegmentPath, AppRenderContext } from './app-render'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts' import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
...@@ -57,7 +55,6 @@ export async function createComponentTree({ ...@@ -57,7 +55,6 @@ export async function createComponentTree({
}, },
pagePath, pagePath,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query,
isPrefetch, isPrefetch,
searchParamsProps, searchParamsProps,
} = ctx } = ctx
...@@ -285,13 +282,9 @@ export async function createComponentTree({ ...@@ -285,13 +282,9 @@ export async function createComponentTree({
// Resolve the segment param // Resolve the segment param
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 //
// TODO: Once we're done refactoring the Flight response type so that all the // TODO: Combine this `map` traversal with the loop below that turns the array
// tree nodes are passed at the root of the response, we'll no longer need to // into an object.
// 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 ( async (
...@@ -304,8 +297,6 @@ export async function createComponentTree({ ...@@ -304,8 +297,6 @@ export async function createComponentTree({
const parallelRoute = parallelRoutes[parallelRouteKey] const parallelRoute = parallelRoutes[parallelRouteKey]
const childSegment = parallelRoute[0]
const childSegmentParam = getDynamicParamFromSegment(childSegment)
const notFoundComponent = const notFoundComponent =
NotFound && isChildrenRouteKey ? <NotFound /> : undefined NotFound && isChildrenRouteKey ? <NotFound /> : undefined
...@@ -313,12 +304,7 @@ export async function createComponentTree({ ...@@ -313,12 +304,7 @@ export async function createComponentTree({
// otherwise we keep rendering for the prefetch. // otherwise we keep rendering for the prefetch.
// 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 childCacheNodeSeedData: CacheNodeSeedData | null = null
let childCacheNodeSeedData = null
const childPropSegment = addSearchParamsIfPageSegment(
childSegmentParam ? childSegmentParam.treeSegment : childSegment,
query
)
if ( if (
!( !(
isPrefetch && isPrefetch &&
...@@ -343,7 +329,6 @@ export async function createComponentTree({ ...@@ -343,7 +329,6 @@ export async function createComponentTree({
}) })
currentStyles = childComponentStyles currentStyles = childComponentStyles
initialChildNode = seedData[2]
childCacheNodeSeedData = seedData childCacheNodeSeedData = seedData
} }
...@@ -370,11 +355,6 @@ export async function createComponentTree({ ...@@ -370,11 +355,6 @@ export async function createComponentTree({
templateScripts={templateScripts} templateScripts={templateScripts}
notFound={notFoundComponent} notFound={notFoundComponent}
notFoundStyles={notFoundStyles} 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} styles={currentStyles}
/>, />,
childCacheNodeSeedData, childCacheNodeSeedData,
...@@ -397,12 +377,16 @@ export async function createComponentTree({ ...@@ -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 // 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 {
// TODO: I don't think the extra fragment is necessary. React treats top seedData: [
// level fragments as transparent, i.e. the runtime behavior should be actualSegment,
// identical even without it. But maybe there's some findDOMNode-related parallelRouteCacheNodeSeedData,
// reason that I'm not aware of, so I'm leaving it as-is out of extreme // TODO: I don't think the extra fragment is necessary. React treats top
// caution, for now. // level fragments as transparent, i.e. the runtime behavior should be
seedData: [actualSegment, null, <>{parallelRouteProps.children}</>], // 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, styles: layerAssets,
} }
} }
...@@ -452,16 +436,6 @@ export async function createComponentTree({ ...@@ -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 { return {
seedData: [ seedData: [
actualSegment, actualSegment,
......
...@@ -86,9 +86,8 @@ export type FlightDataPath = ...@@ -86,9 +86,8 @@ export type FlightDataPath =
...FlightSegmentPath[], ...FlightSegmentPath[],
/* segment of the rendered slice: */ Segment, /* segment of the rendered slice: */ Segment,
/* treePatch */ FlightRouterState, /* treePatch */ FlightRouterState,
/* subTreeData: */ React.ReactNode | null, // Can be null during prefetch if there's no loading component /* cacheNodeSeedData */ CacheNodeSeedData, // Can be null during prefetch if there's no loading component
/* head */ React.ReactNode | null, /* head */ React.ReactNode | null
/* cacheNodeSeedData */ null
] ]
/** /**
......
...@@ -122,68 +122,56 @@ export async function walkTreeWithFlightRouterState({ ...@@ -122,68 +122,56 @@ export async function walkTreeWithFlightRouterState({
flightRouterState && flightRouterState &&
canSegmentBeOverridden(actualSegment, flightRouterState[0]) canSegmentBeOverridden(actualSegment, flightRouterState[0])
? flightRouterState[0] ? flightRouterState[0]
: null : actualSegment
return [ const routerState = createFlightRouterStateFromLoaderTree(
[ // Create router state using the slice of the loaderTree
overriddenSegment ?? actualSegment, loaderTreeToFilter,
createFlightRouterStateFromLoaderTree( getDynamicParamFromSegment,
// Create router state using the slice of the loaderTree query
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),
})
return ( if (shouldSkipComponentTree) {
<> // Send only the router state
{layerAssets} return [[overriddenSegment, routerState, null, null]]
{rscPayloadHead} } else {
</> // Create component tree using the slice of the loaderTree
) const { seedData } = await createComponentTree(
})(), // This ensures flightRouterPath is valid and filters down the tree
null, {
], 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 // 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