Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 10 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions packages/next/src/client/components/app-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,7 @@ function Router({
)

const navigate: RouterNavigate = useCallback(
(
href: string,
navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean
) => {
(href, navigateType, forceOptimisticNavigation, shouldScroll) => {
huozhi marked this conversation as resolved.
Show resolved Hide resolved
const url = new URL(addBasePath(href), location.href)

return dispatch({
Expand All @@ -244,6 +240,7 @@ function Router({
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
forceOptimisticNavigation,
shouldScroll: shouldScroll ?? true,
navigateType,
cache: createEmptyCacheNode(),
mutable: {},
Expand Down Expand Up @@ -296,12 +293,22 @@ function Router({
},
replace: (href, options = {}) => {
startTransition(() => {
navigate(href, 'replace', Boolean(options.forceOptimisticNavigation))
navigate(
href,
'replace',
Boolean(options.forceOptimisticNavigation),
options.scroll ?? true
)
})
},
push: (href, options = {}) => {
startTransition(() => {
navigate(href, 'push', Boolean(options.forceOptimisticNavigation))
navigate(
href,
'push',
Boolean(options.forceOptimisticNavigation),
options.scroll ?? true
)
})
},
refresh: () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export function handleMutable(
state: ReadonlyReducerState,
mutable: Mutable
): ReducerState {
// shouldScroll is true by default, can override to false.
const shouldScroll = mutable.shouldScroll ?? true

return {
buildId: state.buildId,
// Set href.
Expand All @@ -30,19 +33,25 @@ export function handleMutable(
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: {
apply:
mutable?.scrollableSegments !== undefined
apply: shouldScroll
? mutable?.scrollableSegments !== undefined
? true
: state.focusAndScrollRef.apply,
hashFragment:
// Empty hash should trigger default behavior of scrolling layout into view.
// #top is handled in layout-router.
mutable.hashFragment && mutable.hashFragment !== ''
: state.focusAndScrollRef.apply
: // If shouldScroll is false then we should not apply scroll and focus management.
false,
hashFragment: shouldScroll
? // 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.
decodeURIComponent(mutable.hashFragment.slice(1))
: state.focusAndScrollRef.hashFragment,
segmentPaths:
mutable?.scrollableSegments ?? state.focusAndScrollRef.segmentPaths,
: state.focusAndScrollRef.hashFragment
: // If shouldScroll is false then we should not apply scroll and focus management.
null,
segmentPaths: shouldScroll
? mutable?.scrollableSegments ?? state.focusAndScrollRef.segmentPaths
: // If shouldScroll is false then we should not apply scroll and focus management.
[],
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { fetchServerResponse as fetchServerResponseType } from '../fetch-se
import type { FlightData } from '../../../../server/app-render/types'

const buildId = 'development'

const flightData: FlightData = [
[
'children',
Expand Down Expand Up @@ -58,6 +59,9 @@ jest.mock('../fetch-server-response', () => {
fetchServerResponse: (
url: URL
): ReturnType<typeof fetchServerResponseType> => {
if (url.pathname === '/linking' && url.hash === '#hash') {
return Promise.resolve(['', undefined])
}
if (url.pathname === '/linking/about') {
return Promise.resolve([flightData, undefined])
}
Expand Down Expand Up @@ -174,6 +178,7 @@ describe('navigateReducer', () => {
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down Expand Up @@ -362,6 +367,7 @@ describe('navigateReducer', () => {
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down Expand Up @@ -555,6 +561,7 @@ describe('navigateReducer', () => {
isExternalUrl,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down Expand Up @@ -717,6 +724,7 @@ describe('navigateReducer', () => {
isExternalUrl,
locationSearch: '',
navigateType: 'replace',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down Expand Up @@ -876,6 +884,7 @@ describe('navigateReducer', () => {
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: true,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down Expand Up @@ -977,6 +986,169 @@ describe('navigateReducer', () => {
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 () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
Expand Down Expand Up @@ -1060,6 +1232,7 @@ describe('navigateReducer', () => {
isExternalUrl: false,
navigateType: 'push',
locationSearch: '',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down Expand Up @@ -1342,6 +1515,7 @@ describe('navigateReducer', () => {
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export function navigateReducer(
cache,
mutable,
forceOptimisticNavigation,
shouldScroll,
} = action
const { pathname, hash } = url
const href = createHrefFromUrl(url)
Expand Down Expand Up @@ -191,6 +192,7 @@ export function navigateReducer(
mutable.patchedTree = optimisticTree
mutable.pendingPush = pendingPush
mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll
mutable.scrollableSegments = []
mutable.cache = temporaryCacheNode
mutable.canonicalUrl = href
Expand Down Expand Up @@ -355,12 +357,13 @@ export function navigateReducer(

mutable.previousTree = state.tree
mutable.patchedTree = currentTree
mutable.scrollableSegments = scrollableSegments
mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: href
mutable.pendingPush = pendingPush
mutable.scrollableSegments = scrollableSegments
mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll

return handleMutable(state, mutable)
}
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ describe('serverPatchReducer', () => {
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
Expand Down
Loading