Unverified Commit 71ad0dd0 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add prefetch to new router (#39866)

Follow-up to #37551
Implements prefetching for the new router.

There are multiple behaviors related to prefetching so I've split them out for each case. The list below each case is what's prefetched:

Reference:
- Checkmark checked → it's implemented.
- RSC Payload → Rendered server components.
- Router state → Patch for the router history state.
- Preloads for client component entry → This will be handled in a follow-up PR.
- No `loading.js` static case → Will be handled in a follow-up PR.

---

- `prefetch={true}` (default, same as current router, links in viewport are prefetched)
    - [x]  Static all the way down the component tree
        - [x] RSC payload
        - [x] Router state
        - [ ] preloads for the client component entry
    - [x]  Not static all the way down the component tree
        - [x]  With `loading.js`
            - [x] RSC payload up until the loading below the common layout
            - [x] router state
            - [ ] preloads for the client component entry
        - [x]  No `loading.js` (This case can be static files to make sure it’s fast)
            - [x] router state
            - [ ] preloads for the client component entry
- `prefetch={false}`
    - [x]  always do an optimistic navigation. We already have this implemented where it tries to figure out the router state based on the provided url. That result might be wrong but the router will automatically figure out that

---

In the first implementation there is a distinction between `hard` and `soft` navigation. With the addition of prefetching you no longer have to add a `soft` prop to `next/link` in order to leverage the `soft` case. 

A heuristic has been added that automatically prefers `soft` navigation except when navigating between mismatching dynamic parameters.

An example:
- `app/[userOrTeam]/dashboard/page.js` and `app/[userOrTeam]/dashboard/settings/page.js`
  - `/tim/dashboard` → `/tim/dashboard/settings` = Soft navigation 
  - `/tim/dashboard` → `/vercel/dashboard` = Hard navigation
  - `/vercel/dashboard` → `/vercel/dashboard/settings` = Soft navigation
  - `/vercel/dashboard/settings` -> `/tim/dashboard` = Hard navigation

---

While adding these new heuristics some of the tests started failing and I found some state bugs in `router.reload()` which have been fixed. An example being when you push to `/dashboard` while on `/` in the same transition it would navigate to `/`, it also wouldn't push a new history entry. Both of these cases are now fixed:

```
React.startTransition(() => {
  router.push('/dashboard')
  router.reload()
})
```

---

While debugging the various changes I ended up debugging and manually diffing the cache and router state quite often and was looking at a way to automate this. `useReducer` is quite similar to Redux so I was wondering if Redux Devtools could be used in order to debug the various actions as it has diffing built-in. It took a bit of time to figure out the connection mechanism but in the end I figured out how to connect `useReducer`, a new hook `useReducerWithReduxDevtools` has been added, we'll probably want to put this behind a compile-time flag when the new router is marked stable but until then it's useful to have it enabled by default (only when you have Redux Devtools installed ofcourse).

> ⚠️ Redux Devtools is only connected to take incoming actions / state. Time travel and other features are not supported because the state sent to the devtools is normalized to allow diffing the maps, you can't move backward based on that state so applying the state is not connected.

Example of the integration:

<img width="1912" alt="Screen Shot 2022-09-02 at 10 00 40" src="https://user-images.githubusercontent.com/6324199/188637303-ad8d6a81-15e5-4b65-875b-1c4f93df4e44.png">
parent 5f95b6b0
import React, { useContext, useEffect, useRef } from 'react' import React, { useContext, useEffect, useRef } from 'react'
import type { ChildProp, Segment } from '../../server/app-render' import type {
ChildProp,
//Segment
} from '../../server/app-render'
import type { ChildSegmentMap } from '../../shared/lib/app-router-context' import type { ChildSegmentMap } from '../../shared/lib/app-router-context'
import type { import type {
FlightRouterState, FlightRouterState,
FlightSegmentPath, FlightSegmentPath,
FlightDataPath, // FlightDataPath,
} from '../../server/app-render' } from '../../server/app-render'
import { import {
LayoutRouterContext, LayoutRouterContext,
GlobalLayoutRouterContext, GlobalLayoutRouterContext,
} from '../../shared/lib/app-router-context' } from '../../shared/lib/app-router-context'
import { fetchServerResponse } from './app-router.client' import { fetchServerResponse } from './app-router.client'
import { matchSegment } from './match-segments' // import { matchSegment } from './match-segments'
/** /**
* Check if every segment in array a and b matches * Check if every segment in array a and b matches
*/ */
function equalSegmentPaths(a: Segment[], b: Segment[]) { // function equalSegmentPaths(a: Segment[], b: Segment[]) {
// Comparing length is a fast path. // // Comparing length is a fast path.
return a.length === b.length && a.every((val, i) => matchSegment(val, b[i])) // return a.length === b.length && a.every((val, i) => matchSegment(val, b[i]))
} // }
/** /**
* Check if flightDataPath matches layoutSegmentPath * Check if flightDataPath matches layoutSegmentPath
*/ */
function segmentPathMatches( // function segmentPathMatches(
flightDataPath: FlightDataPath, // flightDataPath: FlightDataPath,
layoutSegmentPath: FlightSegmentPath // layoutSegmentPath: FlightSegmentPath
): boolean { // ): boolean {
// The last three items are the current segment, tree, and subTreeData // // The last three items are the current segment, tree, and subTreeData
const pathToLayout = flightDataPath.slice(0, -3) // const pathToLayout = flightDataPath.slice(0, -3)
return equalSegmentPaths(layoutSegmentPath, pathToLayout) // return equalSegmentPaths(layoutSegmentPath, pathToLayout)
// }
/**
* Add refetch marker to router state at the point of the current layout segment.
* This ensures the response returned is not further down than the current layout segment.
*/
function walkAddRefetch(
segmentPathToWalk: FlightSegmentPath | undefined,
treeToRecreate: FlightRouterState
): FlightRouterState {
if (segmentPathToWalk) {
const [segment, parallelRouteKey] = segmentPathToWalk
const isLast = segmentPathToWalk.length === 2
if (treeToRecreate[0] === segment) {
if (treeToRecreate[1].hasOwnProperty(parallelRouteKey)) {
if (isLast) {
const subTree = walkAddRefetch(
undefined,
treeToRecreate[1][parallelRouteKey]
)
return [
treeToRecreate[0],
{
...treeToRecreate[1],
[parallelRouteKey]: [
subTree[0],
subTree[1],
subTree[2],
'refetch',
],
},
]
}
return [
treeToRecreate[0],
{
...treeToRecreate[1],
[parallelRouteKey]: walkAddRefetch(
segmentPathToWalk.slice(2),
treeToRecreate[1][parallelRouteKey]
),
},
]
}
}
}
return treeToRecreate
} }
/** /**
...@@ -114,7 +167,13 @@ export function InnerLayoutRouter({ ...@@ -114,7 +167,13 @@ export function InnerLayoutRouter({
let childNode = childNodes.get(path) let childNode = childNodes.get(path)
// If childProp is available this means it's the Flight / SSR case. // If childProp is available this means it's the Flight / SSR case.
if (childProp && !childNode) { if (
childProp &&
// TODO-APP: verify if this can be null based on user code
childProp.current !== null &&
!childNode /*&&
!childProp.partial*/
) {
// Add the segment's subTreeData to the cache. // 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. // 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.
childNodes.set(path, { childNodes.set(path, {
...@@ -130,55 +189,6 @@ export function InnerLayoutRouter({ ...@@ -130,55 +189,6 @@ export function InnerLayoutRouter({
// 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) { if (!childNode) {
/**
* Add refetch marker to router state at the point of the current layout segment.
* This ensures the response returned is not further down than the current layout segment.
*/
const walkAddRefetch = (
segmentPathToWalk: FlightSegmentPath | undefined,
treeToRecreate: FlightRouterState
): FlightRouterState => {
if (segmentPathToWalk) {
const [segment, parallelRouteKey] = segmentPathToWalk
const isLast = segmentPathToWalk.length === 2
if (treeToRecreate[0] === segment) {
if (treeToRecreate[1].hasOwnProperty(parallelRouteKey)) {
if (isLast) {
const subTree = walkAddRefetch(
undefined,
treeToRecreate[1][parallelRouteKey]
)
if (!subTree[2]) {
subTree[2] = undefined
}
subTree[3] = 'refetch'
return [
treeToRecreate[0],
{
...treeToRecreate[1],
[parallelRouteKey]: [...subTree],
},
]
}
return [
treeToRecreate[0],
{
...treeToRecreate[1],
[parallelRouteKey]: walkAddRefetch(
segmentPathToWalk.slice(2),
treeToRecreate[1][parallelRouteKey]
),
},
]
}
}
}
return treeToRecreate
}
/** /**
* Router state with refetch marker added * Router state with refetch marker added
*/ */
...@@ -188,9 +198,8 @@ export function InnerLayoutRouter({ ...@@ -188,9 +198,8 @@ export function InnerLayoutRouter({
/** /**
* Flight data fetch kicked off during render and put into the cache. * Flight data fetch kicked off during render and put into the cache.
*/ */
const data = fetchServerResponse(new URL(url, location.origin), refetchTree)
childNodes.set(path, { childNodes.set(path, {
data, data: fetchServerResponse(new URL(url, location.origin), refetchTree),
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}) })
...@@ -230,22 +239,22 @@ export function InnerLayoutRouter({ ...@@ -230,22 +239,22 @@ export function InnerLayoutRouter({
let fastPath: boolean = false let fastPath: boolean = false
// If there are multiple patches returned in the Flight data we need to dispatch to ensure a single render. // If there are multiple patches returned in the Flight data we need to dispatch to ensure a single render.
if (flightData.length === 1) { // if (flightData.length === 1) {
const flightDataPath = flightData[0] // const flightDataPath = flightData[0]
if (segmentPathMatches(flightDataPath, segmentPath)) { // if (segmentPathMatches(flightDataPath, segmentPath)) {
// Ensure data is set to null as subTreeData will be set in the cache now. // // Ensure data is set to null as subTreeData will be set in the cache now.
childNode.data = null // childNode.data = null
// Last item is the subtreeData // // Last item is the subtreeData
// TODO-APP: routerTreePatch needs to be applied to the tree, handle it in render? // // TODO-APP: routerTreePatch needs to be applied to the tree, handle it in render?
const [, /* routerTreePatch */ subTreeData] = flightDataPath.slice(-2) // const [, /* routerTreePatch */ subTreeData] = flightDataPath.slice(-2)
// Add subTreeData into the cache // // Add subTreeData into the cache
childNode.subTreeData = subTreeData // childNode.subTreeData = subTreeData
// This field is required for new items // // This field is required for new items
childNode.parallelRoutes = new Map() // childNode.parallelRoutes = new Map()
fastPath = true // fastPath = true
} // }
} // }
// When the fast path is not used a new action is dispatched to update the tree and cache. // When the fast path is not used a new action is dispatched to update the tree and cache.
if (!fastPath) { if (!fastPath) {
......
This diff is collapsed.
import type { reducer } from './reducer'
import type {
ReducerState,
ReducerAction,
MutableRefObject,
Dispatch,
} from 'react'
import { useRef, useReducer, useEffect, useCallback } from 'react'
function normalizeRouterState(val: any): any {
if (val instanceof Map) {
const obj: { [key: string]: any } = {}
for (const [key, value] of val.entries()) {
if (typeof value === 'function') {
obj[key] = 'fn()'
continue
}
if (typeof value === 'object' && value !== null) {
if (value.$$typeof) {
obj[key] = value.$$typeof.toString()
continue
}
if (value._bundlerConfig) {
obj[key] = 'FlightData'
continue
}
}
obj[key] = normalizeRouterState(value)
}
return obj
}
if (typeof val === 'object' && val !== null) {
const obj: { [key: string]: any } = {}
for (const key in val) {
const value = val[key]
if (typeof value === 'function') {
obj[key] = 'fn()'
continue
}
if (typeof value === 'object' && value !== null) {
if (value.$$typeof) {
obj[key] = value.$$typeof.toString()
continue
}
if (value.hasOwnProperty('_bundlerConfig')) {
obj[key] = 'FlightData'
continue
}
}
obj[key] = normalizeRouterState(value)
}
return obj
}
if (Array.isArray(val)) {
return val.map(normalizeRouterState)
}
return val
}
// Log router state when actions are triggered.
// function logReducer(fn: typeof reducer) {
// return (
// state: ReducerState<typeof reducer>,
// action: ReducerAction<typeof reducer>
// ) => {
// console.groupCollapsed(action.type)
// console.log('action', action)
// console.log('old', state)
// const res = fn(state, action)
// console.log('new', res)
// console.groupEnd()
// return res
// }
// }
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: any
}
}
interface ReduxDevToolsInstance {
send(action: any, state: any): void
init(initialState: any): void
}
function devToolReducer(
fn: typeof reducer,
ref: MutableRefObject<ReduxDevToolsInstance | undefined>
) {
return (
state: ReducerState<typeof reducer>,
action: ReducerAction<typeof reducer>
) => {
const res = fn(state, action)
if (ref.current) {
ref.current.send(action, normalizeRouterState(res))
}
return res
}
}
export function useReducerWithReduxDevtools(
fn: typeof reducer,
initialState: ReturnType<typeof reducer>
): [
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>,
() => void
] {
const devtoolsConnectionRef = useRef<ReduxDevToolsInstance>()
const enabledRef = useRef<boolean>()
useEffect(() => {
if (devtoolsConnectionRef.current || enabledRef.current === false) {
return
}
if (
enabledRef.current === undefined &&
typeof window.__REDUX_DEVTOOLS_EXTENSION__ === 'undefined'
) {
enabledRef.current = false
return
}
devtoolsConnectionRef.current = window.__REDUX_DEVTOOLS_EXTENSION__.connect(
{
instanceId: 1,
name: 'next-router',
}
)
if (devtoolsConnectionRef.current) {
devtoolsConnectionRef.current.init(normalizeRouterState(initialState))
}
return () => {
devtoolsConnectionRef.current = undefined
}
}, [initialState])
const [state, dispatch] = useReducer(
devToolReducer(/* logReducer( */ fn /*)*/, devtoolsConnectionRef),
initialState
)
const sync = useCallback(() => {
if (devtoolsConnectionRef.current) {
devtoolsConnectionRef.current.send(
{ type: 'RENDER_SYNC' },
normalizeRouterState(state)
)
}
}, [state])
return [state, dispatch, sync]
}
...@@ -31,11 +31,6 @@ type InternalLinkProps = { ...@@ -31,11 +31,6 @@ type InternalLinkProps = {
href: Url href: Url
as?: Url as?: Url
replace?: boolean replace?: boolean
/**
* TODO-APP
*/
soft?: boolean
scroll?: boolean scroll?: boolean
shallow?: boolean shallow?: boolean
passHref?: boolean passHref?: boolean
...@@ -79,7 +74,7 @@ function prefetch( ...@@ -79,7 +74,7 @@ function prefetch(
// We need to handle a prefetch error here since we may be // We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't // loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch // want to force navigation since this is only a prefetch
router.prefetch(href, as, options).catch((err) => { Promise.resolve(router.prefetch(href, as, options)).catch((err) => {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
// rethrow to show invalid URL errors // rethrow to show invalid URL errors
throw err throw err
...@@ -112,11 +107,11 @@ function linkClicked( ...@@ -112,11 +107,11 @@ function linkClicked(
href: string, href: string,
as: string, as: string,
replace?: boolean, replace?: boolean,
soft?: boolean,
shallow?: boolean, shallow?: boolean,
scroll?: boolean, scroll?: boolean,
locale?: string | false, locale?: string | false,
startTransition?: (cb: any) => void startTransition?: (cb: any) => void,
prefetchEnabled?: boolean
): void { ): void {
const { nodeName } = e.currentTarget const { nodeName } = e.currentTarget
...@@ -131,26 +126,18 @@ function linkClicked( ...@@ -131,26 +126,18 @@ function linkClicked(
e.preventDefault() e.preventDefault()
const navigate = () => { const navigate = () => {
// If the router is an AppRouterInstance, then it'll have `softPush` and // If the router is an NextRouter instance it will have `beforePopState`
// `softReplace`. if ('beforePopState' in router) {
if ('softPush' in router && 'softReplace' in router) {
// If we're doing a soft navigation, use the soft variants of
// replace/push.
const method: keyof AppRouterInstance = soft
? replace
? 'softReplace'
: 'softPush'
: replace
? 'replace'
: 'push'
router[method](href)
} else {
router[replace ? 'replace' : 'push'](href, as, { router[replace ? 'replace' : 'push'](href, as, {
shallow, shallow,
locale, locale,
scroll, scroll,
}) })
} else {
// If `beforePopState` doesn't exist on the router it's the AppRouter.
const method: keyof AppRouterInstance = replace ? 'replace' : 'push'
router[method](href, { forceOptimisticNavigation: !prefetchEnabled })
} }
} }
...@@ -212,7 +199,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -212,7 +199,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
const optionalPropsGuard: Record<LinkPropsOptional, true> = { const optionalPropsGuard: Record<LinkPropsOptional, true> = {
as: true, as: true,
replace: true, replace: true,
soft: true,
scroll: true, scroll: true,
shallow: true, shallow: true,
passHref: true, passHref: true,
...@@ -259,7 +245,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -259,7 +245,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
} }
} else if ( } else if (
key === 'replace' || key === 'replace' ||
key === 'soft' ||
key === 'scroll' || key === 'scroll' ||
key === 'shallow' || key === 'shallow' ||
key === 'passHref' || key === 'passHref' ||
...@@ -300,7 +285,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -300,7 +285,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
prefetch: prefetchProp, prefetch: prefetchProp,
passHref, passHref,
replace, replace,
soft,
shallow, shallow,
scroll, scroll,
locale, locale,
...@@ -455,11 +439,11 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -455,11 +439,11 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
href, href,
as, as,
replace, replace,
soft,
shallow, shallow,
scroll, scroll,
locale, locale,
appRouter ? startTransition : undefined appRouter ? startTransition : undefined,
p
) )
} }
}, },
...@@ -474,8 +458,12 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -474,8 +458,12 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
) { ) {
child.props.onMouseEnter(e) child.props.onMouseEnter(e)
} }
if (isLocalURL(href)) {
prefetch(router, href, as, { priority: true }) // Check for not prefetch disabled in page using appRouter
if (!(!p && appRouter)) {
if (isLocalURL(href)) {
prefetch(router, href, as, { priority: true })
}
} }
}, },
onTouchStart: (e: React.TouchEvent<HTMLAnchorElement>) => { onTouchStart: (e: React.TouchEvent<HTMLAnchorElement>) => {
...@@ -491,8 +479,11 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -491,8 +479,11 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
child.props.onTouchStart(e) child.props.onTouchStart(e)
} }
if (isLocalURL(href)) { // Check for not prefetch disabled in page using appRouter
prefetch(router, href, as, { priority: true }) if (!(!p && appRouter)) {
if (isLocalURL(href)) {
prefetch(router, href, as, { priority: true })
}
} }
}, },
} }
......
...@@ -298,8 +298,7 @@ export type FlightRouterState = [ ...@@ -298,8 +298,7 @@ export type FlightRouterState = [
segment: Segment, segment: Segment,
parallelRoutes: { [parallelRouterKey: string]: FlightRouterState }, parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },
url?: string, url?: string,
refresh?: 'refetch', refresh?: 'refetch'
loading?: 'loading'
] ]
/** /**
...@@ -327,7 +326,7 @@ export type FlightDataPath = ...@@ -327,7 +326,7 @@ export type FlightDataPath =
...FlightSegmentPath, ...FlightSegmentPath,
/* segment of the rendered slice: */ Segment, /* segment of the rendered slice: */ Segment,
/* treePatch */ FlightRouterState, /* treePatch */ FlightRouterState,
/* subTreeData: */ React.ReactNode /* subTreeData: */ React.ReactNode | null // Can be null during prefetch if there's no loading component
] ]
/** /**
...@@ -339,7 +338,10 @@ export type FlightData = Array<FlightDataPath> | string ...@@ -339,7 +338,10 @@ export type FlightData = Array<FlightDataPath> | string
* Property holding the current subTreeData. * Property holding the current subTreeData.
*/ */
export type ChildProp = { export type ChildProp = {
current: React.ReactNode /**
* Null indicates that the tree is partial
*/
current: React.ReactNode | null
segment: Segment segment: Segment
} }
...@@ -431,6 +433,7 @@ export async function renderToHTMLOrFlight( ...@@ -431,6 +433,7 @@ export async function renderToHTMLOrFlight(
} = renderOpts } = renderOpts
const isFlight = query.__flight__ !== undefined const isFlight = query.__flight__ !== undefined
const isPrefetch = query.__flight_prefetch__ !== undefined
// Handle client-side navigation to pages directory // Handle client-side navigation to pages directory
if (isFlight && isPagesDir) { if (isFlight && isPagesDir) {
...@@ -565,9 +568,7 @@ export async function renderToHTMLOrFlight( ...@@ -565,9 +568,7 @@ export async function renderToHTMLOrFlight(
const createFlightRouterStateFromLoaderTree = ([ const createFlightRouterStateFromLoaderTree = ([
segment, segment,
parallelRoutes, parallelRoutes,
{ loading },
]: LoaderTree): FlightRouterState => { ]: LoaderTree): FlightRouterState => {
const hasLoading = Boolean(loading)
const dynamicParam = getDynamicParamFromSegment(segment) const dynamicParam = getDynamicParamFromSegment(segment)
const segmentTree: FlightRouterState = [ const segmentTree: FlightRouterState = [
...@@ -587,9 +588,6 @@ export async function renderToHTMLOrFlight( ...@@ -587,9 +588,6 @@ export async function renderToHTMLOrFlight(
) )
} }
if (hasLoading) {
segmentTree[4] = 'loading'
}
return segmentTree return segmentTree
} }
...@@ -671,6 +669,31 @@ export async function renderToHTMLOrFlight( ...@@ -671,6 +669,31 @@ export async function renderToHTMLOrFlight(
? [parallelRouteKey] ? [parallelRouteKey]
: [actualSegment, parallelRouteKey] : [actualSegment, parallelRouteKey]
const childSegment = parallelRoutes[parallelRouteKey][0]
const childSegmentParam = getDynamicParamFromSegment(childSegment)
if (isPrefetch && Loading) {
const childProp: ChildProp = {
// Null indicates the tree is not fully rendered
current: null,
segment: childSegmentParam
? childSegmentParam.treeSegment
: childSegment,
}
// This is turned back into an object below.
return [
parallelRouteKey,
<LayoutRouter
parallelRouterKey={parallelRouteKey}
segmentPath={createSegmentPath(currentSegmentPath)}
loading={Loading ? <Loading /> : undefined}
childProp={childProp}
rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove}
/>,
]
}
// Create the child component // Create the child component
const { Component: ChildComponent } = await createComponentTree({ const { Component: ChildComponent } = await createComponentTree({
createSegmentPath: (child) => { createSegmentPath: (child) => {
...@@ -681,8 +704,6 @@ export async function renderToHTMLOrFlight( ...@@ -681,8 +704,6 @@ export async function renderToHTMLOrFlight(
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
}) })
const childSegment = parallelRoutes[parallelRouteKey][0]
const childSegmentParam = getDynamicParamFromSegment(childSegment)
const childProp: ChildProp = { const childProp: ChildProp = {
current: <ChildComponent />, current: <ChildComponent />,
segment: childSegmentParam segment: childSegmentParam
...@@ -898,21 +919,23 @@ export async function renderToHTMLOrFlight( ...@@ -898,21 +919,23 @@ export async function renderToHTMLOrFlight(
actualSegment, actualSegment,
// Create router state using the slice of the loaderTree // Create router state using the slice of the loaderTree
createFlightRouterStateFromLoaderTree(loaderTreeToFilter), createFlightRouterStateFromLoaderTree(loaderTreeToFilter),
// Create component tree using the slice of the loaderTree // Check if one level down from the common layout has a loading component. If it doesn't only provide the router state as part of the Flight data.
React.createElement( isPrefetch && !Boolean(loaderTreeToFilter[2].loading)
( ? null
await createComponentTree( : // Create component tree using the slice of the loaderTree
// This ensures flightRouterPath is valid and filters down the tree React.createElement(
{ (
createSegmentPath: (child) => child, await createComponentTree(
loaderTree: loaderTreeToFilter, // This ensures flightRouterPath is valid and filters down the tree
parentParams: currentParams, {
firstItem: true, createSegmentPath: (child) => child,
// parentSegmentPath: '', loaderTree: loaderTreeToFilter,
} parentParams: currentParams,
) firstItem: true,
).Component }
), )
).Component
),
] ]
} }
......
...@@ -24,7 +24,11 @@ export type CacheNode = { ...@@ -24,7 +24,11 @@ export type CacheNode = {
parallelRoutes: Map<string, ChildSegmentMap> parallelRoutes: Map<string, ChildSegmentMap>
} }
export type AppRouterInstance = { interface NavigateOptions {
forceOptimisticNavigation?: boolean
}
export interface AppRouterInstance {
/** /**
* Reload the current page. Fetches new data from the server. * Reload the current page. Fetches new data from the server.
*/ */
...@@ -33,26 +37,16 @@ export type AppRouterInstance = { ...@@ -33,26 +37,16 @@ export type AppRouterInstance = {
* Hard navigate to the provided href. Fetches new data from the server. * Hard navigate to the provided href. Fetches new data from the server.
* Pushes a new history entry. * Pushes a new history entry.
*/ */
push(href: string): void push(href: string, options: NavigateOptions): void
/**
* Soft navigate to the provided href. Does not fetch data from the server if it was already fetched.
* Pushes a new history entry.
*/
softPush(href: string): void
/** /**
* Hard navigate to the provided href. Does not fetch data from the server if it was already fetched. * Hard navigate to the provided href. Does not fetch data from the server if it was already fetched.
* Replaces the current history entry. * Replaces the current history entry.
*/ */
replace(href: string): void replace(href: string, options: NavigateOptions): void
/**
* Soft navigate to the provided href. Does not fetch data from the server if it was already fetched.
* Replaces the current history entry.
*/
softReplace(href: string): void
/** /**
* Soft prefetch the provided href. Does not fetch data from the server if it was already fetched. * Soft prefetch the provided href. Does not fetch data from the server if it was already fetched.
*/ */
prefetch(href: string): Promise<void> prefetch(href: string): void
} }
export const AppRouterContext = React.createContext<AppRouterInstance>( export const AppRouterContext = React.createContext<AppRouterInstance>(
......
import Link from 'next/link'
export async function getServerSideProps() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: { a: 'b' },
}
}
export default function IdPage({ params }) {
if (params.id === '123') {
return (
<>
IdPage: {params.id}
<Link href="/dashboard/456">To 456</Link>
</>
)
}
return (
<>
IdPage: {params.id}
<Link href="/dashboard/123">To 123</Link>
</>
)
}
export async function getServerSideProps() {
await new Promise((resolve) => setTimeout(resolve, 2000))
return {
props: {
message: 'Hello World',
},
}
}
export default function DashboardLayout({ children, message }) {
return (
<>
<h1>Dashboard {message}</h1>
{children}
</>
)
}
export default function DashboardLoading() {
return <>Loading dashboard...</>
}
export async function getServerSideProps() {
await new Promise((resolve) => setTimeout(resolve, 3000))
return {
props: {
message: 'Welcome to the dashboard',
},
}
}
export default function DashboardPage({ message }) {
return (
<>
<p>{message}</p>
</>
)
}
export default function Root({ children }) {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>{children}</body>
</html>
)
}
export default function GlobalLoading() {
return <>Loading...</>
}
import Link from 'next/link' import Link from 'next/link'
export default function HomePage() {
export default function Page() {
return ( return (
<Link href="/with-id"> <>
<a id="link">With ID</a> <Link href="/dashboard">To Dashboard</Link>
</Link> </>
) )
} }
module.exports = {
experimental: {
appDir: true,
serverComponents: true,
legacyBrowsers: false,
browsersListForSwc: true,
},
}
import Link from 'next/link'
import { nanoid } from 'nanoid'
export default function Page({ params }) {
const other = params.id === '123' ? '456' : '123'
return (
<>
<h1 id={`render-id-${params.id}`}>{nanoid()}</h1>{' '}
<Link href={`/link-hard-push/${other}`}>
<a id="link">To {other}</a>
</Link>
</>
)
}
import Link from 'next/link'
import { nanoid } from 'nanoid'
export default function Page({ params }) {
const other = params.id === '123' ? '456' : '123'
return (
<>
<h1 id={`render-id-${params.id}`}>{nanoid()}</h1>{' '}
<Link href={`/link-hard-replace/${other}`} replace>
<a id="link">To {other}</a>
</Link>
</>
)
}
...@@ -2,7 +2,7 @@ import Link from 'next/link' ...@@ -2,7 +2,7 @@ import Link from 'next/link'
export default function Page() { export default function Page() {
return ( return (
<Link href="/with-id" soft> <Link href="/with-id">
<a id="link">With ID</a> <a id="link">With ID</a>
</Link> </Link>
) )
......
...@@ -5,10 +5,10 @@ export default function Page() { ...@@ -5,10 +5,10 @@ export default function Page() {
return ( return (
<> <>
<h1 id="render-id">{nanoid()}</h1> <h1 id="render-id">{nanoid()}</h1>
<Link href="/link-soft-replace" soft replace> <Link href="/link-soft-replace" replace>
<a id="self-link">Self Link</a> <a id="self-link">Self Link</a>
</Link> </Link>
<Link href="/link-soft-replace/subpage" soft replace> <Link href="/link-soft-replace/subpage" replace>
<a id="subpage-link">Subpage</a> <a id="subpage-link">Subpage</a>
</Link> </Link>
</> </>
......
...@@ -2,7 +2,7 @@ import Link from 'next/link' ...@@ -2,7 +2,7 @@ import Link from 'next/link'
export default function Page() { export default function Page() {
return ( return (
<Link href="/link-soft-replace" soft replace> <Link href="/link-soft-replace" replace>
<a id="back-link">Self Link</a> <a id="back-link">Self Link</a>
</Link> </Link>
) )
......
import { useRouter } from 'next/dist/client/components/hooks-client'
import React from 'react'
import { useEffect } from 'react'
export default function HardLink({ href, children, ...props }) {
const router = useRouter()
useEffect(() => {
router.prefetch(href)
}, [router, href])
return (
<a
{...props}
href={href}
onClick={(e) => {
e.preventDefault()
React.startTransition(() => {
router.push(href)
router.reload()
})
}}
>
{children}
</a>
)
}
import { nanoid } from 'nanoid' import { nanoid } from 'nanoid'
import Link from 'next/link' import Link from './link.client.js'
export default function Page() { export default function Page() {
return ( return (
<> <>
<h1 id="render-id">{nanoid()}</h1> <h1 id="render-id">{nanoid()}</h1>
<h2 id="from-navigation">hello from /navigation</h2> <h2 id="from-navigation">hello from /navigation</h2>
<Link href="/hooks/use-cookies"> <Link href="/hooks/use-cookies" id="use-cookies">
<a id="use-cookies">useCookies</a> useCookies
</Link> </Link>
<Link href="/hooks/use-headers"> <Link href="/hooks/use-headers" id="use-headers">
<a id="use-headers">useHeaders</a> useHeaders
</Link> </Link>
</> </>
) )
......
...@@ -293,66 +293,60 @@ describe('app dir', () => { ...@@ -293,66 +293,60 @@ describe('app dir', () => {
}) })
describe('<Link />', () => { describe('<Link />', () => {
// TODO-APP: fix development test it('should hard push', async () => {
it.skip('should hard push', async () => { const browser = await webdriver(next.url, '/link-hard-push/123')
const browser = await webdriver(next.url, '/link-hard-push')
try { try {
// Click the link on the page, and verify that the history entry was // Click the link on the page, and verify that the history entry was
// added. // added.
expect(await browser.eval('window.history.length')).toBe(2) expect(await browser.eval('window.history.length')).toBe(2)
await browser.elementById('link').click() await browser.elementById('link').click()
await browser.waitForElementByCss('#render-id') await browser.waitForElementByCss('#render-id-456')
expect(await browser.eval('window.history.length')).toBe(3) expect(await browser.eval('window.history.length')).toBe(3)
// Get the id on the rendered page. // Get the id on the rendered page.
const firstID = await browser.elementById('render-id').text() const firstID = await browser.elementById('render-id-456').text()
// Go back, and redo the navigation by clicking the link. // Go back, and redo the navigation by clicking the link.
await browser.back() await browser.back()
await browser.elementById('link').click() await browser.elementById('link').click()
await browser.waitForElementByCss('#render-id') await browser.waitForElementByCss('#render-id-456')
// Get the id again, and compare, they should not be the same. // Get the id again, and compare, they should not be the same.
const secondID = await browser.elementById('render-id').text() const secondID = await browser.elementById('render-id-456').text()
expect(secondID).not.toBe(firstID) expect(secondID).not.toBe(firstID)
} finally { } finally {
await browser.close() await browser.close()
} }
}) })
// TODO-APP: fix development test it('should hard replace', async () => {
it.skip('should hard replace', async () => { const browser = await webdriver(next.url, '/link-hard-replace/123')
const browser = await webdriver(next.url, '/link-hard-replace')
try { try {
// Get the render ID so we can compare it.
const firstID = await browser.elementById('render-id').text()
// Click the link on the page, and verify that the history entry was NOT // Click the link on the page, and verify that the history entry was NOT
// added. // added.
expect(await browser.eval('window.history.length')).toBe(2) expect(await browser.eval('window.history.length')).toBe(2)
await browser.elementById('self-link').click() await browser.elementById('link').click()
await browser.waitForElementByCss('#render-id') await browser.waitForElementByCss('#render-id-456')
expect(await browser.eval('window.history.length')).toBe(2) expect(await browser.eval('window.history.length')).toBe(2)
// Get the date again, and compare, they should not be the same. // Get the date again, and compare, they should not be the same.
const secondID = await browser.elementById('render-id').text() const firstId = await browser.elementById('render-id-456').text()
expect(secondID).not.toBe(firstID)
// Navigate to the subpage, verify that the history entry was NOT added. // Navigate to the subpage, verify that the history entry was NOT added.
await browser.elementById('subpage-link').click() await browser.elementById('link').click()
await browser.waitForElementByCss('#back-link') await browser.waitForElementByCss('#render-id-123')
expect(await browser.eval('window.history.length')).toBe(2) expect(await browser.eval('window.history.length')).toBe(2)
// Navigate back again, verify that the history entry was NOT added. // Navigate back again, verify that the history entry was NOT added.
await browser.elementById('back-link').click() await browser.elementById('link').click()
await browser.waitForElementByCss('#render-id') await browser.waitForElementByCss('#render-id-456')
expect(await browser.eval('window.history.length')).toBe(2) expect(await browser.eval('window.history.length')).toBe(2)
// Get the date again, and compare, they should not be the same. // Get the date again, and compare, they should not be the same.
const thirdID = await browser.elementById('render-id').text() const secondId = await browser.elementById('render-id-456').text()
expect(thirdID).not.toBe(secondID) expect(firstId).not.toBe(secondId)
} finally { } finally {
await browser.close() await browser.close()
} }
......
...@@ -119,7 +119,11 @@ describe('app dir - react server components', () => { ...@@ -119,7 +119,11 @@ describe('app dir - react server components', () => {
page.on('request', (request) => { page.on('request', (request) => {
requestsCount++ requestsCount++
const url = request.url() const url = request.url()
if (/\?__flight__=1/.test(url)) { if (
url.includes('__flight__=1') &&
// Prefetches also include `__flight__`
!url.includes('__flight_prefetch__=1')
) {
hasFlightRequest = true hasFlightRequest = true
} }
}) })
...@@ -231,7 +235,11 @@ describe('app dir - react server components', () => { ...@@ -231,7 +235,11 @@ describe('app dir - react server components', () => {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
const url = request.url() const url = request.url()
if (/\?__flight__=1/.test(url)) { if (
url.includes('__flight__=1') &&
// Prefetches also include `__flight__`
!url.includes('__flight_prefetch__=1')
) {
hasFlightRequest = true hasFlightRequest = true
} }
}) })
......
...@@ -17,7 +17,6 @@ export default function LinkPage({ queryId }) { ...@@ -17,7 +17,6 @@ export default function LinkPage({ queryId }) {
} }
export function getServerSideProps(ctx) { export function getServerSideProps(ctx) {
// FIXME: query is missing
const { searchParams } = ctx const { searchParams } = ctx
return { return {
props: { props: {
......
...@@ -116,7 +116,9 @@ export default async function webdriver( ...@@ -116,7 +116,9 @@ export default async function webdriver(
// if it's not a Next.js app return // if it's not a Next.js app return
if ( if (
document.documentElement.innerHTML.indexOf('__NEXT_DATA__') === -1 document.documentElement.innerHTML.indexOf('__NEXT_DATA__') === -1 &&
// @ts-ignore next exists on window if it's a Next.js page.
typeof (window as any).next?.version === 'undefined'
) { ) {
console.log('Not a next.js page, resolving hydrate check') console.log('Not a next.js page, resolving hydrate check')
callback() callback()
......
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