Unverified Commit 30a6c512 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor server-patch-reducer and refresh-reducer to use applyFlightData and…

Refactor server-patch-reducer and refresh-reducer to use applyFlightData and handleMutable (#45608)Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Jan Kaifer <jan@kaifer.cz>

Follow-up to #45555. This uses the same handling of mutable for
serverPatchReducer and refreshReducer.

Fixes NEXT-213

Ensures scroll position is still applied when calling `router.push()`
and `router.refresh()` in a single transition:
```tsx
startTransition(() => {
    router.push('/dashboard')
    router.refresh()
})
```
<!--
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)

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: 's avatarJan Kaifer <jan@kaifer.cz>
parent fd5a0cf9
...@@ -25,30 +25,34 @@ import { ...@@ -25,30 +25,34 @@ import {
ReducerState, ReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
function handleMutable( export function handleMutable(
state: ReadonlyReducerState, state: ReadonlyReducerState,
mutable: Mutable mutable: Mutable
): ReducerState { ): ReducerState {
return { return {
// Set href. // Set href.
canonicalUrl: canonicalUrl:
typeof mutable.canonicalUrl !== 'undefined' ? mutable.canonicalUrl : '', typeof mutable.canonicalUrl !== 'undefined'
? mutable.canonicalUrl === state.canonicalUrl
? state.canonicalUrl
: mutable.canonicalUrl
: state.canonicalUrl,
pushRef: { pushRef: {
pendingPush: pendingPush:
typeof mutable.pendingPush !== 'undefined' typeof mutable.pendingPush !== 'undefined'
? mutable.pendingPush ? mutable.pendingPush
: false, : state.pushRef.pendingPush,
mpaNavigation: mpaNavigation:
typeof mutable.mpaNavigation !== 'undefined' typeof mutable.mpaNavigation !== 'undefined'
? mutable.mpaNavigation ? mutable.mpaNavigation
: false, : state.pushRef.mpaNavigation,
}, },
// All navigation requires scroll and focus management to trigger. // All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { focusAndScrollRef: {
apply: apply:
typeof mutable.applyFocusAndScroll !== 'undefined' typeof mutable.applyFocusAndScroll !== 'undefined'
? mutable.applyFocusAndScroll ? mutable.applyFocusAndScroll
: true, : state.focusAndScrollRef.apply,
}, },
// Apply cache. // Apply cache.
cache: mutable.cache ? mutable.cache : state.cache, cache: mutable.cache ? mutable.cache : state.cache,
...@@ -61,11 +65,11 @@ function handleMutable( ...@@ -61,11 +65,11 @@ function handleMutable(
} }
} }
function applyFlightData( export function applyFlightData(
state: ReadonlyReducerState, state: ReadonlyReducerState,
cache: CacheNode, cache: CacheNode,
flightDataPath: FlightDataPath flightDataPath: FlightDataPath
) { ): boolean {
// The one before last item is the router state tree patch // The one before last item is the router state tree patch
const [treePatch, subTreeData, head] = flightDataPath.slice(-3) const [treePatch, subTreeData, head] = flightDataPath.slice(-3)
...@@ -89,7 +93,7 @@ function applyFlightData( ...@@ -89,7 +93,7 @@ function applyFlightData(
return true return true
} }
function handleExternalUrl( export function handleExternalUrl(
state: ReadonlyReducerState, state: ReadonlyReducerState,
mutable: Mutable, mutable: Mutable,
url: string, url: string,
...@@ -125,10 +129,7 @@ export function navigateReducer( ...@@ -125,10 +129,7 @@ export function navigateReducer(
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree) JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
if (isForCurrentTree) { if (isForCurrentTree) {
const result = handleMutable(state, mutable) return handleMutable(state, mutable)
if (result) {
return result
}
} }
if (isExternalUrl) { if (isExternalUrl) {
...@@ -146,6 +147,10 @@ export function navigateReducer( ...@@ -146,6 +147,10 @@ export function navigateReducer(
} }
if (newTree !== null) { if (newTree !== null) {
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
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. // 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 flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice( const flightSegmentPath = flightDataPath.slice(
...@@ -183,7 +188,6 @@ export function navigateReducer( ...@@ -183,7 +188,6 @@ export function navigateReducer(
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.applyFocusAndScroll = true mutable.applyFocusAndScroll = true
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
mutable.canonicalUrl = canonicalUrlOverride mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride) ? createHrefFromUrl(canonicalUrlOverride)
: href : href
...@@ -273,6 +277,10 @@ export function navigateReducer( ...@@ -273,6 +277,10 @@ export function navigateReducer(
throw new Error('SEGMENT MISMATCH') throw new Error('SEGMENT MISMATCH')
} }
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
mutable.canonicalUrl = canonicalUrlOverride mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride) ? createHrefFromUrl(canonicalUrlOverride)
: href : href
...@@ -280,7 +288,6 @@ export function navigateReducer( ...@@ -280,7 +288,6 @@ export function navigateReducer(
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.applyFocusAndScroll = true mutable.applyFocusAndScroll = true
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
mutable.pendingPush = pendingPush mutable.pendingPush = pendingPush
const applied = applyFlightData(state, cache, flightDataPath) const applied = applyFlightData(state, cache, flightDataPath)
......
import { CacheStates } from '../../../../shared/lib/app-router-context'
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 { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import { import {
...@@ -11,6 +9,11 @@ import { ...@@ -11,6 +9,11 @@ import {
ReducerState, ReducerState,
RefreshAction, RefreshAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import {
handleMutable,
applyFlightData,
handleExternalUrl,
} from './navigate-reducer'
export function refreshReducer( export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -22,41 +25,8 @@ export function refreshReducer( ...@@ -22,41 +25,8 @@ export function refreshReducer(
const isForCurrentTree = const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree) JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
if (mutable.mpaNavigation && isForCurrentTree) { if (isForCurrentTree) {
return { return handleMutable(state, mutable)
// Set href.
canonicalUrl: mutable.canonicalUrl
? mutable.canonicalUrl
: state.canonicalUrl,
// TODO-APP: verify mpaNavigation not being set is correct here.
pushRef: {
pendingPush: true,
mpaNavigation: mutable.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: false },
// Apply cache.
cache: state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: state.tree,
}
}
// Handle concurrent rendering / strict mode case where the cache and tree were already populated.
if (mutable.patchedTree && isForCurrentTree) {
return {
// Set href.
canonicalUrl: mutable.canonicalUrl ? mutable.canonicalUrl : href,
// set pendingPush (always false in this case).
pushRef: state.pushRef,
// Apply focus and scroll.
// TODO-APP: might need to disable this for Fast Refresh.
focusAndScrollRef: { apply: false },
cache: cache,
prefetchCache: state.prefetchCache,
tree: mutable.patchedTree,
}
} }
if (!cache.data) { if (!cache.data) {
...@@ -75,14 +45,12 @@ export function refreshReducer( ...@@ -75,14 +45,12 @@ export function refreshReducer(
// 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 { return handleExternalUrl(
canonicalUrl: flightData, state,
pushRef: { pendingPush: true, mpaNavigation: true }, mutable,
focusAndScrollRef: { apply: false }, flightData,
cache: state.cache, state.pushRef.pendingPush
prefetchCache: state.prefetchCache, )
tree: state.tree,
}
} }
// Remove cache.data as it has been resolved at this point. // Remove cache.data as it has been resolved at this point.
...@@ -99,7 +67,7 @@ export function refreshReducer( ...@@ -99,7 +67,7 @@ export function refreshReducer(
} }
// Given the path can only have two items the items are only the router state and subTreeData for the root. // Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch, subTreeData, head] = flightDataPath const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree( const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove '' // TODO-APP: remove ''
[''], [''],
...@@ -111,6 +79,10 @@ export function refreshReducer( ...@@ -111,6 +79,10 @@ export function refreshReducer(
throw new Error('SEGMENT MISMATCH') throw new Error('SEGMENT MISMATCH')
} }
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush)
}
const canonicalUrlOverrideHref = canonicalUrlOverride const canonicalUrlOverrideHref = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride) ? createHrefFromUrl(canonicalUrlOverride)
: undefined : undefined
...@@ -119,26 +91,15 @@ export function refreshReducer( ...@@ -119,26 +91,15 @@ export function refreshReducer(
mutable.canonicalUrl = canonicalUrlOverrideHref mutable.canonicalUrl = canonicalUrlOverrideHref
} }
const applied = applyFlightData(state, cache, flightDataPath)
if (applied) {
mutable.cache = cache
}
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree) mutable.canonicalUrl = href
// Set subTreeData for the root node of the cache. return handleMutable(state, mutable)
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head)
return {
// Set href, this doesn't reuse the state.canonicalUrl as because of concurrent rendering the href might change between dispatching and applying.
canonicalUrl: canonicalUrlOverrideHref ? canonicalUrlOverrideHref : href,
// set pendingPush (always false in this case).
pushRef: state.pushRef,
// TODO-APP: might need to disable this for Fast Refresh.
focusAndScrollRef: { apply: false },
// Apply patched cache.
cache: cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: newTree,
}
} }
import { CacheStates } from '../../../../shared/lib/app-router-context'
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 { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import { import {
...@@ -9,6 +6,11 @@ import { ...@@ -9,6 +6,11 @@ import {
ReducerState, ReducerState,
ReadonlyReducerState, ReadonlyReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import {
handleMutable,
applyFlightData,
handleExternalUrl,
} from './navigate-reducer'
export function serverPatchReducer( export function serverPatchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -17,69 +19,30 @@ export function serverPatchReducer( ...@@ -17,69 +19,30 @@ export function serverPatchReducer(
const { flightData, previousTree, overrideCanonicalUrl, cache, mutable } = const { flightData, previousTree, overrideCanonicalUrl, cache, mutable } =
action action
const isForCurrentTree =
JSON.stringify(previousTree) === JSON.stringify(state.tree)
// When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs. // When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs.
// In that case opt-out of applying the patch given that the data could be stale. // In that case opt-out of applying the patch given that the data could be stale.
if (JSON.stringify(previousTree) !== JSON.stringify(state.tree)) { if (!isForCurrentTree) {
// TODO-APP: Handle tree mismatch // TODO-APP: Handle tree mismatch
console.log('TREE MISMATCH') console.log('TREE MISMATCH')
// Keep everything as-is. // Keep everything as-is.
return state return state
} }
if (mutable.mpaNavigation) { if (mutable.previousTree) {
return { return handleMutable(state, mutable)
// Set href.
canonicalUrl: mutable.canonicalUrl
? mutable.canonicalUrl
: state.canonicalUrl,
// TODO-APP: verify mpaNavigation not being set is correct here.
pushRef: {
pendingPush: true,
mpaNavigation: mutable.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: false },
// Apply cache.
cache: state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: state.tree,
}
}
// Handle concurrent rendering / strict mode case where the cache and tree were already populated.
if (mutable.patchedTree) {
return {
// Keep href as it was set during navigate / restore
canonicalUrl: mutable.canonicalUrl
? mutable.canonicalUrl
: state.canonicalUrl,
// Keep pushRef as server-patch only causes cache/tree update.
pushRef: state.pushRef,
// Keep focusAndScrollRef as server-patch only causes cache/tree update.
focusAndScrollRef: state.focusAndScrollRef,
// Apply patched router state
tree: mutable.patchedTree,
prefetchCache: state.prefetchCache,
// Apply patched cache
cache: cache,
}
} }
// 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 { return handleExternalUrl(
// Set href. state,
canonicalUrl: flightData, mutable,
// Enable mpaNavigation as this is a navigation that the app-router shouldn't handle. flightData,
pushRef: { pendingPush: true, mpaNavigation: true }, state.pushRef.pendingPush
// Don't apply scroll and focus management. )
focusAndScrollRef: { apply: false },
// Other state is kept as-is.
cache: state.cache,
prefetchCache: state.prefetchCache,
tree: state.tree,
}
} }
// TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths. // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
...@@ -87,7 +50,7 @@ export function serverPatchReducer( ...@@ -87,7 +50,7 @@ export function serverPatchReducer(
// Slices off the last segment (which is at -4) as it doesn't exist in the tree yet // Slices off the last segment (which is at -4) as it doesn't exist in the tree yet
const flightSegmentPath = flightDataPath.slice(0, -4) const flightSegmentPath = flightDataPath.slice(0, -4)
const [treePatch, subTreeData, head] = flightDataPath.slice(-3) const [treePatch] = flightDataPath.slice(-3, -2)
const newTree = applyRouterStatePatchToTree( const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove '' // TODO-APP: remove ''
...@@ -100,6 +63,15 @@ export function serverPatchReducer( ...@@ -100,6 +63,15 @@ export function serverPatchReducer(
throw new Error('SEGMENT MISMATCH') throw new Error('SEGMENT MISMATCH')
} }
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(
state,
mutable,
state.canonicalUrl,
state.pushRef.pendingPush
)
}
const canonicalUrlOverrideHref = overrideCanonicalUrl const canonicalUrlOverrideHref = overrideCanonicalUrl
? createHrefFromUrl(overrideCanonicalUrl) ? createHrefFromUrl(overrideCanonicalUrl)
: undefined : undefined
...@@ -108,34 +80,12 @@ export function serverPatchReducer( ...@@ -108,34 +80,12 @@ export function serverPatchReducer(
mutable.canonicalUrl = canonicalUrlOverrideHref mutable.canonicalUrl = canonicalUrlOverrideHref
} }
mutable.patchedTree = newTree applyFlightData(state, cache, flightDataPath)
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
// Root refresh mutable.previousTree = state.tree
if (flightDataPath.length === 3) { mutable.patchedTree = newTree
cache.status = CacheStates.READY mutable.cache = cache
cache.subTreeData = subTreeData mutable.applyFocusAndScroll = false
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
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
}
return { return handleMutable(state, mutable)
// Keep href as it was set during navigate / restore
canonicalUrl: canonicalUrlOverrideHref
? canonicalUrlOverrideHref
: state.canonicalUrl,
// Keep pushRef as server-patch only causes cache/tree update.
pushRef: state.pushRef,
// Keep focusAndScrollRef as server-patch only causes cache/tree update.
focusAndScrollRef: state.focusAndScrollRef,
// Apply patched router state
tree: newTree,
prefetchCache: state.prefetchCache,
// Apply patched cache
cache: cache,
}
} }
...@@ -140,8 +140,7 @@ describe('router autoscrolling on navigation', () => { ...@@ -140,8 +140,7 @@ describe('router autoscrolling on navigation', () => {
await waitForScrollToComplete(browser, { x: 0, y: 12000 }) await waitForScrollToComplete(browser, { x: 0, y: 12000 })
}) })
// TODO fix next js to pass this it('should not stop router.push() from scrolling', async () => {
it.skip('should not stop router.push() from scrolling', async () => {
const browser = await webdriver(next.url, '/10/10000/100/1000/page1') const browser = await webdriver(next.url, '/10/10000/100/1000/page1')
await scrollTo(browser, { x: 0, y: 12000 }) await scrollTo(browser, { x: 0, y: 12000 })
......
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