Unverified Commit d1f18a51 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Move router reducer to separate file (#45236)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 35f68bc6
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import React, { useEffect, useMemo, useCallback } from 'react' import React, { useEffect, useMemo, useCallback } from 'react'
import { createFromFetch } from 'next/dist/compiled/react-server-dom-webpack/client'
import { import {
AppRouterContext, AppRouterContext,
LayoutRouterContext, LayoutRouterContext,
...@@ -21,9 +20,9 @@ import { ...@@ -21,9 +20,9 @@ import {
ACTION_REFRESH, ACTION_REFRESH,
ACTION_RESTORE, ACTION_RESTORE,
ACTION_SERVER_PATCH, ACTION_SERVER_PATCH,
createHrefFromUrl,
reducer, reducer,
} from './reducer' } from './router-reducer/router-reducer'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { import {
SearchParamsContext, SearchParamsContext,
// ParamsContext, // ParamsContext,
...@@ -33,12 +32,16 @@ import { ...@@ -33,12 +32,16 @@ import {
import { useReducerWithReduxDevtools } from './use-reducer-with-devtools' import { useReducerWithReduxDevtools } from './use-reducer-with-devtools'
import { ErrorBoundary } from './error-boundary' import { ErrorBoundary } from './error-boundary'
import { import {
NEXT_ROUTER_PREFETCH, createInitialRouterState,
NEXT_ROUTER_STATE_TREE, InitialRouterStateParameters,
RSC, } from './router-reducer/create-initial-router-state'
} from './app-router-headers' import { fetchServerResponse } from './router-reducer/fetch-server-response'
function urlToUrlWithoutFlightMarker(url: string): URL { // Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.
let initialParallelRoutes: CacheNode['parallelRoutes'] =
typeof window === 'undefined' ? null! : new Map()
export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin) const urlWithoutFlightParameters = new URL(url, location.origin)
// TODO-APP: handle .rsc for static export case // TODO-APP: handle .rsc for static export case
return urlWithoutFlightParameters return urlWithoutFlightParameters
...@@ -52,60 +55,13 @@ const HotReloader: ...@@ -52,60 +55,13 @@ const HotReloader:
: (require('./react-dev-overlay/hot-reloader-client') : (require('./react-dev-overlay/hot-reloader-client')
.default as typeof import('./react-dev-overlay/hot-reloader-client').default) .default as typeof import('./react-dev-overlay/hot-reloader-client').default)
/**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
*/
export async function fetchServerResponse(
url: URL,
flightRouterState: FlightRouterState,
prefetch?: true
): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> {
const headers: {
[RSC]: '1'
[NEXT_ROUTER_STATE_TREE]: string
[NEXT_ROUTER_PREFETCH]?: '1'
} = {
// Enable flight response
[RSC]: '1',
// Provide the current router state
[NEXT_ROUTER_STATE_TREE]: JSON.stringify(flightRouterState),
}
if (prefetch) {
// Enable prefetch response
headers[NEXT_ROUTER_PREFETCH] = '1'
}
const res = await fetch(url.toString(), {
headers,
})
const canonicalUrl = res.redirected
? urlToUrlWithoutFlightMarker(res.url)
: undefined
const isFlightResponse =
res.headers.get('content-type') === 'application/octet-stream'
// If fetch returns something different than flight response handle it like a mpa navigation
if (!isFlightResponse) {
return [res.url, undefined]
}
// Handle the `fetch` readable stream that can be unwrapped by `React.use`.
const flightData: FlightData = await createFromFetch(Promise.resolve(res))
return [flightData, canonicalUrl]
}
// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.
let initialParallelRoutes: CacheNode['parallelRoutes'] =
typeof window === 'undefined' ? null! : new Map()
const prefetched = new Set<string>() const prefetched = new Set<string>()
type AppRouterProps = { type AppRouterProps = Omit<
InitialRouterStateParameters,
'initialParallelRoutes'
> & {
initialHead: ReactNode initialHead: ReactNode
initialTree: FlightRouterState
initialCanonicalUrl: string
children: ReactNode
assetPrefix: string assetPrefix: string
} }
...@@ -150,28 +106,16 @@ function Router({ ...@@ -150,28 +106,16 @@ function Router({
children, children,
assetPrefix, assetPrefix,
}: AppRouterProps) { }: AppRouterProps) {
const initialState = useMemo(() => { const initialState = useMemo(
return { () =>
tree: initialTree, createInitialRouterState({
cache: { children,
status: CacheStates.READY, initialCanonicalUrl,
data: null, initialTree,
subTreeData: children, initialParallelRoutes,
parallelRoutes: }),
typeof window === 'undefined' ? new Map() : initialParallelRoutes, [children, initialCanonicalUrl, initialTree]
} as CacheNode, )
prefetchCache: new Map(),
pushRef: { pendingPush: false, mpaNavigation: false },
focusAndScrollRef: { apply: false },
canonicalUrl:
// location.href is read as the initial value for canonicalUrl in the browser
// This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.
typeof window !== 'undefined'
? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.
createHrefFromUrl(window.location)
: initialCanonicalUrl,
}
}, [children, initialCanonicalUrl, initialTree])
const [ const [
{ tree, cache, prefetchCache, pushRef, focusAndScrollRef, canonicalUrl }, { tree, cache, prefetchCache, pushRef, focusAndScrollRef, canonicalUrl },
dispatch, dispatch,
......
...@@ -9,7 +9,7 @@ import type { ...@@ -9,7 +9,7 @@ import type {
ChildProp, ChildProp,
} from '../../server/app-render' } from '../../server/app-render'
import type { ErrorComponent } from './error-boundary' import type { ErrorComponent } from './error-boundary'
import type { FocusAndScrollRef } from './reducer' import type { FocusAndScrollRef } from './router-reducer/router-reducer'
import React, { useContext, useEffect, use } from 'react' import React, { useContext, useEffect, use } from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
...@@ -19,7 +19,7 @@ import { ...@@ -19,7 +19,7 @@ import {
GlobalLayoutRouterContext, GlobalLayoutRouterContext,
TemplateContext, TemplateContext,
} from '../../shared/lib/app-router-context' } from '../../shared/lib/app-router-context'
import { fetchServerResponse } from './app-router' import { fetchServerResponse } from './router-reducer/fetch-server-response'
import { createInfinitePromise } from './infinite-promise' import { createInfinitePromise } from './infinite-promise'
import { ErrorBoundary } from './error-boundary' import { ErrorBoundary } from './error-boundary'
import { matchSegment } from './match-segments' import { matchSegment } from './match-segments'
......
import React from 'react'
import type { FlightData, FlightRouterState } from '../../../server/app-render'
import { applyRouterStatePatchToTree } from './apply-router-state-patch-to-tree'
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
true,
]
const getFlightData = (): FlightData => {
return [
[
'children',
'linking',
'children',
'about',
[
'about',
{
children: ['', {}],
},
],
<h1>About Page!</h1>,
<>
<title>About page!</title>
</>,
],
]
}
describe('applyRouterStatePatchToTree', () => {
it('should apply a patch to the tree', () => {
const initialRouterStateTree = getInitialRouterStateTree()
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const [treePatch /*, subTreeData, head*/] = flightDataPath.slice(-3)
const flightSegmentPath = flightDataPath.slice(0, -4)
const newRouterStateTree = applyRouterStatePatchToTree(
['', ...flightSegmentPath],
initialRouterStateTree,
treePatch
)
expect(newRouterStateTree).toMatchObject([
'',
{
children: [
'linking',
{
children: [
'about',
{
children: ['', {}],
},
],
},
],
},
undefined,
undefined,
true,
])
})
})
import {
FlightRouterState,
FlightSegmentPath,
} from '../../../server/app-render'
import { matchSegment } from '../match-segments'
/**
* Apply the router state from the Flight response. Creates a new router state tree.
*/
export function applyRouterStatePatchToTree(
flightSegmentPath: FlightSegmentPath,
flightRouterState: FlightRouterState,
treePatch: FlightRouterState
): FlightRouterState | null {
const [segment, parallelRoutes, , , isRootLayout] = flightRouterState
// Root refresh
if (flightSegmentPath.length === 1) {
const tree: FlightRouterState = [...treePatch]
return tree
}
const [currentSegment, parallelRouteKey] = flightSegmentPath
// Tree path returned from the server should always match up with the current tree in the browser
if (!matchSegment(currentSegment, segment)) {
return null
}
const lastSegment = flightSegmentPath.length === 2
let parallelRoutePatch
if (lastSegment) {
parallelRoutePatch = treePatch
} else {
parallelRoutePatch = applyRouterStatePatchToTree(
flightSegmentPath.slice(2),
parallelRoutes[parallelRouteKey],
treePatch
)
if (parallelRoutePatch === null) {
return null
}
}
const tree: FlightRouterState = [
flightSegmentPath[0],
{
...parallelRoutes,
[parallelRouteKey]: parallelRoutePatch,
},
]
// Current segment is the root layout
if (isRootLayout) {
tree[4] = true
}
return tree
}
import { createHrefFromUrl } from './create-href-from-url'
describe('createHrefFromUrl', () => {
it('returns a string', () => {
const url = new URL('https://example.com/')
expect(createHrefFromUrl(url)).toBe('/')
})
it('adds hash', () => {
const url = new URL('https://example.com/#hash')
expect(createHrefFromUrl(url)).toBe('/#hash')
})
it('adds searchParams', () => {
const url = new URL('https://example.com/?a=1&b=2')
expect(createHrefFromUrl(url)).toBe('/?a=1&b=2')
})
it('adds pathname', () => {
const url = new URL('https://example.com/path')
expect(createHrefFromUrl(url)).toBe('/path')
})
it('adds pathname, searchParams, and hash', () => {
const url = new URL('https://example.com/path?a=1&b=2#hash')
expect(createHrefFromUrl(url)).toBe('/path?a=1&b=2#hash')
})
})
export function createHrefFromUrl(
url: Pick<URL, 'pathname' | 'search' | 'hash'>
): string {
return url.pathname + url.search + url.hash
}
import type { ReactNode } from 'react'
import type { CacheNode } from '../../../shared/lib/app-router-context'
import type { FlightRouterState } from '../../../server/app-render'
import { CacheStates } from '../../../shared/lib/app-router-context'
import { createHrefFromUrl } from './create-href-from-url'
export interface InitialRouterStateParameters {
initialTree: FlightRouterState
initialCanonicalUrl: string
children: ReactNode
initialParallelRoutes: CacheNode['parallelRoutes']
}
export function createInitialRouterState({
initialTree,
children,
initialCanonicalUrl,
initialParallelRoutes,
}: InitialRouterStateParameters) {
return {
tree: initialTree,
cache: {
status: CacheStates.READY,
data: null,
subTreeData: children,
parallelRoutes:
typeof window === 'undefined' ? new Map() : initialParallelRoutes,
} as CacheNode,
prefetchCache: new Map(),
pushRef: { pendingPush: false, mpaNavigation: false },
focusAndScrollRef: { apply: false },
canonicalUrl:
// location.href is read as the initial value for canonicalUrl in the browser
// This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.
typeof window !== 'undefined'
? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.
createHrefFromUrl(window.location)
: initialCanonicalUrl,
}
}
import { FlightRouterState } from '../../../server/app-render'
import { matchSegment } from '../match-segments'
/**
* Create optimistic version of router state based on the existing router state and segments.
* This is used to allow rendering layout-routers up till the point where data is missing.
*/
export function createOptimisticTree(
segments: string[],
flightRouterState: FlightRouterState | null,
_isFirstSegment: boolean,
parentRefetch: boolean,
_href?: string
): FlightRouterState {
const [existingSegment, existingParallelRoutes] = flightRouterState || [
null,
{},
]
const segment = segments[0]
const isLastSegment = segments.length === 1
const segmentMatches =
existingSegment !== null && matchSegment(existingSegment, segment)
const shouldRefetchThisLevel = !flightRouterState || !segmentMatches
let parallelRoutes: FlightRouterState[1] = {}
if (existingSegment !== null && segmentMatches) {
parallelRoutes = existingParallelRoutes
}
let childTree
if (!isLastSegment) {
const childItem = createOptimisticTree(
segments.slice(1),
parallelRoutes ? parallelRoutes.children : null,
false,
parentRefetch || shouldRefetchThisLevel
)
childTree = childItem
}
const result: FlightRouterState = [
segment,
{
...parallelRoutes,
...(childTree ? { children: childTree } : {}),
},
]
if (!parentRefetch && shouldRefetchThisLevel) {
result[3] = 'refetch'
}
return result
}
import { createRecordFromThenable } from './create-record-from-thenable'
describe('createRecordFromThenable', () => {
it('successful promise', async () => {
const thenable = Promise.resolve('success')
const record = createRecordFromThenable(thenable)
expect(record.status).toBe('pending')
await thenable
expect(record.status).toBe('fulfilled')
expect(record.value).toBe('success')
})
it('rejecting promise', async () => {
const thenable = Promise.reject('error')
const record = createRecordFromThenable(thenable)
expect(record.status).toBe('pending')
await thenable.catch(() => {})
expect(record.status).toBe('rejected')
expect(record.value).toBe('error')
})
})
/**
* Create data fetching record for Promise.
*/
// TODO-APP: change `any` to type inference.
export function createRecordFromThenable(thenable: any) {
thenable.status = 'pending'
thenable.then(
(value: any) => {
if (thenable.status === 'pending') {
thenable.status = 'fulfilled'
thenable.value = value
}
},
(err: any) => {
if (thenable.status === 'pending') {
thenable.status = 'rejected'
thenable.value = err
}
}
)
return thenable
}
'use client'
import { createFromFetch } from 'next/dist/compiled/react-server-dom-webpack/client'
import { FlightRouterState, FlightData } from '../../../server/app-render'
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_STATE_TREE,
RSC,
} from '../app-router-headers'
import { urlToUrlWithoutFlightMarker } from '../app-router'
/**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
*/
export async function fetchServerResponse(
url: URL,
flightRouterState: FlightRouterState,
prefetch?: true
): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> {
const headers: {
[RSC]: '1'
[NEXT_ROUTER_STATE_TREE]: string
[NEXT_ROUTER_PREFETCH]?: '1'
} = {
// Enable flight response
[RSC]: '1',
// Provide the current router state
[NEXT_ROUTER_STATE_TREE]: JSON.stringify(flightRouterState),
}
if (prefetch) {
// Enable prefetch response
headers[NEXT_ROUTER_PREFETCH] = '1'
}
const res = await fetch(url.toString(), {
headers,
})
const canonicalUrl = res.redirected
? urlToUrlWithoutFlightMarker(res.url)
: undefined
const isFlightResponse =
res.headers.get('content-type') === 'application/octet-stream'
// If fetch returns something different than flight response handle it like a mpa navigation
if (!isFlightResponse) {
return [res.url, undefined]
}
// Handle the `fetch` readable stream that can be unwrapped by `React.use`.
const flightData: FlightData = await createFromFetch(Promise.resolve(res))
return [flightData, canonicalUrl]
}
import React from 'react'
import { fetchServerResponse } from './fetch-server-response'
import { fillCacheWithDataProperty } from './fill-cache-with-data-property'
import { CacheStates, CacheNode } from '../../../shared/lib/app-router-context'
describe('fillCacheWithDataProperty', () => {
it('should add data property', () => {
const fetchServerResponseMock: jest.Mock<
ReturnType<typeof fetchServerResponse>
> = jest.fn(() =>
Promise.resolve([
/* TODO-APP: replace with actual FlightData */ '',
undefined,
])
)
const pathname = '/dashboard/settings'
const segments = pathname.split('/')
// TODO-APP: figure out something better for index pages
segments.push('')
const cache: CacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
const existingCache: CacheNode = {
data: null,
status: CacheStates.READY,
subTreeData: <>Root layout</>,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
data: null,
status: CacheStates.READY,
subTreeData: <>Linking</>,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
data: null,
status: CacheStates.READY,
subTreeData: <>Page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
fillCacheWithDataProperty(cache, existingCache, segments, () =>
fetchServerResponseMock()
)
const expectedCache: CacheNode = {
data: null,
status: CacheStates.LAZY_INITIALIZED,
subTreeData: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
data: null,
status: CacheStates.READY,
subTreeData: <>Linking</>,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
data: null,
status: CacheStates.READY,
subTreeData: <>Page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
[
'',
{
data: fetchServerResponseMock(),
parallelRoutes: new Map(),
status: CacheStates.DATA_FETCH,
subTreeData: null,
},
],
]),
],
]),
}
expect(cache).toMatchObject(expectedCache)
})
})
import { CacheNode, CacheStates } from '../../../shared/lib/app-router-context'
import { fetchServerResponse } from './fetch-server-response'
/**
* Kick off fetch based on the common layout between two routes. Fill cache with data property holding the in-progress fetch.
*/
export function fillCacheWithDataProperty(
newCache: CacheNode,
existingCache: CacheNode,
segments: string[],
fetchResponse: () => ReturnType<typeof fetchServerResponse>
): { bailOptimistic: boolean } | undefined {
const isLastEntry = segments.length === 1
const parallelRouteKey = 'children'
const [segment] = segments
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return { bailOptimistic: true }
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
const existingChildCacheNode = existingChildSegmentMap.get(segment)
let childCacheNode = childSegmentMap.get(segment)
// In case of last segment start off the fetch at this level and don't copy further down.
if (isLastEntry) {
if (
!childCacheNode ||
!childCacheNode.data ||
childCacheNode === existingChildCacheNode
) {
childSegmentMap.set(segment, {
status: CacheStates.DATA_FETCH,
data: fetchResponse(),
subTreeData: null,
parallelRoutes: new Map(),
})
}
return
}
if (!childCacheNode || !existingChildCacheNode) {
// Start fetch in the place where the existing cache doesn't have the data yet.
if (!childCacheNode) {
childSegmentMap.set(segment, {
status: CacheStates.DATA_FETCH,
data: fetchResponse(),
subTreeData: null,
parallelRoutes: new Map(),
})
}
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
status: childCacheNode.status,
data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
} as CacheNode
childSegmentMap.set(segment, childCacheNode)
}
return fillCacheWithDataProperty(
childCacheNode,
existingChildCacheNode,
segments.slice(1),
fetchResponse
)
}
import { CacheNode, CacheStates } from '../../../shared/lib/app-router-context'
import { FlightDataPath } from '../../../server/app-render'
import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
/**
* Fill cache with subTreeData based on flightDataPath
*/
export function fillCacheWithNewSubTreeData(
newCache: CacheNode,
existingCache: CacheNode,
flightDataPath: FlightDataPath
): void {
const isLastEntry = flightDataPath.length <= 5
const [parallelRouteKey, segment] = flightDataPath
const segmentForCache = Array.isArray(segment) ? segment[1] : segment
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache)
let childCacheNode = childSegmentMap.get(segmentForCache)
if (isLastEntry) {
if (
!childCacheNode ||
!childCacheNode.data ||
childCacheNode === existingChildCacheNode
) {
childCacheNode = {
status: CacheStates.READY,
data: null,
subTreeData: flightDataPath[3],
// Ensure segments other than the one we got data for are preserved.
parallelRoutes: existingChildCacheNode
? new Map(existingChildCacheNode.parallelRoutes)
: new Map(),
}
if (existingChildCacheNode) {
invalidateCacheByRouterState(
childCacheNode,
existingChildCacheNode,
flightDataPath[2]
)
}
fillLazyItemsTillLeafWithHead(
childCacheNode,
existingChildCacheNode,
flightDataPath[2],
flightDataPath[4]
)
childSegmentMap.set(segmentForCache, childCacheNode)
}
return
}
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
status: childCacheNode.status,
data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
} as CacheNode
childSegmentMap.set(segmentForCache, childCacheNode)
}
fillCacheWithNewSubTreeData(
childCacheNode,
existingChildCacheNode,
flightDataPath.slice(2)
)
}
import React from 'react'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import { CacheStates, CacheNode } from '../../../shared/lib/app-router-context'
import { FlightData } from '../../../server/app-render'
const getFlightData = (): FlightData => {
return [
[
[
'',
{
children: [
'linking',
{
children: [
'about',
{
children: ['', {}],
},
],
},
],
},
null,
null,
true,
],
<h1>About Page!</h1>,
<>
<title>About page!</title>
</>,
],
]
}
describe('fillLazyItemsTillLeafWithHead', () => {
it('should fill lazy items till leaf with head', () => {
const cache: CacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
const existingCache: CacheNode = {
data: null,
status: CacheStates.READY,
subTreeData: <>Root layout</>,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
data: null,
status: CacheStates.READY,
subTreeData: <>Linking</>,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
data: null,
status: CacheStates.READY,
subTreeData: <>Page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// 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(-3)
// const flightSegmentPath = flightDataPath.slice(0, -4)
fillLazyItemsTillLeafWithHead(cache, existingCache, treePatch, head)
const expectedCache: CacheNode = {
data: null,
status: CacheStates.LAZY_INITIALIZED,
subTreeData: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
data: null,
status: CacheStates.LAZY_INITIALIZED,
subTreeData: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'about',
{
data: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
data: null,
status: CacheStates.LAZY_INITIALIZED,
subTreeData: null,
parallelRoutes: new Map(),
head: (
<>
<title>About page!</title>
</>
),
},
],
]),
],
]),
subTreeData: null,
status: CacheStates.LAZY_INITIALIZED,
},
],
// TODO-APP: this segment should be preserved when creating the new cache
// [
// '',
// {
// data: null,
// status: CacheStates.READY,
// subTreeData: <>Page</>,
// parallelRoutes: new Map(),
// },
// ],
]),
],
]),
},
],
]),
],
]),
}
expect(cache).toMatchObject(expectedCache)
})
})
import { CacheNode, CacheStates } from '../../../shared/lib/app-router-context'
import { FlightRouterState } from '../../../server/app-render'
export function fillLazyItemsTillLeafWithHead(
newCache: CacheNode,
existingCache: CacheNode | undefined,
routerState: FlightRouterState,
head: React.ReactNode
): void {
const isLastSegment = Object.keys(routerState[1]).length === 0
if (isLastSegment) {
newCache.head = head
return
}
// Remove segment that we got data for so that it is filled in during rendering of subTreeData.
for (const key in routerState[1]) {
const parallelRouteState = routerState[1][key]
const segmentForParallelRoute = parallelRouteState[0]
const cacheKey = Array.isArray(segmentForParallelRoute)
? segmentForParallelRoute[1]
: segmentForParallelRoute
if (existingCache) {
const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
parallelRouteCacheNode.delete(cacheKey)
const newCacheNode: CacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
parallelRouteCacheNode.set(cacheKey, newCacheNode)
fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
parallelRouteState,
head
)
newCache.parallelRoutes.set(key, parallelRouteCacheNode)
continue
}
}
const newCacheNode: CacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))
fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
parallelRouteState,
head
)
}
}
import { CacheNode } from '../../../shared/lib/app-router-context'
import { FlightRouterState } from '../../../server/app-render'
/**
* Invalidate cache one level down from the router state.
*/
export function invalidateCacheByRouterState(
newCache: CacheNode,
existingCache: CacheNode,
routerState: FlightRouterState
): void {
// Remove segment that we got data for so that it is filled in during rendering of subTreeData.
for (const key in routerState[1]) {
const segmentForParallelRoute = routerState[1][key][0]
const cacheKey = Array.isArray(segmentForParallelRoute)
? segmentForParallelRoute[1]
: segmentForParallelRoute
const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
parallelRouteCacheNode.delete(cacheKey)
newCache.parallelRoutes.set(key, parallelRouteCacheNode)
}
}
}
import { CacheNode } from '../../../shared/lib/app-router-context'
import { FlightSegmentPath } from '../../../server/app-render'
/**
* Fill cache up to the end of the flightSegmentPath, invalidating anything below it.
*/
export function invalidateCacheBelowFlightSegmentPath(
newCache: CacheNode,
existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath
): void {
const isLastEntry = flightSegmentPath.length <= 2
const [parallelRouteKey, segment] = flightSegmentPath
const segmentForCache = Array.isArray(segment) ? segment[1] : segment
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
// In case of last entry don't copy further down.
if (isLastEntry) {
childSegmentMap.delete(segmentForCache)
return
}
const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache)
let childCacheNode = childSegmentMap.get(segmentForCache)
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
status: childCacheNode.status,
data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
} as CacheNode
childSegmentMap.set(segmentForCache, childCacheNode)
}
invalidateCacheBelowFlightSegmentPath(
childCacheNode,
existingChildCacheNode,
flightSegmentPath.slice(2)
)
}
import { FlightRouterState } from '../../../server/app-render'
export function isNavigatingToNewRootLayout(
currentTree: FlightRouterState,
nextTree: FlightRouterState
): boolean {
// Compare segments
const currentTreeSegment = currentTree[0]
const nextTreeSegment = nextTree[0]
// If any segment is different before we find the root layout, the root layout has changed.
// E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js
// First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.
if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {
// Compare dynamic param name and type but ignore the value, different values would not affect the current root layout
// /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js
if (
currentTreeSegment[0] !== nextTreeSegment[0] ||
currentTreeSegment[2] !== nextTreeSegment[2]
) {
return true
}
} else if (currentTreeSegment !== nextTreeSegment) {
return true
}
// Current tree root layout found
if (currentTree[4]) {
// If the next tree doesn't have the root layout flag, it must have changed.
return !nextTree[4]
}
// Current tree didn't have its root layout here, must have changed.
if (nextTree[4]) {
return true
}
// We can't assume it's `parallelRoutes.children` here in case the root layout is `app/@something/layout.js`
// But it's not possible to be more than one parallelRoutes before the root layout is found
// TODO-APP: change to traverse all parallel routes
const currentTreeChild = Object.values(currentTree[1])[0]
const nextTreeChild = Object.values(nextTree[1])[0]
if (!currentTreeChild || !nextTreeChild) return true
return isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild)
}
import { readRecordValue } from './read-record-value'
import { createRecordFromThenable } from './create-record-from-thenable'
describe('readRecordValue', () => {
it('successful promise', async () => {
const thenable = Promise.resolve('success')
const record = createRecordFromThenable(thenable)
expect(() => readRecordValue(record)).toThrow()
await thenable
expect(readRecordValue(record)).toBe('success')
})
it('rejecting promise', async () => {
const thenable = Promise.reject('failed')
const record = createRecordFromThenable(thenable)
expect(() => readRecordValue(record)).toThrow()
await thenable.catch(() => {})
expect(() => readRecordValue(record)).toThrow()
const result: any = (() => {
try {
return readRecordValue(record)
} catch (err) {
return err
}
})()
expect(result.status).toBe('rejected')
expect(result.value).toBe('failed')
})
})
/**
* Read record value or throw Promise if it's not resolved yet.
*/
export function readRecordValue<T>(thenable: Promise<T>): T {
// @ts-expect-error TODO: fix type
if (thenable.status === 'fulfilled') {
// @ts-expect-error TODO: fix type
return thenable.value
} else {
throw thenable
}
}
import {
FlightRouterState,
FlightDataPath,
Segment,
} from '../../../server/app-render'
import { matchSegment } from '../match-segments'
export function shouldHardNavigate(
flightSegmentPath: FlightDataPath,
flightRouterState: FlightRouterState,
treePatch: FlightRouterState
): boolean {
const [segment, parallelRoutes] = flightRouterState
// TODO-APP: Check if `as` can be replaced.
const [currentSegment, parallelRouteKey] = flightSegmentPath as [
Segment,
string
]
// Check if current segment matches the existing segment.
if (!matchSegment(currentSegment, segment)) {
// If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered.
if (Array.isArray(currentSegment)) {
return true
}
// If the existing segment did not match soft navigation is triggered.
return false
}
const lastSegment = flightSegmentPath.length <= 2
if (lastSegment) {
return false
}
return shouldHardNavigate(
flightSegmentPath.slice(2),
parallelRoutes[parallelRouteKey],
treePatch
)
}
import type { reducer } from './reducer' import type { reducer } from './router-reducer/router-reducer'
import type { import type {
ReducerState, ReducerState,
ReducerAction, ReducerAction,
......
...@@ -636,8 +636,8 @@ type LoaderTree = [ ...@@ -636,8 +636,8 @@ type LoaderTree = [
export type FlightRouterState = [ export type FlightRouterState = [
segment: Segment, segment: Segment,
parallelRoutes: { [parallelRouterKey: string]: FlightRouterState }, parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },
url?: string, url?: string | null,
refresh?: 'refetch', refresh?: 'refetch' | null,
isRootLayout?: boolean isRootLayout?: boolean
] ]
......
'use client' 'use client'
import React from 'react' import type { FocusAndScrollRef } from '../../client/components/router-reducer/router-reducer'
import type { FocusAndScrollRef } from '../../client/components/reducer' import type { fetchServerResponse } from '../../client/components/router-reducer/fetch-server-response'
import type { FlightRouterState, FlightData } from '../../server/app-render' import type { FlightRouterState, FlightData } from '../../server/app-render'
import React from 'react'
export type ChildSegmentMap = Map<string, CacheNode> export type ChildSegmentMap = Map<string, CacheNode>
...@@ -22,9 +23,7 @@ export type CacheNode = ...@@ -22,9 +23,7 @@ export type CacheNode =
/** /**
* In-flight request for this node. * In-flight request for this node.
*/ */
data: ReturnType< data: ReturnType<typeof fetchServerResponse> | null
typeof import('../../client/components/app-router').fetchServerResponse
> | null
head?: React.ReactNode head?: React.ReactNode
/** /**
* React Component for this node. * React Component for this node.
......
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