Unverified Commit 5d06b79e authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Support scroll: false for Link component for app router (#51869)

### What

Support `scroll={false}` for Link component in app router. This can be
used when you don't need to scroll back to top again when route url
changes. For instance hash query changes, if you want to keep the
scrolling as it is, you can use this option.

### How

Handling the `scroll` option in navigation reducer on client side.  

Fixes #50105
Fixes NEXT-1377

---------
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent b8ae8d21
...@@ -231,11 +231,7 @@ function Router({ ...@@ -231,11 +231,7 @@ function Router({
) )
const navigate: RouterNavigate = useCallback( const navigate: RouterNavigate = useCallback(
( (href, navigateType, forceOptimisticNavigation, shouldScroll) => {
href: string,
navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean
) => {
const url = new URL(addBasePath(href), location.href) const url = new URL(addBasePath(href), location.href)
return dispatch({ return dispatch({
...@@ -244,6 +240,7 @@ function Router({ ...@@ -244,6 +240,7 @@ function Router({
isExternalUrl: isExternalURL(url), isExternalUrl: isExternalURL(url),
locationSearch: location.search, locationSearch: location.search,
forceOptimisticNavigation, forceOptimisticNavigation,
shouldScroll: shouldScroll ?? true,
navigateType, navigateType,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: {}, mutable: {},
...@@ -296,12 +293,22 @@ function Router({ ...@@ -296,12 +293,22 @@ function Router({
}, },
replace: (href, options = {}) => { replace: (href, options = {}) => {
startTransition(() => { startTransition(() => {
navigate(href, 'replace', Boolean(options.forceOptimisticNavigation)) navigate(
href,
'replace',
Boolean(options.forceOptimisticNavigation),
options.scroll ?? true
)
}) })
}, },
push: (href, options = {}) => { push: (href, options = {}) => {
startTransition(() => { startTransition(() => {
navigate(href, 'push', Boolean(options.forceOptimisticNavigation)) navigate(
href,
'push',
Boolean(options.forceOptimisticNavigation),
options.scroll ?? true
)
}) })
}, },
refresh: () => { refresh: () => {
......
...@@ -9,6 +9,9 @@ export function handleMutable( ...@@ -9,6 +9,9 @@ export function handleMutable(
state: ReadonlyReducerState, state: ReadonlyReducerState,
mutable: Mutable mutable: Mutable
): ReducerState { ): ReducerState {
// shouldScroll is true by default, can override to false.
const shouldScroll = mutable.shouldScroll ?? true
return { return {
buildId: state.buildId, buildId: state.buildId,
// Set href. // Set href.
...@@ -30,19 +33,25 @@ export function handleMutable( ...@@ -30,19 +33,25 @@ export function handleMutable(
}, },
// All navigation requires scroll and focus management to trigger. // All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { focusAndScrollRef: {
apply: apply: shouldScroll
mutable?.scrollableSegments !== undefined ? mutable?.scrollableSegments !== undefined
? true ? true
: state.focusAndScrollRef.apply, : state.focusAndScrollRef.apply
hashFragment: : // If shouldScroll is false then we should not apply scroll and focus management.
// Empty hash should trigger default behavior of scrolling layout into view. false,
// #top is handled in layout-router. hashFragment: shouldScroll
mutable.hashFragment && mutable.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. ? // Remove leading # and decode hash to make non-latin hashes work.
decodeURIComponent(mutable.hashFragment.slice(1)) decodeURIComponent(mutable.hashFragment.slice(1))
: state.focusAndScrollRef.hashFragment, : state.focusAndScrollRef.hashFragment
segmentPaths: : // If shouldScroll is false then we should not apply scroll and focus management.
mutable?.scrollableSegments ?? state.focusAndScrollRef.segmentPaths, null,
segmentPaths: shouldScroll
? mutable?.scrollableSegments ?? state.focusAndScrollRef.segmentPaths
: // If shouldScroll is false then we should not apply scroll and focus management.
[],
}, },
// Apply cache. // Apply cache.
cache: mutable.cache ? mutable.cache : state.cache, cache: mutable.cache ? mutable.cache : state.cache,
......
...@@ -3,6 +3,7 @@ import type { fetchServerResponse as fetchServerResponseType } from '../fetch-se ...@@ -3,6 +3,7 @@ import type { fetchServerResponse as fetchServerResponseType } from '../fetch-se
import type { FlightData } from '../../../../server/app-render/types' import type { FlightData } from '../../../../server/app-render/types'
const buildId = 'development' const buildId = 'development'
const flightData: FlightData = [ const flightData: FlightData = [
[ [
'children', 'children',
...@@ -58,6 +59,9 @@ jest.mock('../fetch-server-response', () => { ...@@ -58,6 +59,9 @@ jest.mock('../fetch-server-response', () => {
fetchServerResponse: ( fetchServerResponse: (
url: URL url: URL
): ReturnType<typeof fetchServerResponseType> => { ): ReturnType<typeof fetchServerResponseType> => {
if (url.pathname === '/linking' && url.hash === '#hash') {
return Promise.resolve(['', undefined])
}
if (url.pathname === '/linking/about') { if (url.pathname === '/linking/about') {
return Promise.resolve([flightData, undefined]) return Promise.resolve([flightData, undefined])
} }
...@@ -174,6 +178,7 @@ describe('navigateReducer', () => { ...@@ -174,6 +178,7 @@ describe('navigateReducer', () => {
isExternalUrl: false, isExternalUrl: false,
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
...@@ -362,6 +367,7 @@ describe('navigateReducer', () => { ...@@ -362,6 +367,7 @@ describe('navigateReducer', () => {
isExternalUrl: false, isExternalUrl: false,
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
...@@ -555,6 +561,7 @@ describe('navigateReducer', () => { ...@@ -555,6 +561,7 @@ describe('navigateReducer', () => {
isExternalUrl, isExternalUrl,
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
...@@ -717,6 +724,7 @@ describe('navigateReducer', () => { ...@@ -717,6 +724,7 @@ describe('navigateReducer', () => {
isExternalUrl, isExternalUrl,
locationSearch: '', locationSearch: '',
navigateType: 'replace', navigateType: 'replace',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
...@@ -876,6 +884,7 @@ describe('navigateReducer', () => { ...@@ -876,6 +884,7 @@ describe('navigateReducer', () => {
isExternalUrl: false, isExternalUrl: false,
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: true, forceOptimisticNavigation: true,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
...@@ -977,6 +986,169 @@ describe('navigateReducer', () => { ...@@ -977,6 +986,169 @@ describe('navigateReducer', () => {
expect(newState).toMatchObject(expectedState) expect(newState).toMatchObject(expectedState)
}) })
it('should apply navigation for scroll', 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([
[
'__PAGE__',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
])
const state = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
const state2 = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking#hash', 'https://localhost') as any,
})
const action: NavigateAction = {
type: ACTION_NAVIGATE,
url: new URL('/linking#hash', 'https://localhost'),
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: false, // should not scroll
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
const newState = await runPromiseThrowChain(() =>
navigateReducer(state2, action)
)
const expectedState: ReturnType<typeof navigateReducer> = {
buildId,
prefetchCache: new Map(),
pushRef: {
mpaNavigation: true,
pendingPush: true,
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
segmentPaths: [],
},
canonicalUrl: '',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
subTreeData: (
<html>
<head></head>
<body>Root layout</body>
</html>
),
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'__PAGE__',
{
status: CacheStates.READY,
// Real promise is not needed here.
data: null,
parallelRoutes: new Map(),
subTreeData: <>Linking page</>,
},
],
]),
],
]),
// Real promise is not needed here.
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
]),
},
tree: [
'',
{
children: [
'linking',
{
children: ['__PAGE__', {}],
},
],
},
// TODO-APP: optimistic tree is wrong
undefined,
undefined,
true,
],
}
expect(newState).toMatchObject(expectedState)
})
it('should apply navigation with prefetched data', async () => { it('should apply navigation with prefetched data', async () => {
const initialTree = getInitialRouterStateTree() const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking' const initialCanonicalUrl = '/linking'
...@@ -1060,6 +1232,7 @@ describe('navigateReducer', () => { ...@@ -1060,6 +1232,7 @@ describe('navigateReducer', () => {
isExternalUrl: false, isExternalUrl: false,
navigateType: 'push', navigateType: 'push',
locationSearch: '', locationSearch: '',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
...@@ -1342,6 +1515,7 @@ describe('navigateReducer', () => { ...@@ -1342,6 +1515,7 @@ describe('navigateReducer', () => {
isExternalUrl: false, isExternalUrl: false,
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
......
...@@ -114,6 +114,7 @@ export function navigateReducer( ...@@ -114,6 +114,7 @@ export function navigateReducer(
cache, cache,
mutable, mutable,
forceOptimisticNavigation, forceOptimisticNavigation,
shouldScroll,
} = action } = action
const { pathname, hash } = url const { pathname, hash } = url
const href = createHrefFromUrl(url) const href = createHrefFromUrl(url)
...@@ -191,6 +192,7 @@ export function navigateReducer( ...@@ -191,6 +192,7 @@ export function navigateReducer(
mutable.patchedTree = optimisticTree mutable.patchedTree = optimisticTree
mutable.pendingPush = pendingPush mutable.pendingPush = pendingPush
mutable.hashFragment = hash mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll
mutable.scrollableSegments = [] mutable.scrollableSegments = []
mutable.cache = temporaryCacheNode mutable.cache = temporaryCacheNode
mutable.canonicalUrl = href mutable.canonicalUrl = href
...@@ -355,12 +357,13 @@ export function navigateReducer( ...@@ -355,12 +357,13 @@ export function navigateReducer(
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = currentTree mutable.patchedTree = currentTree
mutable.scrollableSegments = scrollableSegments
mutable.canonicalUrl = canonicalUrlOverride mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride) ? createHrefFromUrl(canonicalUrlOverride)
: href : href
mutable.pendingPush = pendingPush mutable.pendingPush = pendingPush
mutable.scrollableSegments = scrollableSegments
mutable.hashFragment = hash mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll
return handleMutable(state, mutable) return handleMutable(state, mutable)
} }
...@@ -502,6 +502,7 @@ describe('serverPatchReducer', () => { ...@@ -502,6 +502,7 @@ describe('serverPatchReducer', () => {
isExternalUrl: false, isExternalUrl: false,
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false, forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
......
...@@ -23,7 +23,8 @@ export type RouterChangeByServerResponse = ( ...@@ -23,7 +23,8 @@ export type RouterChangeByServerResponse = (
export type RouterNavigate = ( export type RouterNavigate = (
href: string, href: string,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean,
shouldScroll: boolean
) => void ) => void
export interface Mutable { export interface Mutable {
...@@ -36,6 +37,7 @@ export interface Mutable { ...@@ -36,6 +37,7 @@ export interface Mutable {
cache?: CacheNode cache?: CacheNode
prefetchCache?: AppRouterState['prefetchCache'] prefetchCache?: AppRouterState['prefetchCache']
hashFragment?: string hashFragment?: string
shouldScroll?: boolean
} }
export interface ServerActionMutable { export interface ServerActionMutable {
...@@ -125,6 +127,7 @@ export interface NavigateAction { ...@@ -125,6 +127,7 @@ export interface NavigateAction {
locationSearch: Location['search'] locationSearch: Location['search']
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean
shouldScroll: boolean
cache: CacheNode cache: CacheNode
mutable: Mutable mutable: Mutable
} }
......
...@@ -217,15 +217,17 @@ function linkClicked( ...@@ -217,15 +217,17 @@ function linkClicked(
const navigate = () => { const navigate = () => {
// If the router is an NextRouter instance it will have `beforePopState` // If the router is an NextRouter instance it will have `beforePopState`
const routerScroll = scroll ?? true
if ('beforePopState' in router) { if ('beforePopState' in router) {
router[replace ? 'replace' : 'push'](href, as, { router[replace ? 'replace' : 'push'](href, as, {
shallow, shallow,
locale, locale,
scroll, scroll: routerScroll,
}) })
} else { } else {
router[replace ? 'replace' : 'push'](as || href, { router[replace ? 'replace' : 'push'](as || href, {
forceOptimisticNavigation: !prefetchEnabled, forceOptimisticNavigation: !prefetchEnabled,
scroll: routerScroll,
}) })
} }
} }
......
...@@ -70,6 +70,7 @@ export type CacheNode = ...@@ -70,6 +70,7 @@ export type CacheNode =
export interface NavigateOptions { export interface NavigateOptions {
/** @internal */ /** @internal */
forceOptimisticNavigation?: boolean forceOptimisticNavigation?: boolean
scroll?: boolean
} }
export interface PrefetchOptions { export interface PrefetchOptions {
......
module.exports = { module.exports = {}
strictMode: true,
}
'use client'
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
const HashChanges = () => {
const router = useRouter()
return (
<div id="hash-changes-page">
<div>
<Link href="#via-link" id="via-link">
Via Link
</Link>
</div>
<div>
<a href="#via-a" id="via-a">
Via A
</a>
</div>
<div>
<Link href="#" id="via-empty-hash">
Via Empty Hash
</Link>
</div>
<div>
<Link href="#item-400" id="scroll-to-item-400">
Go to item 400
</Link>
</div>
<div>
<Link href="#name-item-400" id="scroll-to-name-item-400">
Go to name item 400
</Link>
</div>
<div>
<Link
href="#name-item-400"
scroll={false}
id="scroll-to-name-item-400-no-scroll"
>
Go to name item 400 (no scroll)
</Link>
</div>
<div>
<Link href="#中文" id="scroll-to-cjk-anchor">
Go to CJK anchor
</Link>
</div>
<div>
<Link href="#top" id="via-top-hash">
Via Top Hash
</Link>
</div>
<div id="asPath">ASPATH: {router.asPath}</div>
<div id="pathname">PATHNAME: {router.pathname}</div>
<div id="中文">CJK anchor</div>
{Array.from({ length: 500 }, (x, i) => i + 1).map((i) => {
return (
<div key={`item-${i}`} name={`name-item-${i}`}>
{i}
</div>
)
})}
</div>
)
}
export default HashChanges
...@@ -85,6 +85,17 @@ createNextDescribe( ...@@ -85,6 +85,17 @@ createNextDescribe(
await checkLink('top', 0) await checkLink('top', 0)
await checkLink('non-existent', 0) await checkLink('non-existent', 0)
}) })
it('should not scroll to hash when scroll={false} is set', async () => {
const browser = await next.browser('/hash-changes')
const curScroll = await browser.eval(
'document.documentElement.scrollTop'
)
await browser.elementByCss('#scroll-to-name-item-400-no-scroll').click()
expect(curScroll).toBe(
await browser.eval('document.documentElement.scrollTop')
)
})
}) })
describe('hash-with-scroll-offset', () => { describe('hash-with-scroll-offset', () => {
......
module.exports = { module.exports = {}
strictMode: true,
}
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