-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-browser.js
More file actions
88 lines (78 loc) · 2.48 KB
/
Copy pathgatsby-browser.js
File metadata and controls
88 lines (78 loc) · 2.48 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* eslint-disable react/prop-types */
/* globals window CustomEvent */
import React, { createElement } from "react"
import { Transition } from "react-transition-group"
import createHistory from "history/createBrowserHistory"
import getTransitionStyle from "./src/utils/getTransitionStyle"
const timeout = 250
const historyExitingEventType = `history::exiting`
const getUserConfirmation = (pathname, callback) => {
const event = new CustomEvent(historyExitingEventType, { detail: { pathname } })
window.dispatchEvent(event)
setTimeout(() => {
callback(true)
}, timeout)
}
const history = createHistory({ getUserConfirmation })
// block must return a string to conform
history.block((location, action) => location.pathname)
exports.replaceHistory = () => history
class ReplaceComponentRenderer extends React.Component {
constructor(props) {
super(props)
this.state = { exiting: false, nextPageResources: {} }
this.listenerHandler = this.listenerHandler.bind(this)
}
listenerHandler(event) {
const nextPageResources = this.props.loader.getResourcesForPathname(
event.detail.pathname,
nextPageResources => this.setState({ nextPageResources })
) || {}
this.setState({ exiting: true, nextPageResources })
}
componentDidMount() {
window.addEventListener(historyExitingEventType, this.listenerHandler)
}
componentWillUnmount() {
window.removeEventListener(historyExitingEventType, this.listenerHandler)
}
componentWillReceiveProps(nextProps) {
if (this.props.location.key !== nextProps.location.key) {
this.setState({ exiting: false, nextPageResources: {} })
}
}
render() {
const transitionProps = {
timeout: {
enter: 0,
exit: timeout,
},
appear: true,
in: !this.state.exiting,
key: this.props.location.key,
}
return (
<Transition {...transitionProps}>
{
(status) => createElement(this.props.pageResources.component, {
...this.props,
...this.props.pageResources.json,
transition: {
status,
timeout,
style: getTransitionStyle({ status, timeout }),
nextPageResources: this.state.nextPageResources,
},
})
}
</Transition>
)
}
}
// eslint-disable-next-line react/display-name
exports.replaceComponentRenderer = ({ props, loader }) => {
if (props.layout) {
return undefined
}
return createElement(ReplaceComponentRenderer, { ...props, loader })
}