Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add handling of smooth scroll in existing router
Browse files Browse the repository at this point in the history
timneutkens committed Sep 17, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 792dc1d commit 1405f6f
Showing 2 changed files with 15 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
@@ -688,7 +688,11 @@ function doRender(input: RenderRouteInfo): Promise<any> {
}

if (input.scroll) {
const htmlElement = document.documentElement
const existing = htmlElement.style.scrollBehavior
htmlElement.style.scrollBehavior = 'auto'
window.scrollTo(input.scroll.x, input.scroll.y)
htmlElement.style.scrollBehavior = existing
}
}

14 changes: 11 additions & 3 deletions packages/next/shared/lib/router/router.ts
Original file line number Diff line number Diff line change
@@ -655,6 +655,14 @@ interface FetchNextDataParams {
unstable_skipClientCache?: boolean
}

function handleSmoothScroll(fn: () => void) {
const htmlElement = document.documentElement
const existing = htmlElement.style.scrollBehavior
htmlElement.style.scrollBehavior = 'auto'
fn()
htmlElement.style.scrollBehavior = existing
}

function tryToParseAsJSON(text: string) {
try {
return JSON.parse(text)
@@ -2141,7 +2149,7 @@ export default class Router implements BaseRouter {
// Scroll to top if the hash is just `#` with no value or `#top`
// To mirror browsers
if (hash === '' || hash === 'top') {
window.scrollTo(0, 0)
handleSmoothScroll(() => window.scrollTo(0, 0))
return
}

@@ -2150,14 +2158,14 @@ export default class Router implements BaseRouter {
// First we check if the element by id is found
const idEl = document.getElementById(rawHash)
if (idEl) {
idEl.scrollIntoView()
handleSmoothScroll(() => idEl.scrollIntoView())
return
}
// If there's no element with the id, we check the `name` property
// To mirror browsers
const nameEl = document.getElementsByName(rawHash)[0]
if (nameEl) {
nameEl.scrollIntoView()
handleSmoothScroll(() => nameEl.scrollIntoView())
}
}

0 comments on commit 1405f6f

Please sign in to comment.