1 | "use strict";
|
2 |
|
3 | module.exports = {
|
4 | getRootMargin,
|
5 | getIntersectionRatio,
|
6 | getIsIntersecting
|
7 | };
|
8 |
|
9 | function getRootMargin({rootMargin = ""} = {}) {
|
10 | const [top, right, bottom, left] = rootMargin
|
11 | .split(" ")
|
12 | .map((num) => parseInt(num));
|
13 |
|
14 | return {
|
15 | top: firstOf(top),
|
16 | right: firstOf(right, top),
|
17 | bottom: firstOf(bottom, top),
|
18 | left: firstOf(left, right, top)
|
19 | };
|
20 | }
|
21 |
|
22 | function firstOf(...args) {
|
23 | for (let i = 0; i < args.length; i++) {
|
24 | if (args[i] !== undefined && !isNaN(args[i])) {
|
25 | return args[i];
|
26 | }
|
27 | }
|
28 |
|
29 | return 0;
|
30 | }
|
31 |
|
32 | function getIntersectionRatio(boundingClientRect, windowInnerHeight, rootMargin = {}) {
|
33 | const {top, height, bottom = top + height} = boundingClientRect;
|
34 | const {top: marginTop, bottom: marginBottom} = rootMargin;
|
35 |
|
36 | const topIntersection = -(marginTop || 0);
|
37 | const bottomIntersection = windowInnerHeight + (marginBottom || 0);
|
38 |
|
39 | if (top < topIntersection) {
|
40 | return Math.max((bottom - topIntersection) / height, 0);
|
41 | }
|
42 |
|
43 | if (bottom > bottomIntersection) {
|
44 | return Math.max((bottomIntersection - top) / height, 0);
|
45 | }
|
46 |
|
47 | return 1;
|
48 | }
|
49 |
|
50 | function getIsIntersecting(intersectionRatio) {
|
51 | return intersectionRatio > 0;
|
52 | }
|