UNPKG

@gitlab/ui

Version:
51 lines (47 loc) 1.45 kB
import { isFunction } from 'lodash-es'; // IntersectionObserver-backed visibility directive. // Calls the function when the element enters the viewport. // The element is expanded by ROOT_MARGIN. const ROOT_MARGIN = '640px'; let observer = null; // Exported for testing purposes only const resetObserver = () => { var _observer; (_observer = observer) === null || _observer === void 0 ? void 0 : _observer.disconnect(); observer = null; }; const attachObserver = (el, callback) => { if (!isFunction(callback)) { throw TypeError('directive value must be a function'); } if (!observer) { // the observer instance is shared for performance reasons // more information: https://github.com/WICG/ResizeObserver/issues/59 observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.glVisibleHandler(); } }); }, { rootMargin: ROOT_MARGIN }); } el.glVisibleHandler = callback; observer.observe(el); }; const detachObserver = el => { if (el.glVisibleHandler) { var _observer2; delete el.glVisibleHandler; (_observer2 = observer) === null || _observer2 === void 0 ? void 0 : _observer2.unobserve(el); } }; const GlVisibleDirective = { bind(el, _ref) { let callback = _ref.value; attachObserver(el, callback); }, unbind: detachObserver }; export { GlVisibleDirective, resetObserver };