1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Scroll to name when hash is provided (#5019)

Fixes #5008 

Apparently, browser behavior is to scroll to `name="something"` too.
This commit is contained in:
Tim Neutkens 2018-08-23 20:20:45 +02:00 committed by GitHub
parent 918e0a6e32
commit bd5ee26841
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 3 deletions

View file

@ -325,9 +325,17 @@ export default class Router {
return
}
const el = document.getElementById(hash)
if (el) {
el.scrollIntoView()
// First we check if the element by id is found
const idEl = document.getElementById(hash)
if (idEl) {
idEl.scrollIntoView()
return
}
// If there's no element with the id, we check the `name` property
// To mirror browsers
const nameEl = document.getElementsByName(hash)[0]
if (nameEl) {
nameEl.scrollIntoView()
}
}

View file

@ -27,10 +27,16 @@ export default class SelfReload extends Component {
<Link href='#item-400'>
<a id='scroll-to-item-400'>Go to item 400</a>
</Link>
<Link href='#name-item-400'>
<a id='scroll-to-name-item-400'>Go to name 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>
})}
{Array.from({length: 500}, (x, i) => i + 1).map(i => {
return <div key={`item-${i}`} name={`name-item-${i}`}>{i}</div>
})}
</div>
)
}

View file

@ -293,6 +293,33 @@ export default (context, render) => {
}
})
it('should scroll to the specified position on the same page with a name property', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/nav/hash-changes')
// Scrolls to item 400 with name="name-item-400" on the page
const scrollPosition = await browser
.elementByCss('#scroll-to-name-item-400').click()
.eval('window.pageYOffset')
console.log(scrollPosition)
expect(scrollPosition).toBe(16258)
// 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()
}
}
})
it('should scroll to the specified position to a new page', async () => {
let browser
try {