Skip to content

Commit

Permalink
fix(gatsby-remark-autolink-headers): use shouldUpdateScroll api and n…
Browse files Browse the repository at this point in the history
…ot onRouteUpdate (#9657)

* use shouldUpdateScroll api to not battle with builtin scrollbehaviour on scroll handling

* use passed hash, doh
  • Loading branch information
pieh committed Nov 2, 2018
1 parent 8877165 commit 390803c
Showing 1 changed file with 19 additions and 24 deletions.
43 changes: 19 additions & 24 deletions packages/gatsby-remark-autolink-headers/src/gatsby-browser.js
@@ -1,35 +1,30 @@
import { globalHistory as history } from "@reach/router/lib/history"

let currentPathName
let offsetY = 0

const scrollToHash = () => {
// Make sure React has had a chance to flush to DOM first and apply styles.
setTimeout(() => {
const hash = window.decodeURI(window.location.hash.replace(`#`, ``))
if (hash !== ``) {
const element = document.getElementById(hash)
if (element) {
const offset = element.offsetTop
window.scrollTo(0, offset - offsetY)
}
const getTargetOffset = hash => {
const id = window.decodeURI(hash.replace(`#`, ``))
if (id !== ``) {
const element = document.getElementById(id)
if (element) {
return element.offsetTop - offsetY
}
}, 10)
}

history.listen(() => {
if (location.pathname === currentPathName) {
scrollToHash()
}
})
return null
}

exports.onClientEntry = (args, pluginOptions) => {
exports.onInitialClientRender = (_, pluginOptions) => {
if (pluginOptions.offsetY) {
offsetY = pluginOptions.offsetY
}

requestAnimationFrame(() => {
const offset = getTargetOffset(window.location.hash)
if (offset !== null) {
window.scrollTo(0, offset)
}
})
}

exports.onRouteUpdate = ({ location }, pluginOptions) => {
scrollToHash()
currentPathName = location.pathname
exports.shouldUpdateScroll = ({ routerProps: { location } }) => {
const offset = getTargetOffset(location.hash)
return offset !== null ? [0, offset] : true
}

0 comments on commit 390803c

Please sign in to comment.