Unverified Commit 341daf9c authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Ensure router.refresh() matches revalidatePath('/') behavior (#46723)

Ensures `router.refresh()` matches the upcoming `revalidatePath('/')`
api. This also ensures that when server context has changed it applies
to all routes, not just the one that triggered the refresh.

- When `router.refresh()` is called we fetch the full RSC payload from
the server (root layout till the page)
- The client-side router cache is fully invalidated, effectively making
it empty
- The client-side router prefetch cache is fully invalidated,
effectively making it empty
- RSC payload is applied to the state


fix NEXT-590 ([link](https://linear.app/vercel/issue/NEXT-590))

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent a3dff7c8
...@@ -38,7 +38,6 @@ import { ...@@ -38,7 +38,6 @@ import {
createInitialRouterState, createInitialRouterState,
InitialRouterStateParameters, InitialRouterStateParameters,
} from './router-reducer/create-initial-router-state' } from './router-reducer/create-initial-router-state'
import { fetchServerResponse } from './router-reducer/fetch-server-response'
import { isBot } from '../../shared/lib/router/utils/is-bot' import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
...@@ -64,8 +63,6 @@ const HotReloader: ...@@ -64,8 +63,6 @@ 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)
const prefetched = new Set<string>()
type AppRouterProps = Omit< type AppRouterProps = Omit<
Omit<InitialRouterStateParameters, 'isServer' | 'location'>, Omit<InitialRouterStateParameters, 'isServer' | 'location'>,
'initialParallelRoutes' 'initialParallelRoutes'
...@@ -184,41 +181,23 @@ function Router({ ...@@ -184,41 +181,23 @@ function Router({
back: () => window.history.back(), back: () => window.history.back(),
forward: () => window.history.forward(), forward: () => window.history.forward(),
prefetch: async (href) => { prefetch: async (href) => {
const hrefWithBasePath = addBasePath(href)
// If prefetch has already been triggered, don't trigger it again. // If prefetch has already been triggered, don't trigger it again.
if ( if (isBot(window.navigator.userAgent)) {
prefetched.has(hrefWithBasePath) ||
(typeof window !== 'undefined' && isBot(window.navigator.userAgent))
) {
return return
} }
prefetched.add(hrefWithBasePath) const url = new URL(addBasePath(href), location.origin)
const url = new URL(hrefWithBasePath, location.origin)
// External urls can't be prefetched in the same way. // External urls can't be prefetched in the same way.
if (isExternalURL(url)) { if (isExternalURL(url)) {
return return
} }
try {
const routerTree = window.history.state?.tree || initialTree // @ts-ignore startTransition exists
const serverResponse = await fetchServerResponse( React.startTransition(() => {
dispatch({
type: ACTION_PREFETCH,
url, url,
// initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.
routerTree,
true
)
// @ts-ignore startTransition exists
React.startTransition(() => {
dispatch({
type: ACTION_PREFETCH,
url,
tree: routerTree,
serverResponse,
})
}) })
} catch (err) { })
console.error('PREFETCH ERROR', err)
}
}, },
replace: (href, options = {}) => { replace: (href, options = {}) => {
// @ts-ignore startTransition exists // @ts-ignore startTransition exists
...@@ -251,7 +230,7 @@ function Router({ ...@@ -251,7 +230,7 @@ function Router({
} }
return routerInstance return routerInstance
}, [dispatch, initialTree]) }, [dispatch])
useEffect(() => { useEffect(() => {
// When mpaNavigation flag is set do a hard navigation to the new url. // When mpaNavigation flag is set do a hard navigation to the new url.
......
import { CacheNode, CacheStates } from '../../../shared/lib/app-router-context'
import { FlightDataPath } from '../../../server/app-render/types'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'
import { ReadonlyReducerState } from './router-reducer-types'
export function applyFlightData(
state: ReadonlyReducerState,
cache: CacheNode,
flightDataPath: FlightDataPath
): boolean {
// The one before last item is the router state tree patch
const [treePatch, subTreeData, head] = flightDataPath.slice(-3)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData === null) {
return false
}
if (flightDataPath.length === 3) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head)
} else {
// Copy subTreeData for the root node of the cache.
cache.status = CacheStates.READY
cache.subTreeData = state.cache.subTreeData
// Create a copy of the existing cache with the subTreeData applied.
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
}
return true
}
export function createHrefFromUrl( export function createHrefFromUrl(
url: Pick<URL, 'pathname' | 'search' | 'hash'> url: Pick<URL, 'pathname' | 'search' | 'hash'>,
includeHash: boolean = true
): string { ): string {
return url.pathname + url.search + url.hash return url.pathname + url.search + (includeHash ? url.hash : '')
} }
...@@ -40,8 +40,6 @@ describe('createInitialRouterState', () => { ...@@ -40,8 +40,6 @@ describe('createInitialRouterState', () => {
initialHead: <title>Test</title>, initialHead: <title>Test</title>,
}) })
console.log(initialParallelRoutes)
const state2 = createInitialRouterState({ const state2 = createInitialRouterState({
initialTree, initialTree,
initialCanonicalUrl, initialCanonicalUrl,
......
import {
Mutable,
ReadonlyReducerState,
ReducerState,
} from './router-reducer-types'
export function handleMutable(
state: ReadonlyReducerState,
mutable: Mutable
): ReducerState {
return {
// Set href.
canonicalUrl:
typeof mutable.canonicalUrl !== 'undefined'
? mutable.canonicalUrl === state.canonicalUrl
? state.canonicalUrl
: mutable.canonicalUrl
: state.canonicalUrl,
pushRef: {
pendingPush:
typeof mutable.pendingPush !== 'undefined'
? mutable.pendingPush
: state.pushRef.pendingPush,
mpaNavigation:
typeof mutable.mpaNavigation !== 'undefined'
? mutable.mpaNavigation
: state.pushRef.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: {
apply:
typeof mutable.applyFocusAndScroll !== 'undefined'
? mutable.applyFocusAndScroll
: state.focusAndScrollRef.apply,
hashFragment:
// Empty hash should trigger default behavior of scrolling layout into view.
// #top is handled in layout-router.
mutable.hashFragment && mutable.hashFragment !== ''
? // Remove leading # and decode hash to make non-latin hashes work.
decodeURIComponent(mutable.hashFragment.slice(1))
: null,
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
prefetchCache: mutable.prefetchCache
? mutable.prefetchCache
: state.prefetchCache,
// Apply patched router state.
tree:
typeof mutable.patchedTree !== 'undefined'
? mutable.patchedTree
: state.tree,
}
}
...@@ -68,6 +68,7 @@ jest.mock('../fetch-server-response', () => { ...@@ -68,6 +68,7 @@ jest.mock('../fetch-server-response', () => {
}, },
} }
}) })
import { FlightRouterState } from '../../../../server/app-render/types' import { FlightRouterState } from '../../../../server/app-render/types'
import { import {
CacheNode, CacheNode,
...@@ -82,7 +83,7 @@ import { ...@@ -82,7 +83,7 @@ import {
} from '../router-reducer-types' } from '../router-reducer-types'
import { navigateReducer } from './navigate-reducer' import { navigateReducer } from './navigate-reducer'
import { prefetchReducer } from './prefetch-reducer' import { prefetchReducer } from './prefetch-reducer'
import { fetchServerResponse } from '../fetch-server-response' import { createRecordFromThenable } from '../create-record-from-thenable'
const getInitialRouterStateTree = (): FlightRouterState => [ const getInitialRouterStateTree = (): FlightRouterState => [
'', '',
...@@ -987,12 +988,9 @@ describe('navigateReducer', () => { ...@@ -987,12 +988,9 @@ describe('navigateReducer', () => {
]) ])
const url = new URL('/linking/about', 'https://localhost') const url = new URL('/linking/about', 'https://localhost')
const serverResponse = await fetchServerResponse(url, initialTree, true)
const prefetchAction: PrefetchAction = { const prefetchAction: PrefetchAction = {
type: ACTION_PREFETCH, type: ACTION_PREFETCH,
url, url,
tree: initialTree,
serverResponse,
} }
const state = createInitialRouterState({ const state = createInitialRouterState({
...@@ -1007,6 +1005,8 @@ describe('navigateReducer', () => { ...@@ -1007,6 +1005,8 @@ describe('navigateReducer', () => {
await runPromiseThrowChain(() => prefetchReducer(state, prefetchAction)) await runPromiseThrowChain(() => prefetchReducer(state, prefetchAction))
await state.prefetchCache.get(url.pathname + url.search)?.data
const state2 = createInitialRouterState({ const state2 = createInitialRouterState({
initialTree, initialTree,
initialHead: null, initialHead: null,
...@@ -1018,6 +1018,7 @@ describe('navigateReducer', () => { ...@@ -1018,6 +1018,7 @@ describe('navigateReducer', () => {
}) })
await runPromiseThrowChain(() => prefetchReducer(state2, prefetchAction)) await runPromiseThrowChain(() => prefetchReducer(state2, prefetchAction))
await state2.prefetchCache.get(url.pathname + url.search)?.data
const action: NavigateAction = { const action: NavigateAction = {
type: ACTION_NAVIGATE, type: ACTION_NAVIGATE,
...@@ -1041,42 +1042,43 @@ describe('navigateReducer', () => { ...@@ -1041,42 +1042,43 @@ describe('navigateReducer', () => {
navigateReducer(state2, action) navigateReducer(state2, action)
) )
const prom = Promise.resolve([
[
[
'children',
'linking',
'children',
'about',
[
'about',
{
children: ['', {}],
},
],
<h1>About Page!</h1>,
<React.Fragment>
<title>About page!</title>
</React.Fragment>,
],
],
undefined,
] as any)
const record = createRecordFromThenable(prom)
await prom
const expectedState: ReturnType<typeof navigateReducer> = { const expectedState: ReturnType<typeof navigateReducer> = {
prefetchCache: new Map([ prefetchCache: new Map([
[ [
'/linking/about', '/linking/about',
{ {
canonicalUrlOverride: undefined, data: record,
flightData: [ treeAtTimeOfPrefetch: [
[
'children',
'linking',
'children',
'about',
[
'about',
{
children: ['', {}],
},
],
<h1>About Page!</h1>,
<React.Fragment>
<title>About page!</title>
</React.Fragment>,
],
],
tree: [
'', '',
{ {
children: [ children: [
'linking', 'linking',
{ {
children: [ children: ['', {}],
'about',
{
children: ['', {}],
},
],
}, },
], ],
}, },
......
import { import { CacheStates } from '../../../../shared/lib/app-router-context'
CacheNode, import type { FlightSegmentPath } from '../../../../server/app-render/types'
CacheStates,
} from '../../../../shared/lib/app-router-context'
import type {
FlightDataPath,
FlightSegmentPath,
} from '../../../../server/app-render/types'
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value' import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'
import { fillCacheWithNewSubTreeData } from '../fill-cache-with-new-subtree-data'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath' import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property' import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
import { createOptimisticTree } from '../create-optimistic-tree' import { createOptimisticTree } from '../create-optimistic-tree'
...@@ -24,81 +16,8 @@ import type { ...@@ -24,81 +16,8 @@ import type {
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { handleMutable } from '../handle-mutable'
export function handleMutable( import { applyFlightData } from '../apply-flight-data'
state: ReadonlyReducerState,
mutable: Mutable
): ReducerState {
return {
// Set href.
canonicalUrl:
typeof mutable.canonicalUrl !== 'undefined'
? mutable.canonicalUrl === state.canonicalUrl
? state.canonicalUrl
: mutable.canonicalUrl
: state.canonicalUrl,
pushRef: {
pendingPush:
typeof mutable.pendingPush !== 'undefined'
? mutable.pendingPush
: state.pushRef.pendingPush,
mpaNavigation:
typeof mutable.mpaNavigation !== 'undefined'
? mutable.mpaNavigation
: state.pushRef.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: {
apply:
typeof mutable.applyFocusAndScroll !== 'undefined'
? mutable.applyFocusAndScroll
: state.focusAndScrollRef.apply,
hashFragment:
// Empty hash should trigger default behavior of scrolling layout into view.
// #top is handled in layout-router.
mutable.hashFragment && mutable.hashFragment !== ''
? // Remove leading # and decode hash to make non-latin hashes work.
decodeURIComponent(mutable.hashFragment.slice(1))
: null,
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree:
typeof mutable.patchedTree !== 'undefined'
? mutable.patchedTree
: state.tree,
}
}
export function applyFlightData(
state: ReadonlyReducerState,
cache: CacheNode,
flightDataPath: FlightDataPath
): boolean {
// The one before last item is the router state tree patch
const [treePatch, subTreeData, head] = flightDataPath.slice(-3)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData === null) {
return false
}
if (flightDataPath.length === 3) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head)
} else {
// Copy subTreeData for the root node of the cache.
cache.status = CacheStates.READY
cache.subTreeData = state.cache.subTreeData
// Create a copy of the existing cache with the subTreeData applied.
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
}
return true
}
export function handleExternalUrl( export function handleExternalUrl(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -143,28 +62,52 @@ export function navigateReducer( ...@@ -143,28 +62,52 @@ export function navigateReducer(
return handleExternalUrl(state, mutable, url.toString(), pendingPush) return handleExternalUrl(state, mutable, url.toString(), pendingPush)
} }
const prefetchValues = state.prefetchCache.get(href) const prefetchValues = state.prefetchCache.get(createHrefFromUrl(url, false))
if (prefetchValues) { if (prefetchValues) {
// The one before last item is the router state tree patch // The one before last item is the router state tree patch
const { flightData, tree: newTree, canonicalUrlOverride } = prefetchValues const { treeAtTimeOfPrefetch, data } = prefetchValues
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
const [flightData, canonicalUrlOverride] = readRecordValue(data!)
// Handle case when navigating to page in `pages` from `app` // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
return handleExternalUrl(state, mutable, flightData, pendingPush) return handleExternalUrl(state, mutable, flightData, pendingPush)
} }
// TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(
0,
-3
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const [treePatch] = flightDataPath.slice(-3)
// Create new tree based on the flightSegmentPath and router state patch
let newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
['', ...flightSegmentPath],
state.tree,
treePatch
)
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
// TODO-APP: This should instead fill in the missing pieces in `state.tree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.
if (newTree === null) {
newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
['', ...flightSegmentPath],
treeAtTimeOfPrefetch,
treePatch
)
}
if (newTree !== null) { if (newTree !== null) {
if (isNavigatingToNewRootLayout(state.tree, newTree)) { if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush) return handleExternalUrl(state, mutable, href, pendingPush)
} }
// TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(
0,
-3
) as unknown as FlightSegmentPath
const applied = applyFlightData(state, cache, flightDataPath) const applied = applyFlightData(state, cache, flightDataPath)
const hardNavigate = const hardNavigate =
......
...@@ -41,6 +41,7 @@ import { createInitialRouterState } from '../create-initial-router-state' ...@@ -41,6 +41,7 @@ import { createInitialRouterState } from '../create-initial-router-state'
import { PrefetchAction, ACTION_PREFETCH } from '../router-reducer-types' import { PrefetchAction, ACTION_PREFETCH } from '../router-reducer-types'
import { prefetchReducer } from './prefetch-reducer' import { prefetchReducer } from './prefetch-reducer'
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
const getInitialRouterStateTree = (): FlightRouterState => [ const getInitialRouterStateTree = (): FlightRouterState => [
'', '',
...@@ -127,33 +128,29 @@ describe('prefetchReducer', () => { ...@@ -127,33 +128,29 @@ describe('prefetchReducer', () => {
const action: PrefetchAction = { const action: PrefetchAction = {
type: ACTION_PREFETCH, type: ACTION_PREFETCH,
url, url,
tree: initialTree,
serverResponse,
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
prefetchReducer(state, action) prefetchReducer(state, action)
) )
const prom = Promise.resolve(serverResponse)
const record = createRecordFromThenable(prom)
await prom
const expectedState: ReturnType<typeof prefetchReducer> = { const expectedState: ReturnType<typeof prefetchReducer> = {
prefetchCache: new Map([ prefetchCache: new Map([
[ [
'/linking/about', '/linking/about',
{ {
canonicalUrlOverride: undefined, data: record,
flightData: serverResponse[0], treeAtTimeOfPrefetch: [
tree: [
'', '',
{ {
children: [ children: [
'linking', 'linking',
{ {
children: [ children: ['', {}],
'about',
{
children: ['', {}],
},
],
}, },
], ],
}, },
...@@ -269,8 +266,6 @@ describe('prefetchReducer', () => { ...@@ -269,8 +266,6 @@ describe('prefetchReducer', () => {
const action: PrefetchAction = { const action: PrefetchAction = {
type: ACTION_PREFETCH, type: ACTION_PREFETCH,
url, url,
tree: initialTree,
serverResponse,
} }
await runPromiseThrowChain(() => prefetchReducer(state, action)) await runPromiseThrowChain(() => prefetchReducer(state, action))
...@@ -279,25 +274,23 @@ describe('prefetchReducer', () => { ...@@ -279,25 +274,23 @@ describe('prefetchReducer', () => {
prefetchReducer(state2, action) prefetchReducer(state2, action)
) )
const prom = Promise.resolve(serverResponse)
const record = createRecordFromThenable(prom)
await prom
const expectedState: ReturnType<typeof prefetchReducer> = { const expectedState: ReturnType<typeof prefetchReducer> = {
prefetchCache: new Map([ prefetchCache: new Map([
[ [
'/linking/about', '/linking/about',
{ {
canonicalUrlOverride: undefined, data: record,
flightData: serverResponse[0], treeAtTimeOfPrefetch: [
tree: [
'', '',
{ {
children: [ children: [
'linking', 'linking',
{ {
children: [ children: ['', {}],
'about',
{
children: ['', {}],
},
],
}, },
], ],
}, },
......
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { fetchServerResponse } from '../fetch-server-response'
import { import {
PrefetchAction, PrefetchAction,
ReducerState, ReducerState,
ReadonlyReducerState, ReadonlyReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { createRecordFromThenable } from '../create-record-from-thenable'
export function prefetchReducer( export function prefetchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: PrefetchAction action: PrefetchAction
): ReducerState { ): ReducerState {
const { url, serverResponse } = action const { url } = action
const [flightData, canonicalUrlOverride] = serverResponse const href = createHrefFromUrl(
url,
// Ensures the hash is not part of the cache key as it does not affect fetching the server
false
)
if (typeof flightData === 'string') { // If the href was already prefetched it is not necessary to prefetch it again
if (state.prefetchCache.has(href)) {
return state return state
} }
const href = createHrefFromUrl(url) // fetchServerResponse is intentionally not awaited so that it can be unwrapped in the navigate-reducer
const serverResponse = createRecordFromThenable(
// TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths. fetchServerResponse(
const flightDataPath = flightData[0] url,
// initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.
// The one before last item is the router state tree patch state.tree,
const [treePatch] = flightDataPath.slice(-3) true
)
const flightSegmentPath = flightDataPath.slice(0, -3)
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
['', ...flightSegmentPath],
state.tree,
treePatch
) )
// Patch did not apply correctly
if (newTree === null) {
return state
}
// Create new tree based on the flightSegmentPath and router state patch // Create new tree based on the flightSegmentPath and router state patch
state.prefetchCache.set(href, { state.prefetchCache.set(href, {
flightData,
// Create new tree based on the flightSegmentPath and router state patch // Create new tree based on the flightSegmentPath and router state patch
tree: newTree, treeAtTimeOfPrefetch: state.tree,
canonicalUrlOverride, data: serverResponse,
}) })
return state return state
......
...@@ -378,7 +378,7 @@ describe('refreshReducer', () => { ...@@ -378,7 +378,7 @@ describe('refreshReducer', () => {
expect(newState).toMatchObject(expectedState) expect(newState).toMatchObject(expectedState)
}) })
it('should preserve existing segments (concurrent)', async () => { it('should invalidate all segments (concurrent)', async () => {
const initialTree = getInitialRouterStateTree() const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking' const initialCanonicalUrl = '/linking'
const children = ( const children = (
...@@ -536,10 +536,211 @@ describe('refreshReducer', () => { ...@@ -536,10 +536,211 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
}, },
], ],
[ ]),
],
]),
},
tree: [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
true,
],
}
expect(newState).toMatchObject(expectedState)
})
it('should invalidate prefetchCache (concurrent)', async () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
const children = (
<html>
<head></head>
<body>Root layout</body>
</html>
)
const initialParallelRoutes: CacheNode['parallelRoutes'] = new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
[
'about',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.READY,
data: null,
subTreeData: <>About page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>About layout level</>,
},
],
]),
],
])
const prefetchItem = {
canonicalUrlOverride: undefined,
flightData: [
[
'',
{
children: [
'linking',
{
children: [
'about',
{
children: ['', {}],
},
],
},
],
},
undefined,
undefined,
true,
],
<>About</>,
<>Head</>,
],
tree: [
'',
{
children: [
'linking',
{
children: [
'about', 'about',
{ {
status: CacheStates.READY, children: ['', {}],
},
],
},
],
},
undefined,
undefined,
true,
],
}
const state = createInitialRouterState({
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
state.prefetchCache.set('/linking/about', prefetchItem)
const state2 = createInitialRouterState({
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
state2.prefetchCache.set('/linking/about', prefetchItem)
const action: RefreshAction = {
type: ACTION_REFRESH,
cache: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: {},
origin: new URL('/linking', 'https://localhost').origin,
}
await runPromiseThrowChain(() => refreshReducer(state, action))
const newState = await runPromiseThrowChain(() =>
refreshReducer(state2, action)
)
const expectedState: ReturnType<typeof refreshReducer> = {
prefetchCache: new Map(),
pushRef: {
mpaNavigation: false,
pendingPush: false,
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
subTreeData: (
<html>
<head></head>
<body>
<h1>Linking Page!</h1>
</body>
</html>
),
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.LAZY_INITIALIZED,
parallelRoutes: new Map([ parallelRoutes: new Map([
[ [
'children', 'children',
...@@ -547,17 +748,22 @@ describe('refreshReducer', () => { ...@@ -547,17 +748,22 @@ describe('refreshReducer', () => {
[ [
'', '',
{ {
status: CacheStates.READY, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
subTreeData: <>About page</>, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
head: (
<>
<title>Linking page!</title>
</>
),
}, },
], ],
]), ]),
], ],
]), ]),
data: null, data: null,
subTreeData: <>About layout level</>, subTreeData: null,
}, },
], ],
]), ]),
......
...@@ -9,11 +9,10 @@ import { ...@@ -9,11 +9,10 @@ import {
ReducerState, ReducerState,
RefreshAction, RefreshAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import { import { handleExternalUrl } from './navigate-reducer'
handleMutable, import { handleMutable } from '../handle-mutable'
applyFlightData, import { CacheStates } from '../../../../shared/lib/app-router-context'
handleExternalUrl, import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'
} from './navigate-reducer'
export function refreshReducer( export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -91,10 +90,22 @@ export function refreshReducer( ...@@ -91,10 +90,22 @@ export function refreshReducer(
mutable.canonicalUrl = canonicalUrlOverrideHref mutable.canonicalUrl = canonicalUrlOverrideHref
} }
const applied = applyFlightData(state, cache, flightDataPath) // The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-2)
if (applied) {
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(
cache,
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined,
treePatch,
head
)
mutable.cache = cache mutable.cache = cache
mutable.prefetchCache = new Map()
} }
mutable.previousTree = state.tree mutable.previousTree = state.tree
......
...@@ -6,11 +6,9 @@ import { ...@@ -6,11 +6,9 @@ import {
ReducerState, ReducerState,
ReadonlyReducerState, ReadonlyReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { import { handleExternalUrl } from './navigate-reducer'
handleMutable, import { applyFlightData } from '../apply-flight-data'
applyFlightData, import { handleMutable } from '../handle-mutable'
handleExternalUrl,
} from './navigate-reducer'
export function serverPatchReducer( export function serverPatchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
......
...@@ -19,6 +19,7 @@ export interface Mutable { ...@@ -19,6 +19,7 @@ export interface Mutable {
applyFocusAndScroll?: boolean applyFocusAndScroll?: boolean
pendingPush?: boolean pendingPush?: boolean
cache?: CacheNode cache?: CacheNode
prefetchCache?: AppRouterState['prefetchCache']
hashFragment?: string hashFragment?: string
} }
...@@ -116,8 +117,6 @@ export interface ServerPatchAction { ...@@ -116,8 +117,6 @@ export interface ServerPatchAction {
export interface PrefetchAction { export interface PrefetchAction {
type: typeof ACTION_PREFETCH type: typeof ACTION_PREFETCH
url: URL url: URL
tree: FlightRouterState
serverResponse: Awaited<ReturnType<typeof fetchServerResponse>>
} }
interface PushRef { interface PushRef {
...@@ -164,9 +163,8 @@ export type AppRouterState = { ...@@ -164,9 +163,8 @@ export type AppRouterState = {
prefetchCache: Map< prefetchCache: Map<
string, string,
{ {
flightData: FlightData treeAtTimeOfPrefetch: FlightRouterState
tree: FlightRouterState data: ReturnType<typeof fetchServerResponse> | null
canonicalUrlOverride: URL | undefined
} }
> >
/** /**
......
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