-
Notifications
You must be signed in to change notification settings - Fork 67
/
IntersectionObserver.js
186 lines (163 loc) · 6.51 KB
/
IntersectionObserver.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import React from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import invariant from 'invariant';
import IntersectionObserverContainer from './IntersectionObserverContainer';
import { isDOMTypeElement, shallowCompareOptions } from './utils';
/**
* The Intersection Observer API callback that is called whenever one element,
* called the target, intersects either the device viewport or a specified element.
* Also will get caled whenever the visibility of the target element changes and
* crosses desired amounts of intersection with the root.
* @param {array} changes
* @param {IntersectionObserver} observer
*/
export function callback(changes, observer) {
changes.forEach(entry => {
const instance = IntersectionObserverContainer.findElement(entry, observer);
if (instance) {
instance.handleChange(entry);
}
});
}
const observerOptions = ['root', 'rootMargin', 'threshold'];
const objectProto = Object.prototype;
export default class IntersectionObserver extends React.Component {
static displayName = 'IntersectionObserver';
static propTypes = {
/**
* The element that is used as the target to observe.
*/
children: PropTypes.element.isRequired,
/**
* The element that is used as the viewport for checking visibility of the target.
* Can be specified as string for selector matching within the document.
* Defaults to the browser viewport if not specified or if null.
*/
root: PropTypes.oneOfType(
[PropTypes.string].concat(typeof HTMLElement === 'undefined' ? [] : PropTypes.instanceOf(HTMLElement)),
),
/**
* Margin around the root. Can have values similar to the CSS margin property,
* e.g. "10px 20px 30px 40px" (top, right, bottom, left).
* If the root element is specified, the values can be percentages.
* This set of values serves to grow or shrink each side of the root element's
* bounding box before computing intersections.
* Defaults to all zeros.
*/
rootMargin: PropTypes.string,
/**
* Either a single number or an array of numbers which indicate at what percentage
* of the target's visibility the observer's callback should be executed.
* If you only want to detect when visibility passes the 50% mark, you can use a value of 0.5.
* If you want the callback run every time visibility passes another 25%,
* you would specify the array [0, 0.25, 0.5, 0.75, 1].
* The default is 0 (meaning as soon as even one pixel is visible, the callback will be run).
* A value of 1.0 means that the threshold isn't considered passed until every pixel is visible.
*/
threshold: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
/**
* When true indicate that events fire only until the element is intersecting.
* Different browsers behave differently towards the isIntersecting property, make sure
* you polyfill and/or override the IntersectionObserverEntry object's prototype to your needs.
* Defaults to false.
*/
onlyOnce: PropTypes.bool,
/**
* Controls whether the element should stop being observed by its IntersectionObserver instance.
* Defaults to false.
*/
disabled: PropTypes.bool,
/**
* Function that will be invoked whenever the intersection value for this element changes.
*/
onChange: PropTypes.func.isRequired,
};
get options() {
return observerOptions.reduce((prev, key) => {
if (objectProto.hasOwnProperty.call(this.props, key)) {
let value = this.props[key];
if (key === 'root' && objectProto.toString.call(this.props[key]) === '[object String]') {
value = document.querySelector(value);
}
return {
...prev,
[key]: value,
};
}
return prev;
}, {});
}
handleChange = event => {
this.props.onChange(event);
if (this.props.onlyOnce) {
// eslint-disable-next-line no-undef
if (process.env.NODE_ENV !== 'production') {
invariant(
'isIntersecting' in event,
"onlyOnce requires isIntersecting to exists in IntersectionObserverEntry's prototype. Either your browser or your polyfill lacks support.",
);
}
if (event.isIntersecting) {
this.unobserve();
}
}
};
handleNode = node => {
if (typeof this.props.children.ref === 'function') {
this.props.children.ref(node);
}
if (this.currentTarget && node && this.currentTarget !== node) {
this.unobserve();
this.shouldResetObserver = true;
}
this.target = node;
};
observe() {
this.target = isDOMTypeElement(this.target) ? this.target : findDOMNode(this.target);
this.observer = IntersectionObserverContainer.create(callback, this.options);
IntersectionObserverContainer.observe(this);
}
unobserve() {
if (this.target != null) {
IntersectionObserverContainer.unobserve(this);
}
}
reobserve() {
this.unobserve();
if (!this.props.disabled) {
this.observe();
}
}
componentDidMount() {
// eslint-disable-next-line no-undef
if (process.env.NODE_ENV !== 'production' && parseInt(React.version, 10) < 16) {
invariant(
this.target,
'Stateless function components cannot be given refs. Attempts to access this ref will fail.',
);
}
if (!this.props.disabled) {
this.observe();
}
}
componentWillUnmount() {
this.unobserve();
}
componentDidUpdate() {
if (this.shouldResetObserver) {
this.reobserve();
}
}
componentWillUpdate(nextProps) {
this.shouldResetObserver = observerOptions
.concat(['disabled'])
.some(option => shallowCompareOptions(nextProps[option], this.props[option]));
}
render() {
this.currentTarget = this.target;
return React.cloneElement(React.Children.only(this.props.children), {
ref: this.handleNode,
});
}
}