forked from joshwnj/react-visibility-sensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visibility-sensor.js
324 lines (282 loc) · 8.6 KB
/
visibility-sensor.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
'use strict';
var React = require('react');
var ReactDOM = require('react-dom');
var PropTypes = require('prop-types');
var createReactClass = require('create-react-class');
var isVisibleWithOffset = require('./lib/is-visible-with-offset')
var containmentPropType = PropTypes.any;
if (typeof window !== 'undefined') {
containmentPropType = PropTypes.instanceOf(window.Element);
}
function throttle (callback, limit) {
var wait = false;
return function () {
if (!wait) {
wait = true;
setTimeout(function () {
callback();
wait = false;
}, limit);
}
}
}
function debounce(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
module.exports = createReactClass({
displayName: 'VisibilitySensor',
propTypes: {
onChange: PropTypes.func,
active: PropTypes.bool,
partialVisibility: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
]),
delayedCall: PropTypes.bool,
offset: PropTypes.oneOfType([
PropTypes.shape({
top: PropTypes.number,
left: PropTypes.number,
bottom: PropTypes.number,
right: PropTypes.number
}),
// deprecated offset property
PropTypes.shape({
direction: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
value: PropTypes.number
})
]),
scrollCheck: PropTypes.bool,
scrollDelay: PropTypes.number,
scrollThrottle: PropTypes.number,
resizeCheck: PropTypes.bool,
resizeDelay: PropTypes.number,
resizeThrottle: PropTypes.number,
intervalCheck: PropTypes.bool,
intervalDelay: PropTypes.number,
containment: containmentPropType,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func,
]),
minTopValue: PropTypes.number,
},
getDefaultProps: function () {
return {
active: true,
partialVisibility: false,
minTopValue: 0,
scrollCheck: false,
scrollDelay: 250,
scrollThrottle: -1,
resizeCheck: false,
resizeDelay: 250,
resizeThrottle: -1,
intervalCheck: true,
intervalDelay: 100,
delayedCall: false,
offset: {},
containment: null,
children: React.createElement('span')
};
},
getInitialState: function () {
return {
isVisible: null,
visibilityRect: {}
};
},
componentDidMount: function () {
this.node = ReactDOM.findDOMNode(this);
if (this.props.active) {
this.startWatching();
}
},
componentWillUnmount: function () {
this.stopWatching();
},
componentWillReceiveProps: function (nextProps) {
if (nextProps.active && !this.props.active) {
this.setState(this.getInitialState());
this.startWatching();
} else if (!nextProps.active) {
this.stopWatching();
}
},
getContainer: function () {
return this.props.containment || window;
},
addEventListener: function (target, event, delay, throttle) {
if (!this.debounceCheck) {
this.debounceCheck = {};
}
var timeout;
var func;
var later = function () {
timeout = null;
this.check();
}.bind(this);
if (throttle > -1) {
func = function () {
if (!timeout) {
timeout = setTimeout(later, throttle || 0);
}
};
} else {
func = function () {
clearTimeout(timeout);
timeout = setTimeout(later, delay || 0);
};
}
var info = {
target: target,
fn: func,
getLastTimeout: function () {
return timeout;
},
};
target.addEventListener(event, info.fn);
this.debounceCheck[event] = info;
},
startWatching: function () {
if (this.debounceCheck || this.interval) { return; }
if (this.props.intervalCheck) {
this.interval = setInterval(this.check, this.props.intervalDelay);
}
if (this.props.scrollCheck) {
this.addEventListener(
this.getContainer(),
'scroll',
this.props.scrollDelay,
this.props.scrollThrottle
);
}
if (this.props.resizeCheck) {
this.addEventListener(
window,
'resize',
this.props.resizeDelay,
this.props.resizeThrottle
);
}
// if dont need delayed call, check on load ( before the first interval fires )
!this.props.delayedCall && this.check();
},
stopWatching: function () {
if (this.debounceCheck) {
// clean up event listeners and their debounce callers
for (var debounceEvent in this.debounceCheck) {
if (this.debounceCheck.hasOwnProperty(debounceEvent)) {
var debounceInfo = this.debounceCheck[debounceEvent];
clearTimeout(debounceInfo.getLastTimeout());
debounceInfo.target.removeEventListener(
debounceEvent, debounceInfo.fn
);
this.debounceCheck[debounceEvent] = null;
}
}
}
this.debounceCheck = null;
if (this.interval) { this.interval = clearInterval(this.interval); }
},
/**
* Check if the element is within the visible viewport
*/
check: function () {
var el = this.node;
var rect;
var containmentRect;
// if the component has rendered to null, dont update visibility
if (!el) {
return this.state;
}
rect = el.getBoundingClientRect();
if (this.props.containment) {
var containmentDOMRect = this.props.containment.getBoundingClientRect();
containmentRect = {
top: containmentDOMRect.top,
left: containmentDOMRect.left,
bottom: containmentDOMRect.bottom,
right: containmentDOMRect.right,
}
} else {
containmentRect = {
top: 0,
left: 0,
bottom: window.innerHeight || document.documentElement.clientHeight,
right: window.innerWidth || document.documentElement.clientWidth
};
}
// Check if visibility is wanted via offset?
var offset = this.props.offset || {};
var hasValidOffset = typeof offset === 'object';
if (hasValidOffset) {
containmentRect.top += offset.top || 0;
containmentRect.left += offset.left || 0;
containmentRect.bottom -= offset.bottom || 0;
containmentRect.right -= offset.right || 0;
}
var visibilityRect = {
top: rect.top >= containmentRect.top,
left: rect.left >= containmentRect.left,
bottom: rect.bottom <= containmentRect.bottom,
right: rect.right <= containmentRect.right
};
var isVisible = (
visibilityRect.top &&
visibilityRect.left &&
visibilityRect.bottom &&
visibilityRect.right
);
// check for partial visibility
if (this.props.partialVisibility) {
var partialVisible =
rect.top <= containmentRect.bottom && rect.bottom >= containmentRect.top &&
rect.left <= containmentRect.right && rect.right >= containmentRect.left;
// account for partial visibility on a single edge
if (typeof this.props.partialVisibility === 'string') {
partialVisible = visibilityRect[this.props.partialVisibility]
}
// if we have minimum top visibility set by props, lets check, if it meets the passed value
// so if for instance element is at least 200px in viewport, then show it.
isVisible = this.props.minTopValue
? partialVisible && rect.top <= (containmentRect.bottom - this.props.minTopValue)
: partialVisible
}
// Deprecated options for calculating offset.
if (typeof offset.direction === 'string' &&
typeof offset.value === 'number') {
console.warn('[notice] offset.direction and offset.value have been deprecated. They still work for now, but will be removed in next major version. Please upgrade to the new syntax: { %s: %d }', offset.direction, offset.value)
isVisible = isVisibleWithOffset(offset, rect, containmentRect);
}
var state = this.state;
// notify the parent when the value changes
if (this.state.isVisible !== isVisible) {
state = {
isVisible: isVisible,
visibilityRect: visibilityRect
};
this.setState(state);
if (this.props.onChange) this.props.onChange(isVisible, visibilityRect);
}
return state;
},
render: function () {
if (this.props.children instanceof Function) {
return this.props.children({
isVisible: this.state.isVisible,
visibilityRect: this.state.visibilityRect,
});
}
return React.Children.only(this.props.children);
}
});