mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
Make sure hashchanges get triggered (#4676)
When clicking a next/link with a hash (#something) multiple times, it wouldn't keep the scrolling behavior browsers have. This makes sure we correctly trigger it.
This commit is contained in:
parent
1c817d2bbf
commit
57d8af857a
|
@ -292,6 +292,11 @@ export default class Router {
|
|||
const [ oldUrlNoHash, oldHash ] = this.asPath.split('#')
|
||||
const [ newUrlNoHash, newHash ] = as.split('#')
|
||||
|
||||
// Makes sure we scroll to the provided hash if the url/hash are the same
|
||||
if (newHash && (oldUrlNoHash === newUrlNoHash) && (oldHash === newHash)) {
|
||||
return true
|
||||
}
|
||||
|
||||
// If the urls are change, there's more than a hash change
|
||||
if (oldUrlNoHash !== newUrlNoHash) {
|
||||
return false
|
||||
|
@ -306,6 +311,12 @@ export default class Router {
|
|||
|
||||
scrollToHash (as) {
|
||||
const [ , hash ] = as.split('#')
|
||||
// Scroll to top if the hash is just `#` with no value
|
||||
if (hash === '') {
|
||||
window.scrollTo(0, 0)
|
||||
return
|
||||
}
|
||||
|
||||
const el = document.getElementById(hash)
|
||||
if (el) {
|
||||
el.scrollIntoView()
|
||||
|
|
|
@ -24,7 +24,13 @@ export default class SelfReload extends Component {
|
|||
<Link href='#'>
|
||||
<a id='via-empty-hash'>Via Empty Hash</a>
|
||||
</Link>
|
||||
<Link href='#item-400'>
|
||||
<a id='scroll-to-item-400'>Go to item 400</a>
|
||||
</Link>
|
||||
<p>COUNT: {this.props.count}</p>
|
||||
{Array.from({length: 500}, (x, i) => i + 1).map(i => {
|
||||
return <div key={`item-${i}`} id={`item-${i}`}>{i}</div>
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
@ -230,6 +230,31 @@ export default (context, render) => {
|
|||
|
||||
browser.close()
|
||||
})
|
||||
|
||||
it('should scroll to the specified position', async () => {
|
||||
let browser
|
||||
try {
|
||||
browser = await webdriver(context.appPort, '/nav/hash-changes')
|
||||
|
||||
// Scrolls to item 400 on the page
|
||||
const scrollPosition = await browser
|
||||
.elementByCss('#scroll-to-item-400').click()
|
||||
.eval('window.pageYOffset')
|
||||
|
||||
expect(scrollPosition).toBe(7258)
|
||||
|
||||
// Scrolls back to top when scrolling to `#` with no value.
|
||||
const scrollPositionAfterEmptyHash = await browser
|
||||
.elementByCss('#via-empty-hash').click()
|
||||
.eval('window.pageYOffset')
|
||||
|
||||
expect(scrollPositionAfterEmptyHash).toBe(0)
|
||||
} finally {
|
||||
if (browser) {
|
||||
browser.close()
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('when hash change via A tag', () => {
|
||||
|
|
Loading…
Reference in a new issue