Unverified Commit 83e47acd authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Simplify scroll restoration with shared ScrollRef on CacheNode (#91348)

Replaces the segment-path-matching scroll system with a simpler model
based on a shared mutable ScrollRef on CacheNode.

The old system accumulated segment paths during navigation and matched
them in layout-router to decide which segments should scroll. This was
necessary when CacheNodes were created lazily during render. Now that we
construct the entire CacheNode tree immediately upon navigation, we can
assign a shared ScrollRef directly to each new leaf node. When any
segment scrolls, it flips the ref to false, preventing other segments
from also scrolling. This removes all the segment path accumulation and
matching logic.

Fixes a regression where calling `refresh()` from a server action
scrolled the page to the top. The old system had a semantic gap between
`null` (no segments) and `[]` (scroll everything) — a server action
refresh with no new segments fell through to a path that scrolled
unconditionally. The new model avoids this: refresh creates no new
CacheNodes, so no ScrollRef is assigned, and nothing scrolls.

Repro: https://github.com/stipsan/nextjs-refresh-regression-repro

There is extensive existing test coverage for scroll restoration
behavior. This adds one additional test for the server action refresh
bug.
parent 855f0a3f
......@@ -8,6 +8,7 @@ import { useMergedRef } from '../use-merged-ref'
import { isAbsoluteUrl } from '../../shared/lib/utils'
import { addBasePath } from '../add-base-path'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import { ScrollBehavior } from '../components/router-reducer/router-reducer-types'
import type { PENDING_LINK_STATUS } from '../components/links'
import {
IDLE_LINK_STATUS,
......@@ -307,7 +308,7 @@ function linkClicked(
dispatchNavigateAction(
href,
replace ? 'replace' : 'push',
scroll ?? true,
scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,
linkInstanceRef.current,
transitionTypes
)
......
......@@ -9,6 +9,7 @@ import {
type NavigateAction,
ACTION_HMR_REFRESH,
PrefetchKind,
ScrollBehavior,
type AppHistoryState,
} from './router-reducer/router-reducer-types'
import { reducer } from './router-reducer/router-reducer'
......@@ -277,7 +278,7 @@ function getProfilingHookForOnNavigationStart() {
export function dispatchNavigateAction(
href: string,
navigateType: NavigateAction['navigateType'],
shouldScroll: boolean,
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined
): void {
......@@ -307,7 +308,7 @@ export function dispatchNavigateAction(
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
shouldScroll,
scrollBehavior,
navigateType,
})
}
......@@ -356,7 +357,10 @@ function gesturePush(href: string, options?: NavigateOptions): void {
// Fork the router state for the duration of the gesture transition.
const currentUrl = new URL(state.canonicalUrl, location.href)
const shouldScroll = options?.scroll ?? true
const scrollBehavior =
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default
// This is a special freshness policy that prevents dynamic requests from
// being spawned. During the gesture, we should only show the cached
// prefetched UI, not dynamic data.
......@@ -373,7 +377,7 @@ function gesturePush(href: string, options?: NavigateOptions): void {
state.tree,
state.nextUrl,
freshnessPolicy,
shouldScroll,
scrollBehavior,
'push'
)
dispatchGestureState(forkedGestureState)
......@@ -442,7 +446,9 @@ export const publicAppRouterInstance: AppRouterInstance = {
dispatchNavigateAction(
href,
'replace',
options?.scroll ?? true,
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes
)
......@@ -458,7 +464,9 @@ export const publicAppRouterInstance: AppRouterInstance = {
dispatchNavigateAction(
href,
'push',
options?.scroll ?? true,
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes
)
......
......@@ -233,10 +233,10 @@ export function createInitialRouterState({
preserveCustomHistoryState: true,
},
focusAndScrollRef: {
apply: false,
scrollRef: null,
forceScroll: false,
onlyHashChange: false,
hashFragment: null,
segmentPaths: [],
},
canonicalUrl,
renderedSearch: initialRenderedSearch,
......
......@@ -24,7 +24,7 @@ export function navigateReducer(
state: ReadonlyReducerState,
action: NavigateAction
): ReducerState {
const { url, isExternalUrl, navigateType, shouldScroll } = action
const { url, isExternalUrl, navigateType, scrollBehavior } = action
if (isExternalUrl) {
return completeHardNavigation(state, url, navigateType)
......@@ -50,7 +50,7 @@ export function navigateReducer(
state.tree,
state.nextUrl,
FreshnessPolicy.Default,
shouldScroll,
scrollBehavior,
navigateType
)
}
......@@ -3,6 +3,7 @@ import type {
ReducerState,
RefreshAction,
} from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types'
import {
convertServerPatchToFullTree,
navigateToKnownRoute,
......@@ -56,7 +57,7 @@ export function refreshDynamicData(
const currentUrl = new URL(currentCanonicalUrl, location.origin)
const currentRenderedSearch = state.renderedSearch
const currentFlightRouterState = state.tree
const shouldScroll = false
const scrollBehavior = ScrollBehavior.NoScroll
// Create a NavigationSeed from the current FlightRouterState.
// TODO: Eventually we will store this type directly on the state object
......@@ -82,7 +83,7 @@ export function refreshDynamicData(
currentFlightRouterState,
freshnessPolicy,
nextUrlForRefresh,
shouldScroll,
scrollBehavior,
navigateType,
null,
// Refresh navigations don't use route prediction, so there's no route
......
......@@ -45,8 +45,8 @@ export function restoreReducer(
const now = Date.now()
const accumulation: NavigationRequestAccumulation = {
scrollableSegments: null,
separateRefreshUrls: null,
scrollRef: null,
}
const restoreSeed = convertServerPatchToFullTree(
treeToRestore,
......
......@@ -29,6 +29,7 @@ import type {
ReducerState,
ServerActionAction,
} from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types'
import { assignLocation } from '../../../assign-location'
import { createHrefFromUrl } from '../create-href-from-url'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
......@@ -416,7 +417,7 @@ export function serverActionReducer(
const redirectUrl =
redirectLocation !== undefined ? redirectLocation : currentUrl
const currentFlightRouterState = state.tree
const shouldScroll = true
const scrollBehavior = ScrollBehavior.Default
// If the action triggered a revalidation of the cache, we should also
// refresh all the dynamic data.
......@@ -472,7 +473,7 @@ export function serverActionReducer(
currentFlightRouterState,
freshnessPolicy,
nextUrl,
shouldScroll,
scrollBehavior,
navigateType,
null,
// Server action redirects don't use route prediction - we already
......@@ -494,7 +495,7 @@ export function serverActionReducer(
currentFlightRouterState,
nextUrl,
freshnessPolicy,
shouldScroll,
scrollBehavior,
navigateType
)
},
......
......@@ -4,6 +4,7 @@ import {
type ServerPatchAction,
type ReducerState,
type ReadonlyReducerState,
ScrollBehavior,
} from '../router-reducer-types'
import {
completeHardNavigation,
......@@ -41,7 +42,7 @@ export function serverPatchReducer(
// using the tree we just received from the server.
const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl
const shouldScroll = true
const scrollBehavior = ScrollBehavior.Default
const now = Date.now()
return navigateToKnownRoute(
now,
......@@ -55,7 +56,7 @@ export function serverPatchReducer(
state.tree,
FreshnessPolicy.RefreshAll,
retryNextUrl,
shouldScroll,
scrollBehavior,
navigateType,
null,
// Server patch (retry) navigations don't use route prediction. This is
......
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type {
FlightRouterState,
FlightSegmentPath,
} from '../../../shared/lib/app-router-types'
import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/navigation'
import type { FetchServerResponseResult } from './fetch-server-response'
......@@ -94,7 +91,7 @@ export interface NavigateAction {
isExternalUrl: boolean
locationSearch: Location['search']
navigateType: 'push' | 'replace'
shouldScroll: boolean
scrollBehavior: ScrollBehavior
}
/**
......@@ -163,19 +160,37 @@ export interface PushRef {
preserveCustomHistoryState: boolean
}
/**
* Controls the scroll behavior for a navigation.
*/
export const enum ScrollBehavior {
/** Use per-node ScrollRef to decide whether to scroll. */
Default = 0,
/** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */
NoScroll = 1,
}
export type FocusAndScrollRef = {
/**
* If focus and scroll should be set in the layout-router's useEffect()
* The scroll ref from the most recent navigation. Set to whatever was
* accumulated during tree construction (or null if nothing was
* accumulated). On the next navigation, if new scroll targets are
* created, the previous scrollRef is invalidated by setting
* `current = false`.
*/
apply: boolean
scrollRef: ScrollRef | null
/**
* The hash fragment that should be scrolled to.
* When true, the scroll handler uses `focusAndScrollRef.scrollRef`
* for every segment regardless of per-node state. Used for hash-only
* navigations where every segment should be treated as a scroll
* target. When false, the handler checks `cacheNode.scrollRef`
* instead (per-node), so only segments that actually navigated scroll.
*/
hashFragment: string | null
forceScroll: boolean
/**
* The paths of the segments that should be focused.
* The hash fragment that should be scrolled to.
*/
segmentPaths: FlightSegmentPath[]
hashFragment: string | null
/**
* If only the URLs hash fragment changed
*/
......
......@@ -49,8 +49,25 @@ export type CacheNode = {
head: HeadData
slots: Record<string, CacheNode> | null
/**
* A shared mutable ref that tracks whether this segment should be scrolled
* to. All new segments created during a single navigation share the same
* ref. When any segment's scroll handler fires, it sets `current` to
* `false` so no other segment scrolls for the same navigation.
*
* `null` means this segment is not a scroll target (e.g., a reused shared
* layout segment).
*/
scrollRef: ScrollRef | null
}
/**
* A mutable ref shared across all new segments created during a single
* navigation. Used to ensure that only one segment scrolls per navigation.
*/
export type ScrollRef = { current: boolean }
export type DynamicParamTypes =
| 'catchall'
| 'catchall-intercepted-(..)(..)'
......
......@@ -336,8 +336,8 @@ describe(`Terminal Logging (${bundlerName})`, () => {
...
<RenderFromTemplateContext>
<ScrollAndMaybeFocusHandler segmentPath={[...]}>
<${innerScrollAndMaybeFocusHandlerName} segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}>
<ScrollAndMaybeFocusHandler cacheNode={{rsc:{...}, ...}}>
<${innerScrollAndMaybeFocusHandlerName} focusAndScrollRef={{scrollRef:null, ...}} cacheNode={{rsc:{...}, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary name="hydration-..." loading={null}>
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
......
'use server'
import { refresh } from 'next/cache'
export async function refreshAction() {
refresh()
}
import { refreshAction } from './actions'
import { connection } from 'next/server'
export default async function Page() {
await connection()
const timestamp = Date.now()
return (
<>
<div style={{ height: '200vh' }} />
<form action={refreshAction}>
<button id="refresh-button" type="submit">
Refresh
</button>
</form>
<div id="server-timestamp">{timestamp}</div>
<div style={{ height: '200vh' }} />
</>
)
}
......@@ -173,6 +173,33 @@ describe('router autoscrolling on navigation', () => {
)
})
describe('server action refresh', () => {
it('should not scroll when refresh() is called from a server action', async () => {
const browser = await next.browser('/server-action-refresh')
const initialTimestamp = await browser
.elementByCss('#server-timestamp')
.text()
// Scroll down past the first spacer div
await scrollTo(browser, { x: 0, y: 1000 })
// Click the refresh button which calls refresh() via a server action
await browser.elementByCss('#refresh-button').click()
// Wait for the action to complete by checking the server timestamp
await retry(async () => {
const newTimestamp = await browser
.elementByCss('#server-timestamp')
.text()
expect(newTimestamp).not.toBe(initialTimestamp)
})
// Scroll position should be preserved
await waitForScrollToComplete(browser, { x: 0, y: 1000 })
})
})
describe('bugs', () => {
it('Should scroll to the top of the layout when the first child is display none', async () => {
const browser = await next.browser('/')
......
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