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