Unverified Commit e6bca73d authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add support for scrolling to hash fragment (#46995)

Adds support for scrolling based on the [hash
fragment](https://en.wikipedia.org/wiki/URI_fragment) in client-side
navigations for the App Router, mirroring browser behavior.

- `#main-content` → scrolls to `id="main-content"` or
`name="main-content"` property
- `#top` → scrolls to the top of the page, this is a special case in
browsers.
- no hash → default scroll behavior, layout that changed

Fixes NEXT-658

<!-- 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:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

fixes #44295

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent c0cccf47
......@@ -237,6 +237,7 @@ export function hydrate() {
changeByServerResponse: () => {},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
}}
>
......
......@@ -114,31 +114,72 @@ function topOfElementInViewport(element: HTMLElement, viewportHeight: number) {
return rect.top >= 0 && rect.top <= viewportHeight
}
class ScrollAndFocusHandler extends React.Component<{
/**
* Find the DOM node for a hash fragment.
* If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.
* If the hash fragment is an id, the page has to scroll to the element with that id.
* If the hash fragment is a name, the page has to scroll to the first element with that name.
*/
function getHashFragmentDomNode(hashFragment: string) {
// If the hash fragment is `top` the page has to scroll to the top of the page.
if (hashFragment === 'top') {
return document.body
}
// If the hash fragment is an id, the page has to scroll to the element with that id.
return (
document.getElementById(hashFragment) ??
// If the hash fragment is a name, the page has to scroll to the first element with that name.
document.getElementsByName(hashFragment)[0]
)
}
interface ScrollAndFocusHandlerProps {
focusAndScrollRef: FocusAndScrollRef
children: React.ReactNode
}> {
componentDidMount() {
}
class ScrollAndFocusHandler extends React.Component<ScrollAndFocusHandlerProps> {
handlePotentialScroll = () => {
// Handle scroll and focus, it's only applied once in the first useEffect that triggers that changed.
const { focusAndScrollRef } = this.props
// `findDOMNode` is tricky because it returns just the first child if the component is a fragment.
// This already caused a bug where the first child was a <link/> in head.
const domNode = findDOMNode(this)
if (focusAndScrollRef.apply) {
let domNode:
| ReturnType<typeof getHashFragmentDomNode>
| ReturnType<typeof findDOMNode> = null
const hashFragment = focusAndScrollRef.hashFragment
if (hashFragment) {
domNode = getHashFragmentDomNode(hashFragment)
}
// `findDOMNode` is tricky because it returns just the first child if the component is a fragment.
// This already caused a bug where the first child was a <link/> in head.
if (!domNode) {
domNode = findDOMNode(this)
}
// If there is no DOMNode this layout-router level is skipped. It'll be handled higher-up in the tree.
if (!(domNode instanceof HTMLElement)) {
return
}
if (focusAndScrollRef.apply && domNode instanceof HTMLElement) {
// State is mutated to ensure that the focus and scroll is applied only once.
focusAndScrollRef.apply = false
handleSmoothScroll(
() => {
// In case of hash scroll we need to scroll to the top of the element
if (hashFragment) {
window.scrollTo(0, (domNode as HTMLElement).offsetTop)
return
}
// Store the current viewport height because reading `clientHeight` causes a reflow,
// and it won't change during this function.
const htmlElement = document.documentElement
const viewportHeight = htmlElement.clientHeight
// If the element's top edge is already in the viewport, exit early.
if (topOfElementInViewport(domNode, viewportHeight)) {
if (topOfElementInViewport(domNode as HTMLElement, viewportHeight)) {
return
}
......@@ -149,9 +190,9 @@ class ScrollAndFocusHandler extends React.Component<{
htmlElement.scrollTop = 0
// Scroll to domNode if domNode is not in viewport when scrolled to top of document
if (!topOfElementInViewport(domNode, viewportHeight)) {
if (!topOfElementInViewport(domNode as HTMLElement, viewportHeight)) {
// Scroll into view doesn't scroll horizontally by default when not needed
domNode.scrollIntoView()
;(domNode as HTMLElement).scrollIntoView()
}
},
{
......@@ -165,6 +206,17 @@ class ScrollAndFocusHandler extends React.Component<{
}
}
componentDidMount() {
this.handlePotentialScroll()
}
componentDidUpdate() {
// Because this property is overwritten in handlePotentialScroll it's fine to always run it when true as it'll be set to false for subsequent renders.
if (this.props.focusAndScrollRef.apply) {
this.handlePotentialScroll()
}
}
render() {
return this.props.children
}
......
......@@ -95,7 +95,7 @@ describe('createInitialRouterState', () => {
canonicalUrl: initialCanonicalUrl,
prefetchCache: new Map(),
pushRef: { pendingPush: false, mpaNavigation: false },
focusAndScrollRef: { apply: false },
focusAndScrollRef: { apply: false, hashFragment: null },
cache: expectedCache,
}
......
......@@ -43,7 +43,7 @@ export function createInitialRouterState({
cache,
prefetchCache: new Map(),
pushRef: { pendingPush: false, mpaNavigation: false },
focusAndScrollRef: { apply: false },
focusAndScrollRef: { apply: false, hashFragment: null },
canonicalUrl:
// location.href is read as the initial value for canonicalUrl in the browser
// This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.
......
......@@ -191,6 +191,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: true,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -373,6 +374,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: true,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -558,6 +560,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: 'https://example.vercel.sh/',
cache: {
......@@ -714,6 +717,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: 'https://example.vercel.sh/',
cache: {
......@@ -867,6 +871,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: true,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -1088,6 +1093,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: true,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -1314,6 +1320,7 @@ describe('navigateReducer', () => {
},
focusAndScrollRef: {
apply: true,
hashFragment: null,
},
canonicalUrl: '/parallel-tab-bar/demographics',
cache: {
......
......@@ -53,6 +53,13 @@ export function handleMutable(
typeof mutable.applyFocusAndScroll !== 'undefined'
? mutable.applyFocusAndScroll
: 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 !== ''
? // Remove leading # and decode hash to make non-latin hashes work.
decodeURIComponent(mutable.hashFragment.slice(1))
: null,
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
......@@ -121,7 +128,7 @@ export function navigateReducer(
mutable,
forceOptimisticNavigation,
} = action
const { pathname, search } = url
const { pathname, search, hash } = url
const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push'
......@@ -192,6 +199,7 @@ export function navigateReducer(
? createHrefFromUrl(canonicalUrlOverride)
: href
mutable.pendingPush = pendingPush
mutable.hashFragment = hash
return handleMutable(state, mutable)
}
......@@ -230,6 +238,7 @@ export function navigateReducer(
mutable.previousTree = state.tree
mutable.patchedTree = optimisticTree
mutable.pendingPush = pendingPush
mutable.hashFragment = hash
mutable.applyFocusAndScroll = true
mutable.cache = cache
mutable.canonicalUrl = href
......@@ -289,6 +298,7 @@ export function navigateReducer(
mutable.patchedTree = newTree
mutable.applyFocusAndScroll = true
mutable.pendingPush = pendingPush
mutable.hashFragment = hash
const applied = applyFlightData(state, cache, flightDataPath)
if (applied) {
......
......@@ -170,6 +170,7 @@ describe('prefetchReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking',
cache: {
......@@ -313,6 +314,7 @@ describe('prefetchReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking',
cache: {
......
......@@ -151,6 +151,7 @@ describe('refreshReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking',
cache: {
......@@ -307,6 +308,7 @@ describe('refreshReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking',
cache: {
......@@ -487,6 +489,7 @@ describe('refreshReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking',
cache: {
......
......@@ -123,6 +123,7 @@ describe('serverPatchReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -283,6 +284,7 @@ describe('serverPatchReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......
......@@ -186,6 +186,7 @@ describe('serverPatchReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -379,6 +380,7 @@ describe('serverPatchReducer', () => {
},
focusAndScrollRef: {
apply: false,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......@@ -551,6 +553,7 @@ describe('serverPatchReducer', () => {
},
focusAndScrollRef: {
apply: true,
hashFragment: null,
},
canonicalUrl: '/linking/about',
cache: {
......
......@@ -16,6 +16,7 @@ export interface Mutable {
applyFocusAndScroll?: boolean
pendingPush?: boolean
cache?: CacheNode
hashFragment?: string
}
/**
......@@ -132,6 +133,10 @@ export type FocusAndScrollRef = {
* If focus and scroll should be set in the layout-router's useEffect()
*/
apply: boolean
/**
* The hash fragment that should be scrolled to.
*/
hashFragment: string | null
}
/**
......
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-size: 14px;
line-height: 1;
}
import Link from 'next/link'
import './global.css'
export default function HashPage() {
// Create list of 5000 items that all have unique id
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i }))
return (
<div style={{ fontFamily: 'sans-serif', fontSize: '16px' }}>
<p>Hash Page</p>
<Link href="/hash#hash-6" id="link-to-6">
To 6
</Link>
<Link href="/hash#hash-50" id="link-to-50">
To 50
</Link>
<Link href="/hash#hash-160" id="link-to-160">
To 160
</Link>
<Link href="/hash#hash-300" id="link-to-300">
To 300
</Link>
<Link href="/hash#top" id="link-to-top">
To Top
</Link>
<Link href="/hash#non-existent" id="link-to-non-existent">
To non-existent
</Link>
<div>
{items.map((item) => (
<div key={item.id}>
<div id={`hash-${item.id}`}>{item.id}</div>
</div>
))}
</div>
</div>
)
}
......@@ -33,6 +33,37 @@ createNextDescribe(
})
})
describe('hash', () => {
it('should scroll to the specified hash', async () => {
const browser = await next.browser('/hash')
const checkLink = async (
val: number | string,
expectedScroll: number
) => {
await browser.elementByCss(`#link-to-${val.toString()}`).click()
await check(
async () => {
const val = await browser.eval('window.pageYOffset')
require('console').error({ val })
return val.toString()
},
expectedScroll.toString(),
true,
// Try maximum of 15 seconds
15
)
}
await checkLink(6, 114)
await checkLink(50, 730)
await checkLink(160, 2270)
await checkLink(300, 4230)
await checkLink('top', 0)
await checkLink('non-existent', 0)
})
})
describe('not-found', () => {
it('should trigger not-found in a server component', async () => {
const browser = await next.browser('/not-found/servercomponent')
......
......@@ -533,11 +533,16 @@ export async function startCleanStaticServer(dir) {
// check for content in 1 second intervals timing out after
// 30 seconds
export async function check(contentFn, regex, hardError = true) {
export async function check(
contentFn,
regex,
hardError = true,
maxRetries = 30
) {
let content
let lastErr
for (let tries = 0; tries < 30; tries++) {
for (let tries = 0; tries < maxRetries; tries++) {
try {
content = await contentFn()
if (typeof regex === 'string') {
......
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