1 | "use strict";
|
2 |
|
3 | const {getRootMargin, getIntersectionRatio, getIsIntersecting} = require("./intersectionCalc");
|
4 | const IntersectionObserverEntry = require("./intersectionObserverEntry");
|
5 |
|
6 | module.exports = function FakeIntersectionObserver(browser) {
|
7 | const observed = [];
|
8 |
|
9 | IntersectionObserver._getObserved = function () {
|
10 | return observed;
|
11 | };
|
12 |
|
13 | const intersectionObserverEntry = IntersectionObserverEntry(browser);
|
14 | intersectionObserverEntry.prototype.intersectionRatio = getIntersectionRatio;
|
15 | intersectionObserverEntry.prototype.isIntersecting = getIsIntersecting;
|
16 | browser.window.IntersectionObserverEntry = intersectionObserverEntry;
|
17 |
|
18 | return IntersectionObserver;
|
19 |
|
20 | function IntersectionObserver(viewPortUpdate, options) {
|
21 | const toObserve = [];
|
22 | const rootMargin = getRootMargin(options);
|
23 | browser.window.addEventListener("scroll", onScroll);
|
24 | let previousEntries = [];
|
25 |
|
26 | return {
|
27 | disconnect() {
|
28 | toObserve.length = 0;
|
29 | },
|
30 | observe(element) {
|
31 | toObserve.push(element);
|
32 | observed.push(element);
|
33 | const newEntries = [element].map((el) => intersectionObserverEntry(el, rootMargin));
|
34 | viewPortUpdate(newEntries);
|
35 | previousEntries = previousEntries.concat(newEntries);
|
36 | },
|
37 | unobserve(element) {
|
38 | const idx = toObserve.indexOf(element);
|
39 | if (idx > -1) {
|
40 | toObserve.splice(idx, 1);
|
41 | }
|
42 | }
|
43 | };
|
44 |
|
45 | function onScroll() {
|
46 | const entries = toObserve.map((el) => intersectionObserverEntry(el, rootMargin));
|
47 | const changedEntries = entries.filter(hasChanged);
|
48 |
|
49 | if (changedEntries.length > 0) {
|
50 | viewPortUpdate(changedEntries);
|
51 | }
|
52 |
|
53 | previousEntries = entries;
|
54 | }
|
55 |
|
56 | function hasChanged(entry) {
|
57 | const previous = previousEntries.find((x) => x.target === entry.target);
|
58 | if (!previous) return true;
|
59 | return entry.intersectionRatio !== previous.intersectionRatio;
|
60 | }
|
61 | }
|
62 | };
|