-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathvisible-area.js
50 lines (39 loc) · 1.08 KB
/
visible-area.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
/*
execute a callback once an element became fully visible in the viewport
*/
import '../prototype/window.requestanimationframe';
import isVisible from '../is/visible';
import visibleArea from '../util/visible-area';
import contextToElement from '../util/context-to-element';
export default function({context, callback, area} = {}) {
if (typeof callback !== 'function') {
throw new TypeError('when/visible-area requires options.callback to be a function');
}
if (typeof area !== 'number') {
area = 1;
}
const element = contextToElement({
label: 'when/visible-area',
context,
});
let raf;
let evaluate = null;
const disengage = function() {
raf && cancelAnimationFrame(raf);
};
const predicate = function() {
return !isVisible(element) || visibleArea(element) < area || callback(element) === false;
};
const checkPredicate = function() {
if (predicate()) {
evaluate();
return;
}
disengage();
};
evaluate = function() {
raf = requestAnimationFrame(checkPredicate);
};
evaluate();
return { disengage };
}