"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _1 = require("../../../../../Class/$");
const Holder_1 = require("../../../../../Class/Holder");
const array_1 = require("../../../../../util/array");
const _ids_1 = require("../../../../_ids");
const globalComponent_1 = require("../../../../globalComponent");
class IntersectionObserver_ extends Holder_1.Holder {
    constructor(system) {
        super({
            fi: ['root', 'opt'],
            fo: ['observer'],
            i: [],
            o: [],
        }, {
            input: {
                root: {
                    ref: true,
                },
            },
            output: {
                observer: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_INTERSECTION_OBSERVER);
    }
    async f({ root }, done) {
        const { api: { document: { IntersectionObserver }, }, } = this.__system;
        const globalId = root.getGlobalId();
        const _component = await (0, globalComponent_1.firstGlobalComponentPromise)(this.__system, globalId);
        const callback = (entries) => {
            for (let i = 0; i < entries.length; i++) {
                const entry = entries[i];
                const callback = callbacks[i];
                if (!callback) {
                    return;
                }
                const _entry = {
                    isIntersecting: entry.isIntersecting,
                    time: entry.time,
                };
                callback(_entry);
            }
        };
        let base = _component.getRootBase();
        let r = _component;
        while (base.length === 0) {
            base = r.$slotParent.getRootBase();
            r = r.$slotParent;
        }
        const rootFirstRootLeaf = base[0][1];
        const _observer = new IntersectionObserver(callback, {
            root: rootFirstRootLeaf.$element,
            threshold: 0.1,
        });
        this._observer = _observer;
        const callbacks = [];
        const observer = new (class IntersectionObserver_ extends _1.$ {
            constructor() {
                super(...arguments);
                this.__ = ['OB'];
            }
            observe(element, callback) {
                callbacks.push(callback);
                _observer.observe(element);
                return () => {
                    (0, array_1.remove)(callbacks, callback);
                    _observer.unobserve(element);
                };
            }
        })(this.__system);
        done({ observer });
    }
    d() {
        if (this._observer) {
            this._observer.disconnect();
            this._observer = undefined;
        }
    }
}
exports.default = IntersectionObserver_;
//# sourceMappingURL=index.js.map