fix: replace gatsby-remark-auto-headers

This commit is contained in:
Jean-Philippe Sirois
2020-05-22 00:57:06 -04:00
parent 92c3fe086f
commit 82ac9f0bae
6 changed files with 262 additions and 1 deletions
@@ -0,0 +1,43 @@
var attr = "id"
const getTargetOffset = (hash) => {
const id = window.decodeURI(hash.replace(`#`, ``))
if (id !== ``) {
const element = document.querySelector("[" + attr + "=" + id + "]")
if (element) {
return getElementTop(element)
}
}
return null
}
function getElementTop(el) {
let actualTop = el.offsetTop
let current = el.offsetParent
while (current !== null) {
actualTop += current.offsetTop
current = current.offsetParent
}
return actualTop
}
exports.onInitialClientRender = (_, pluginOptions) => {
if (pluginOptions.offsetY) {
attr = pluginOptions.attr
}
requestAnimationFrame(() => {
const offset = getTargetOffset(window.location.hash)
if (offset !== null) {
window.scrollTo(0, offset)
}
})
}
exports.shouldUpdateScroll = ({ routerProps: { location } }) => {
const offset = getTargetOffset(location.hash)
return offset !== null ? [0, offset] : true
}