-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (43 loc) · 1.13 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
'use strict';
/** @jsx element */
import element from 'magic-virtual-element';
let inViewport;
const watchers = {};
export default {
initialState (props) {
return {
visible: false
};
},
defaultProps: {
heigth: 1,
width: 1
},
render ({ props: { children, offset, height, width }, state: { visible } }) {
// in-viewport doesn't work with a 0 sized element
height = height || 1;
width = width || 1;
const style = { 'min-width': width, 'min-height': height };
const content = visible ? children : undefined;
return (<div class='lazy-load' style={style}>{content}</div>);
},
afterMount ({ props: { offset }, id }, el, setState) {
// adding inViewport here since it doesn't work when rendering on the server
if (!inViewport) {
inViewport = require('in-viewport');
}
watchers[id] = inViewport(el, { offset: Number(offset) || 0 }, () => {
watchers[id].dispose();
delete watchers[id];
setState({
visible: true
});
});
},
beforeUnmount ({ id }) {
if (watchers[id]) {
watchers[id].dispose();
delete watchers[id];
}
}
};