UNPKG

react-intersection

Version:

A React interface for the Intersection Observer API

106 lines (77 loc) 2.9 kB
"use strict"; exports.__esModule = true; exports["default"] = void 0; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var IntersectionObserverWrapper = /*#__PURE__*/ function () { function IntersectionObserverWrapper(props) { var _this = this; _defineProperty(this, "observedQueue", []); _defineProperty(this, "observedMap", new WeakMap()); _defineProperty(this, "activeObservers", []); _defineProperty(this, "observer", void 0); _defineProperty(this, "props", void 0); _defineProperty(this, "fireListener", function (entry) { var onChange = _this.observedMap.get(entry.target); if (onChange) onChange(entry); }); _defineProperty(this, "fireListeners", function (entries) { return entries.forEach(_this.fireListener); }); _defineProperty(this, "observe", function (child, onChange) { _this.observedQueue.push({ child: child, onChange: onChange }); _this.activeObservers.push(child); _this.flushQueue(); }); _defineProperty(this, "unobserve", function (child) { _this.observedMap["delete"](child); _this.observer.unobserve(child); _this.activeObservers.splice(_this.activeObservers.indexOf(child), 1); }); if (typeof IntersectionObserver === 'undefined') return; this.createObserver(props); this.flushQueue(); } var _proto = IntersectionObserverWrapper.prototype; _proto.createObserver = function createObserver(_ref) { var root = _ref.root, _ref$rootMargin = _ref.rootMargin, rootMargin = _ref$rootMargin === void 0 ? '0px 0px 0px 0px' : _ref$rootMargin, _ref$threshold = _ref.threshold, threshold = _ref$threshold === void 0 ? [0, 1] : _ref$threshold; this.observer = new IntersectionObserver(this.fireListeners, { root: root, rootMargin: rootMargin, threshold: threshold }); }; _proto.flushQueue = function flushQueue() { var _this2 = this; if (!this.observer) return; this.observedQueue.forEach(function (_ref2) { var child = _ref2.child, onChange = _ref2.onChange; _this2.observedMap.set(child, onChange); _this2.observer.observe(child); }); }; _proto.disconnect = function disconnect() { this.observer.disconnect(); }; _proto.reconnect = function reconnect(props) { var _this3 = this; this.disconnect(); this.createObserver(props); var observers = this.activeObservers; this.activeObservers = []; observers.forEach(function (child) { return _this3.observe(child, _this3.observedMap.get(child)); }); }; return IntersectionObserverWrapper; }(); exports["default"] = IntersectionObserverWrapper;