-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgatsby-browser.js
70 lines (60 loc) · 1.57 KB
/
gatsby-browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React from "react"
import smoothscroll from "smoothscroll-polyfill"
import { setTimeout } from "requestanimationframe-timer"
import GlobalStyle from "./src/styles/globalStyle"
const loadPolyfills = async () => {
smoothscroll.polyfill()
if (typeof window.IntersectionObserver === "undefined") {
await import("intersection-observer")
}
}
loadPolyfills()
const wrapRootElement = ({ element, props }) => {
return (
<>
<GlobalStyle />
{element}
</>
)
}
const wrapPageElement = require("./src/wrapper")
const getTargetOffset = hash => {
const id = window.decodeURI(hash.replace(`#`, ``))
if (id !== ``) {
const element = document.getElementById(id)
if (element) {
return element.offsetTop
}
}
return null
}
const onInitialClientRender = () => {
requestAnimationFrame(() => {
// Wait for body render
setTimeout(() => {
const offset = getTargetOffset(window.location.hash)
if (offset !== null) {
window.scrollTo(0, offset)
}
}, 100)
})
}
const shouldUpdateScroll = ({ prevRouterProps, routerProps: { location } }) => {
if (prevRouterProps.location.pathname === location.pathname) {
if (location.hash) {
const smoothOffset = getTargetOffset(location.hash)
if (smoothOffset) {
window.scrollTo({ top: smoothOffset, left: 0, behavior: "smooth" })
}
}
return false
}
const offset = getTargetOffset(location.hash)
return offset !== null ? [0, offset] : true
}
export {
wrapPageElement,
wrapRootElement,
onInitialClientRender,
shouldUpdateScroll,
}