-
Notifications
You must be signed in to change notification settings - Fork 7
/
ScrollManager.js
92 lines (74 loc) · 2.4 KB
/
ScrollManager.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
85
86
87
88
89
90
91
92
import StateStorage from 'farce/lib/StateStorage';
import HttpError from 'found/lib/HttpError';
import { routerShape } from 'found/lib/PropTypes';
import PropTypes from 'prop-types';
import React from 'react';
import ScrollBehavior from 'scroll-behavior';
const STORAGE_NAMESPACE = '@@scroll';
const propTypes = {
shouldUpdateScroll: PropTypes.func,
createScrollBehavior: PropTypes.func.isRequired,
renderArgs: PropTypes.shape({
location: PropTypes.object.isRequired,
router: routerShape.isRequired,
elements: PropTypes.array,
error: PropTypes.instanceOf(HttpError),
}).isRequired,
children: PropTypes.node,
};
const defaultProps = {
createScrollBehavior: config => new ScrollBehavior(config),
};
class ScrollManager extends React.Component {
constructor(props, context) {
super(props, context);
const { createScrollBehavior, renderArgs } = props;
const { router } = renderArgs;
this.scrollBehavior = createScrollBehavior({
addTransitionHook: router.addTransitionHook,
stateStorage: new StateStorage(router, STORAGE_NAMESPACE),
getCurrentLocation: () => this.props.renderArgs.location,
shouldUpdateScroll: this.shouldUpdateScroll,
});
this.prevRenderArgs = null;
}
componentDidMount() {
this.maybeUpdateScroll();
}
componentDidUpdate() {
this.maybeUpdateScroll();
}
componentWillUnmount() {
this.scrollBehavior.stop();
}
maybeUpdateScroll() {
const { renderArgs } = this.props;
const prevLocation = this.prevRenderArgs && this.prevRenderArgs.location;
if (
renderArgs.location === prevLocation ||
!(renderArgs.elements || renderArgs.error)
) {
// If the location hasn't actually changed, or if we're in a global
// pending state, don't update the scroll position.
return;
}
this.scrollBehavior.updateScroll(this.prevRenderArgs, renderArgs);
this.prevRenderArgs = renderArgs;
}
shouldUpdateScroll = (prevRenderArgs, renderArgs) => {
const { shouldUpdateScroll } = this.props;
if (!shouldUpdateScroll) {
return true;
}
// Hack to allow access to ScrollBehavior internals (e.g. stateStorage).
return shouldUpdateScroll.call(
this.scrollBehavior, prevRenderArgs, renderArgs,
);
};
render() {
return this.props.children;
}
}
ScrollManager.propTypes = propTypes;
ScrollManager.defaultProps = defaultProps;
export default ScrollManager;