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' ...@@ -8,6 +8,7 @@ import { useMergedRef } from '../use-merged-ref'
import { isAbsoluteUrl } from '../../shared/lib/utils' import { isAbsoluteUrl } from '../../shared/lib/utils'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { warnOnce } from '../../shared/lib/utils/warn-once' 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 type { PENDING_LINK_STATUS } from '../components/links'
import { import {
IDLE_LINK_STATUS, IDLE_LINK_STATUS,
...@@ -307,7 +308,7 @@ function linkClicked( ...@@ -307,7 +308,7 @@ function linkClicked(
dispatchNavigateAction( dispatchNavigateAction(
href, href,
replace ? 'replace' : 'push', replace ? 'replace' : 'push',
scroll ?? true, scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,
linkInstanceRef.current, linkInstanceRef.current,
transitionTypes transitionTypes
) )
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
type NavigateAction, type NavigateAction,
ACTION_HMR_REFRESH, ACTION_HMR_REFRESH,
PrefetchKind, PrefetchKind,
ScrollBehavior,
type AppHistoryState, type AppHistoryState,
} from './router-reducer/router-reducer-types' } from './router-reducer/router-reducer-types'
import { reducer } from './router-reducer/router-reducer' import { reducer } from './router-reducer/router-reducer'
...@@ -277,7 +278,7 @@ function getProfilingHookForOnNavigationStart() { ...@@ -277,7 +278,7 @@ function getProfilingHookForOnNavigationStart() {
export function dispatchNavigateAction( export function dispatchNavigateAction(
href: string, href: string,
navigateType: NavigateAction['navigateType'], navigateType: NavigateAction['navigateType'],
shouldScroll: boolean, scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null, linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined transitionTypes: string[] | undefined
): void { ): void {
...@@ -307,7 +308,7 @@ export function dispatchNavigateAction( ...@@ -307,7 +308,7 @@ export function dispatchNavigateAction(
url, url,
isExternalUrl: isExternalURL(url), isExternalUrl: isExternalURL(url),
locationSearch: location.search, locationSearch: location.search,
shouldScroll, scrollBehavior,
navigateType, navigateType,
}) })
} }
...@@ -356,7 +357,10 @@ function gesturePush(href: string, options?: NavigateOptions): void { ...@@ -356,7 +357,10 @@ function gesturePush(href: string, options?: NavigateOptions): void {
// Fork the router state for the duration of the gesture transition. // Fork the router state for the duration of the gesture transition.
const currentUrl = new URL(state.canonicalUrl, location.href) 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 // This is a special freshness policy that prevents dynamic requests from
// being spawned. During the gesture, we should only show the cached // being spawned. During the gesture, we should only show the cached
// prefetched UI, not dynamic data. // prefetched UI, not dynamic data.
...@@ -373,7 +377,7 @@ function gesturePush(href: string, options?: NavigateOptions): void { ...@@ -373,7 +377,7 @@ function gesturePush(href: string, options?: NavigateOptions): void {
state.tree, state.tree,
state.nextUrl, state.nextUrl,
freshnessPolicy, freshnessPolicy,
shouldScroll, scrollBehavior,
'push' 'push'
) )
dispatchGestureState(forkedGestureState) dispatchGestureState(forkedGestureState)
...@@ -442,7 +446,9 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -442,7 +446,9 @@ export const publicAppRouterInstance: AppRouterInstance = {
dispatchNavigateAction( dispatchNavigateAction(
href, href,
'replace', 'replace',
options?.scroll ?? true, options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null, null,
options?.transitionTypes options?.transitionTypes
) )
...@@ -458,7 +464,9 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -458,7 +464,9 @@ export const publicAppRouterInstance: AppRouterInstance = {
dispatchNavigateAction( dispatchNavigateAction(
href, href,
'push', 'push',
options?.scroll ?? true, options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null, null,
options?.transitionTypes options?.transitionTypes
) )
......
...@@ -233,10 +233,10 @@ export function createInitialRouterState({ ...@@ -233,10 +233,10 @@ export function createInitialRouterState({
preserveCustomHistoryState: true, preserveCustomHistoryState: true,
}, },
focusAndScrollRef: { focusAndScrollRef: {
apply: false, scrollRef: null,
forceScroll: false,
onlyHashChange: false, onlyHashChange: false,
hashFragment: null, hashFragment: null,
segmentPaths: [],
}, },
canonicalUrl, canonicalUrl,
renderedSearch: initialRenderedSearch, renderedSearch: initialRenderedSearch,
......
...@@ -24,7 +24,7 @@ export function navigateReducer( ...@@ -24,7 +24,7 @@ export function navigateReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: NavigateAction action: NavigateAction
): ReducerState { ): ReducerState {
const { url, isExternalUrl, navigateType, shouldScroll } = action const { url, isExternalUrl, navigateType, scrollBehavior } = action
if (isExternalUrl) { if (isExternalUrl) {
return completeHardNavigation(state, url, navigateType) return completeHardNavigation(state, url, navigateType)
...@@ -50,7 +50,7 @@ export function navigateReducer( ...@@ -50,7 +50,7 @@ export function navigateReducer(
state.tree, state.tree,
state.nextUrl, state.nextUrl,
FreshnessPolicy.Default, FreshnessPolicy.Default,
shouldScroll, scrollBehavior,
navigateType navigateType
) )
} }
...@@ -3,6 +3,7 @@ import type { ...@@ -3,6 +3,7 @@ import type {
ReducerState, ReducerState,
RefreshAction, RefreshAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types'
import { import {
convertServerPatchToFullTree, convertServerPatchToFullTree,
navigateToKnownRoute, navigateToKnownRoute,
...@@ -56,7 +57,7 @@ export function refreshDynamicData( ...@@ -56,7 +57,7 @@ export function refreshDynamicData(
const currentUrl = new URL(currentCanonicalUrl, location.origin) const currentUrl = new URL(currentCanonicalUrl, location.origin)
const currentRenderedSearch = state.renderedSearch const currentRenderedSearch = state.renderedSearch
const currentFlightRouterState = state.tree const currentFlightRouterState = state.tree
const shouldScroll = false const scrollBehavior = ScrollBehavior.NoScroll
// Create a NavigationSeed from the current FlightRouterState. // Create a NavigationSeed from the current FlightRouterState.
// TODO: Eventually we will store this type directly on the state object // TODO: Eventually we will store this type directly on the state object
...@@ -82,7 +83,7 @@ export function refreshDynamicData( ...@@ -82,7 +83,7 @@ export function refreshDynamicData(
currentFlightRouterState, currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
nextUrlForRefresh, nextUrlForRefresh,
shouldScroll, scrollBehavior,
navigateType, navigateType,
null, null,
// Refresh navigations don't use route prediction, so there's no route // Refresh navigations don't use route prediction, so there's no route
......
...@@ -45,8 +45,8 @@ export function restoreReducer( ...@@ -45,8 +45,8 @@ export function restoreReducer(
const now = Date.now() const now = Date.now()
const accumulation: NavigationRequestAccumulation = { const accumulation: NavigationRequestAccumulation = {
scrollableSegments: null,
separateRefreshUrls: null, separateRefreshUrls: null,
scrollRef: null,
} }
const restoreSeed = convertServerPatchToFullTree( const restoreSeed = convertServerPatchToFullTree(
treeToRestore, treeToRestore,
......
...@@ -29,6 +29,7 @@ import type { ...@@ -29,6 +29,7 @@ import type {
ReducerState, ReducerState,
ServerActionAction, ServerActionAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types'
import { assignLocation } from '../../../assign-location' import { assignLocation } from '../../../assign-location'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
...@@ -416,7 +417,7 @@ export function serverActionReducer( ...@@ -416,7 +417,7 @@ export function serverActionReducer(
const redirectUrl = const redirectUrl =
redirectLocation !== undefined ? redirectLocation : currentUrl redirectLocation !== undefined ? redirectLocation : currentUrl
const currentFlightRouterState = state.tree const currentFlightRouterState = state.tree
const shouldScroll = true const scrollBehavior = ScrollBehavior.Default
// If the action triggered a revalidation of the cache, we should also // If the action triggered a revalidation of the cache, we should also
// refresh all the dynamic data. // refresh all the dynamic data.
...@@ -472,7 +473,7 @@ export function serverActionReducer( ...@@ -472,7 +473,7 @@ export function serverActionReducer(
currentFlightRouterState, currentFlightRouterState,
freshnessPolicy, freshnessPolicy,
nextUrl, nextUrl,
shouldScroll, scrollBehavior,
navigateType, navigateType,
null, null,
// Server action redirects don't use route prediction - we already // Server action redirects don't use route prediction - we already
...@@ -494,7 +495,7 @@ export function serverActionReducer( ...@@ -494,7 +495,7 @@ export function serverActionReducer(
currentFlightRouterState, currentFlightRouterState,
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
shouldScroll, scrollBehavior,
navigateType navigateType
) )
}, },
......
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
type ServerPatchAction, type ServerPatchAction,
type ReducerState, type ReducerState,
type ReadonlyReducerState, type ReadonlyReducerState,
ScrollBehavior,
} from '../router-reducer-types' } from '../router-reducer-types'
import { import {
completeHardNavigation, completeHardNavigation,
...@@ -41,7 +42,7 @@ export function serverPatchReducer( ...@@ -41,7 +42,7 @@ export function serverPatchReducer(
// using the tree we just received from the server. // using the tree we just received from the server.
const retryCanonicalUrl = createHrefFromUrl(retryUrl) const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl const retryNextUrl = action.nextUrl
const shouldScroll = true const scrollBehavior = ScrollBehavior.Default
const now = Date.now() const now = Date.now()
return navigateToKnownRoute( return navigateToKnownRoute(
now, now,
...@@ -55,7 +56,7 @@ export function serverPatchReducer( ...@@ -55,7 +56,7 @@ export function serverPatchReducer(
state.tree, state.tree,
FreshnessPolicy.RefreshAll, FreshnessPolicy.RefreshAll,
retryNextUrl, retryNextUrl,
shouldScroll, scrollBehavior,
navigateType, navigateType,
null, null,
// Server patch (retry) navigations don't use route prediction. This is // Server patch (retry) navigations don't use route prediction. This is
......
import type { CacheNode } from '../../../shared/lib/app-router-types' import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { import type { FlightRouterState } from '../../../shared/lib/app-router-types'
FlightRouterState,
FlightSegmentPath,
} from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/navigation' import type { NavigationSeed } from '../segment-cache/navigation'
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
...@@ -94,7 +91,7 @@ export interface NavigateAction { ...@@ -94,7 +91,7 @@ export interface NavigateAction {
isExternalUrl: boolean isExternalUrl: boolean
locationSearch: Location['search'] locationSearch: Location['search']
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
shouldScroll: boolean scrollBehavior: ScrollBehavior
} }
/** /**
...@@ -163,19 +160,37 @@ export interface PushRef { ...@@ -163,19 +160,37 @@ export interface PushRef {
preserveCustomHistoryState: boolean 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 = { 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 * If only the URLs hash fragment changed
*/ */
......
...@@ -49,8 +49,25 @@ export type CacheNode = { ...@@ -49,8 +49,25 @@ export type CacheNode = {
head: HeadData head: HeadData
slots: Record<string, CacheNode> | null 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 = export type DynamicParamTypes =
| 'catchall' | 'catchall'
| 'catchall-intercepted-(..)(..)' | 'catchall-intercepted-(..)(..)'
......
...@@ -336,8 +336,8 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -336,8 +336,8 @@ describe(`Terminal Logging (${bundlerName})`, () => {
... ...
<RenderFromTemplateContext> <RenderFromTemplateContext>
<ScrollAndMaybeFocusHandler segmentPath={[...]}> <ScrollAndMaybeFocusHandler cacheNode={{rsc:{...}, ...}}>
<${innerScrollAndMaybeFocusHandlerName} segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}> <${innerScrollAndMaybeFocusHandlerName} focusAndScrollRef={{scrollRef:null, ...}} cacheNode={{rsc:{...}, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}> <ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary name="hydration-..." loading={null}> <LoadingBoundary name="hydration-..." loading={null}>
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <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', () => { ...@@ -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', () => { describe('bugs', () => {
it('Should scroll to the top of the layout when the first child is display none', async () => { it('Should scroll to the top of the layout when the first child is display none', async () => {
const browser = await next.browser('/') 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