-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-browser.js
84 lines (74 loc) · 2.19 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* 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 = 500;
const historyExitingEventType = `history::exiting`;
const getUserConfirmation = (message, callback) => {
const event = new CustomEvent(historyExitingEventType, {
detail: { message },
});
window.dispatchEvent(event);
setTimeout(() => {
callback(true);
}, timeout);
};
const history = createHistory({ getUserConfirmation });
// block must return a string to conform
history.block((location, action) => location.key);
exports.replaceHistory = () => history;
class ReplaceComponentRenderer extends React.Component {
constructor(props) {
super(props);
this.state = { exiting: false };
this.listenerHandler = this.listenerHandler.bind(this);
}
listenerHandler(event) {
this.setState({ exiting: true });
}
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 });
}
}
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 }),
},
})}
</Transition>
);
}
}
// eslint-disable-next-line react/display-name
exports.replaceComponentRenderer = ({ props }) => {
if (props.layout) {
return undefined;
}
return createElement(ReplaceComponentRenderer, props);
};