Skip to content

Commit

Permalink
Add handling of smooth scroll in existing router
Browse files Browse the repository at this point in the history
  • Loading branch information
timneutkens committed Sep 17, 2022
1 parent 792dc1d commit 1405f6f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/next/client/index.tsx
Expand Up @@ -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
}
}

Expand Down
14 changes: 11 additions & 3 deletions packages/next/shared/lib/router/router.ts
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}

Expand All @@ -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())
}
}

Expand Down

0 comments on commit 1405f6f

Please sign in to comment.