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 {
ReducerState,
} from '../router-reducer-types'
function handleMutable(
export function handleMutable(
state: ReadonlyReducerState,
mutable: Mutable
): ReducerState {
return {
// Set href.
canonicalUrl:
typeof mutable.canonicalUrl !== 'undefined' ? mutable.canonicalUrl : '',
typeof mutable.canonicalUrl !== 'undefined'
? mutable.canonicalUrl === state.canonicalUrl
? state.canonicalUrl
: mutable.canonicalUrl
: state.canonicalUrl,
pushRef: {
pendingPush:
typeof mutable.pendingPush !== 'undefined'
? mutable.pendingPush
: false,
: state.pushRef.pendingPush,
mpaNavigation:
typeof mutable.mpaNavigation !== 'undefined'
? mutable.mpaNavigation
: false,
: state.pushRef.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: {
apply:
typeof mutable.applyFocusAndScroll !== 'undefined'
? mutable.applyFocusAndScroll
: true,
: state.focusAndScrollRef.apply,
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
......@@ -61,11 +65,11 @@ function handleMutable(
}
}
function applyFlightData(
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)
......@@ -89,7 +93,7 @@ function applyFlightData(
return true
}
function handleExternalUrl(
export function handleExternalUrl(
state: ReadonlyReducerState,
mutable: Mutable,
url: string,
......@@ -125,10 +129,7 @@ export function navigateReducer(
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
if (isForCurrentTree) {
const result = handleMutable(state, mutable)
if (result) {
return result
}
return handleMutable(state, mutable)
}
if (isExternalUrl) {
......@@ -146,6 +147,10 @@ export function navigateReducer(
}
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.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(
......@@ -183,7 +188,6 @@ export function navigateReducer(
mutable.previousTree = state.tree
mutable.patchedTree = newTree
mutable.applyFocusAndScroll = true
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: href
......@@ -273,6 +277,10 @@ export function navigateReducer(
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: href
......@@ -280,7 +288,6 @@ export function navigateReducer(
mutable.previousTree = state.tree
mutable.patchedTree = newTree
mutable.applyFocusAndScroll = true
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
mutable.pendingPush = pendingPush
const applied = applyFlightData(state, cache, flightDataPath)
......
import { CacheStates } from '../../../../shared/lib/app-router-context'
import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
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 { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import {
......@@ -11,6 +9,11 @@ import {
ReducerState,
RefreshAction,
} from '../router-reducer-types'
import {
handleMutable,
applyFlightData,
handleExternalUrl,
} from './navigate-reducer'
export function refreshReducer(
state: ReadonlyReducerState,
......@@ -22,41 +25,8 @@ export function refreshReducer(
const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
if (mutable.mpaNavigation && isForCurrentTree) {
return {
// 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 (isForCurrentTree) {
return handleMutable(state, mutable)
}
if (!cache.data) {
......@@ -75,14 +45,12 @@ export function refreshReducer(
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return {
canonicalUrl: flightData,
pushRef: { pendingPush: true, mpaNavigation: true },
focusAndScrollRef: { apply: false },
cache: state.cache,
prefetchCache: state.prefetchCache,
tree: state.tree,
}
return handleExternalUrl(
state,
mutable,
flightData,
state.pushRef.pendingPush
)
}
// Remove cache.data as it has been resolved at this point.
......@@ -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.
const [treePatch, subTreeData, head] = flightDataPath
const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
......@@ -111,6 +79,10 @@ export function refreshReducer(
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush)
}
const canonicalUrlOverrideHref = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: undefined
......@@ -119,26 +91,15 @@ export function refreshReducer(
mutable.canonicalUrl = canonicalUrlOverrideHref
}
const applied = applyFlightData(state, cache, flightDataPath)
if (applied) {
mutable.cache = cache
}
mutable.previousTree = state.tree
mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
// Set subTreeData for the root node of the cache.
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,
}
mutable.canonicalUrl = href
return handleMutable(state, mutable)
}
import { CacheStates } from '../../../../shared/lib/app-router-context'
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 { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import {
......@@ -9,6 +6,11 @@ import {
ReducerState,
ReadonlyReducerState,
} from '../router-reducer-types'
import {
handleMutable,
applyFlightData,
handleExternalUrl,
} from './navigate-reducer'
export function serverPatchReducer(
state: ReadonlyReducerState,
......@@ -17,69 +19,30 @@ export function serverPatchReducer(
const { flightData, previousTree, overrideCanonicalUrl, cache, mutable } =
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.
// 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
console.log('TREE MISMATCH')
// Keep everything as-is.
return state
}
if (mutable.mpaNavigation) {
return {
// 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,
}
if (mutable.previousTree) {
return handleMutable(state, mutable)
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return {
// Set href.
canonicalUrl: flightData,
// Enable mpaNavigation as this is a navigation that the app-router shouldn't handle.
pushRef: { pendingPush: true, mpaNavigation: true },
// 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,
}
return handleExternalUrl(
state,
mutable,
flightData,
state.pushRef.pendingPush
)
}
// 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(
// 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 [treePatch, subTreeData, head] = flightDataPath.slice(-3)
const [treePatch] = flightDataPath.slice(-3, -2)
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
......@@ -100,6 +63,15 @@ export function serverPatchReducer(
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(state.tree, newTree)) {
return handleExternalUrl(
state,
mutable,
state.canonicalUrl,
state.pushRef.pendingPush
)
}
const canonicalUrlOverrideHref = overrideCanonicalUrl
? createHrefFromUrl(overrideCanonicalUrl)
: undefined
......@@ -108,34 +80,12 @@ export function serverPatchReducer(
mutable.canonicalUrl = canonicalUrlOverrideHref
}
mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
applyFlightData(state, cache, flightDataPath)
// Root refresh
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
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
}
mutable.previousTree = state.tree
mutable.patchedTree = newTree
mutable.cache = cache
mutable.applyFocusAndScroll = false
return {
// 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,
}
return handleMutable(state, mutable)
}
......@@ -140,8 +140,7 @@ describe('router autoscrolling on navigation', () => {
await waitForScrollToComplete(browser, { x: 0, y: 12000 })
})
// TODO fix next js to pass this
it.skip('should not stop router.push() from scrolling', async () => {
it('should not stop router.push() from scrolling', async () => {
const browser = await webdriver(next.url, '/10/10000/100/1000/page1')
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