forked from twobin/react-lazyload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
344 lines (272 loc) · 13.5 KB
/
index.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.forceCheck = exports.lazyload = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _event = require('./utils/event');
var _scrollParent = require('./utils/scrollParent');
var _scrollParent2 = _interopRequireDefault(_scrollParent);
var _debounce = require('./utils/debounce');
var _debounce2 = _interopRequireDefault(_debounce);
var _throttle = require('./utils/throttle');
var _throttle2 = _interopRequireDefault(_throttle);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _decorator = require('./decorator');
var _decorator2 = _interopRequireDefault(_decorator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* react-lazyload
*/
var defaultBoundingClientRect = { top: 0, right: 0, bottom: 0, left: 0, width: 0, height: 0 };
var LISTEN_FLAG = 'data-lazyload-listened';
var listeners = [];
var pending = [];
/**
* Check if `component` is visible in overflow container `parent`
* @param {node} component React component
* @param {node} parent component's scroll parent
* @return {bool}
*/
var checkOverflowVisible = function checkOverflowVisible(component, parent) {
var node = _reactDom2.default.findDOMNode(component);
var parentTop = void 0;
var parentHeight = void 0;
try {
var _parent$getBoundingCl = parent.getBoundingClientRect();
parentTop = _parent$getBoundingCl.top;
parentHeight = _parent$getBoundingCl.height;
} catch (e) {
parentTop = defaultBoundingClientRect.top;
parentHeight = defaultBoundingClientRect.height;
}
var windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
// calculate top and height of the intersection of the element's scrollParent and viewport
var intersectionTop = Math.max(parentTop, 0); // intersection's top relative to viewport
var intersectionHeight = Math.min(windowInnerHeight, parentTop + parentHeight) - intersectionTop; // height
// check whether the element is visible in the intersection
var top = void 0;
var height = void 0;
try {
var _node$getBoundingClie = node.getBoundingClientRect();
top = _node$getBoundingClie.top;
height = _node$getBoundingClie.height;
} catch (e) {
top = defaultBoundingClientRect.top;
height = defaultBoundingClientRect.height;
}
var offsetTop = top - intersectionTop; // element's top relative to intersection
var offsets = Array.isArray(component.props.offset) ? component.props.offset : [component.props.offset, component.props.offset]; // Be compatible with previous API
return offsetTop - offsets[0] <= intersectionHeight && offsetTop + height + offsets[1] >= 0;
};
/**
* Check if `component` is visible in document
* @param {node} component React component
* @return {bool}
*/
var checkNormalVisible = function checkNormalVisible(component) {
var node = _reactDom2.default.findDOMNode(component);
var top = void 0;
var elementHeight = void 0;
try {
var _node$getBoundingClie2 = node.getBoundingClientRect();
top = _node$getBoundingClie2.top;
elementHeight = _node$getBoundingClie2.height;
} catch (e) {
top = defaultBoundingClientRect.top;
elementHeight = defaultBoundingClientRect.height;
}
var windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
var offsets = Array.isArray(component.props.offset) ? component.props.offset : [component.props.offset, component.props.offset]; // Be compatible with previous API
return top - offsets[0] <= windowInnerHeight && top + elementHeight + offsets[1] >= 0;
};
/**
* Detect if element is visible in viewport, if so, set `visible` state to true.
* If `once` prop is provided true, remove component as listener after checkVisible
*
* @param {React} component React component that respond to scroll and resize
*/
var checkVisible = function checkVisible(component) {
var node = _reactDom2.default.findDOMNode(component);
if (!node) {
return;
}
var parent = (0, _scrollParent2.default)(node);
var isOverflow = component.props.overflow && parent !== node.ownerDocument && parent !== document && parent !== document.documentElement;
var visible = isOverflow ? checkOverflowVisible(component, parent) : checkNormalVisible(component);
if (visible) {
// Avoid extra render if previously is visible, yeah I mean `render` call,
// not actual DOM render
if (!component.visible) {
if (component.props.once) {
pending.push(component);
}
component.visible = true;
component.forceUpdate();
}
} else if (!(component.props.once && component.visible)) {
component.visible = false;
if (component.props.unmountIfInvisible) {
component.forceUpdate();
}
}
};
var purgePending = function purgePending() {
pending.forEach(function (component) {
var index = listeners.indexOf(component);
if (index !== -1) {
listeners.splice(index, 1);
}
});
pending = [];
};
var lazyLoadHandler = function lazyLoadHandler() {
for (var i = 0; i < listeners.length; ++i) {
var listener = listeners[i];
checkVisible(listener);
}
// Remove `once` component in listeners
purgePending();
};
// Depending on component's props
var delayType = void 0;
var finalLazyLoadHandler = null;
var LazyLoad = function (_Component) {
_inherits(LazyLoad, _Component);
function LazyLoad(props) {
_classCallCheck(this, LazyLoad);
var _this = _possibleConstructorReturn(this, (LazyLoad.__proto__ || Object.getPrototypeOf(LazyLoad)).call(this, props));
_this.visible = false;
return _this;
}
_createClass(LazyLoad, [{
key: 'componentDidMount',
value: function componentDidMount() {
if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {
if (_react2.default.Children.count(this.props.children) > 1) {
console.warn('[react-lazyload] Only one child is allowed to be passed to `LazyLoad`.');
}
if (this.props.wheel) {
// eslint-disable-line
console.warn('[react-lazyload] Props `wheel` is not supported anymore, try set `overflow` for lazy loading in overflow containers.');
}
// Warn the user if placeholder and height is not specified and the rendered height is 0
if (!this.props.placeholder && this.props.height === undefined && _reactDom2.default.findDOMNode(this).offsetHeight === 0) {
console.warn('[react-lazyload] Please add `height` props to <LazyLoad> for better performance.');
}
}
// It's unlikely to change delay type on the fly, this is mainly
// designed for tests
var needResetFinalLazyLoadHandler = false;
if (this.props.debounce !== undefined && delayType === 'throttle') {
console.warn('[react-lazyload] Previous delay function is `throttle`, now switching to `debounce`, try setting them unanimously');
needResetFinalLazyLoadHandler = true;
} else if (delayType === 'debounce' && this.props.debounce === undefined) {
console.warn('[react-lazyload] Previous delay function is `debounce`, now switching to `throttle`, try setting them unanimously');
needResetFinalLazyLoadHandler = true;
}
if (needResetFinalLazyLoadHandler) {
(0, _event.off)(window, 'scroll', finalLazyLoadHandler);
(0, _event.off)(window, 'resize', finalLazyLoadHandler);
finalLazyLoadHandler = null;
}
if (!finalLazyLoadHandler) {
if (this.props.debounce !== undefined) {
finalLazyLoadHandler = (0, _debounce2.default)(lazyLoadHandler, typeof this.props.debounce === 'number' ? this.props.debounce : 300);
delayType = 'debounce';
} else {
finalLazyLoadHandler = (0, _throttle2.default)(lazyLoadHandler, typeof this.props.throttle === 'number' ? this.props.throttle : 300);
delayType = 'throttle';
}
}
if (this.props.overflow) {
var parent = (0, _scrollParent2.default)(_reactDom2.default.findDOMNode(this));
if (parent && typeof parent.getAttribute === 'function') {
var listenerCount = 1 + +parent.getAttribute(LISTEN_FLAG);
if (listenerCount === 1) {
parent.addEventListener('scroll', finalLazyLoadHandler);
}
parent.setAttribute(LISTEN_FLAG, listenerCount);
}
} else if (listeners.length === 0 || needResetFinalLazyLoadHandler) {
var _props = this.props,
scroll = _props.scroll,
resize = _props.resize;
if (scroll) {
(0, _event.on)(window, 'scroll', finalLazyLoadHandler);
}
if (resize) {
(0, _event.on)(window, 'resize', finalLazyLoadHandler);
}
}
listeners.push(this);
checkVisible(this);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
return this.visible;
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.props.overflow) {
var parent = (0, _scrollParent2.default)(_reactDom2.default.findDOMNode(this));
if (parent && typeof parent.getAttribute === 'function') {
var listenerCount = +parent.getAttribute(LISTEN_FLAG) - 1;
if (listenerCount === 0) {
parent.removeEventListener('scroll', finalLazyLoadHandler);
parent.removeAttribute(LISTEN_FLAG);
} else {
parent.setAttribute(LISTEN_FLAG, listenerCount);
}
}
}
var index = listeners.indexOf(this);
if (index !== -1) {
listeners.splice(index, 1);
}
if (listeners.length === 0) {
(0, _event.off)(window, 'resize', finalLazyLoadHandler);
(0, _event.off)(window, 'scroll', finalLazyLoadHandler);
}
}
}, {
key: 'render',
value: function render() {
return this.visible ? this.props.children : this.props.placeholder ? this.props.placeholder : _react2.default.createElement('div', { style: { height: this.props.height }, className: 'lazyload-placeholder' });
}
}]);
return LazyLoad;
}(_react.Component);
LazyLoad.propTypes = {
once: _propTypes2.default.bool,
height: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
offset: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.arrayOf(_propTypes2.default.number)]),
overflow: _propTypes2.default.bool,
resize: _propTypes2.default.bool,
scroll: _propTypes2.default.bool,
children: _propTypes2.default.node,
throttle: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.bool]),
debounce: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.bool]),
placeholder: _propTypes2.default.node,
unmountIfInvisible: _propTypes2.default.bool
};
LazyLoad.defaultProps = {
once: false,
offset: 0,
overflow: false,
resize: false,
scroll: true,
unmountIfInvisible: false
};
var lazyload = exports.lazyload = _decorator2.default;
exports.default = LazyLoad;
exports.forceCheck = lazyLoadHandler;