react-cool-inview
Version:
React hook to monitor an element enters or leaves the viewport (or another element).
2 lines (1 loc) • 2.67 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");function r(){return r=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])}return e},r.apply(this,arguments)}function n(e,r){if(null==e)return{};var n,t,o={},i=Object.keys(e);for(t=0;t<i.length;t++)n=i[t],r.indexOf(n)>=0||(o[n]=e[n]);return o}var t=function(r){var n=e.useRef(r);return n.current=r,n},o=function(n){var o=void 0===n?{}:n,i=o.root,c=o.rootMargin,u=o.threshold,s=void 0===u?0:u,l=o.trackVisibility,a=o.delay,v=o.unobserveOnEnter,f=o.onChange,b=o.onEnter,y=o.onLeave,d=e.useState({inView:!1,scrollDirection:{}}),h=d[0],p=d[1],w=e.useRef(!1),g=e.useRef({}),O=e.useRef(),x=e.useRef(!1),R=t(f),I=t(b),V=t(y),k=e.useRef(),C=e.useCallback((function(){O.current&&(O.current.disconnect(),g.current={})}),[]),E=e.useCallback((function(e){e&&e!==k.current&&(C(),k.current=e),O.current&&k.current&&O.current.observe(k.current)}),[C]),M=e.useCallback((function(){if(k.current){var e=k.current.getBoundingClientRect(),r=e.x,n=e.y;g.current={x:r,y:n}}}),[k]);return e.useEffect((function(){if(!("IntersectionObserver"in window)||!("IntersectionObserverEntry"in window))return console.error("💡 react-cool-inview: the browser doesn't support Intersection Observer, please install polyfill: https://github.com/wellyshen/react-cool-inview#intersection-observer-polyfill"),function(){return null};var e=!0;return O.current=new IntersectionObserver((function(n){var t=n[0],o=t.intersectionRatio,i=t.isIntersecting,c=t.boundingClientRect,u=c.x,a=c.y,f=t.isVisible,b={},y=Array.isArray(s)?Math.min.apply(Math,s):s,d=void 0!==i?i:o>0;d=y>0?o>=y:d,u<g.current.x&&(b.horizontal="left"),u>g.current.x&&(b.horizontal="right"),g.current.x=u,a<g.current.y&&(b.vertical="up"),a>g.current.y&&(b.vertical="down"),g.current.y=a;var h={entry:t,scrollDirection:b,observe:E,unobserve:C};l&&(void 0!==f||x.current||(console.warn("💡 react-cool-inview: the browser doesn't support Intersection Observer v2, fallback to v1 behavior"),x.current=!0),void 0!==f&&(d=f)),d&&!w.current&&(v&&C(),I.current&&I.current(h)),!d&&w.current&&V.current&&V.current(h),R.current&&R.current(r({},h,{inView:d})),e&&p({inView:d,scrollDirection:b,entry:t}),w.current=d}),{root:i,rootMargin:c,threshold:s,trackVisibility:l,delay:a}),E(),function(){e=!1,C()}}),[v,i,c,JSON.stringify(s),l,a,E,C]),r({},h,{observe:E,unobserve:C,updatePosition:M})},i=["children"],c=["observe"];exports.InView=function(t){var u=t.children,s=n(t,i),l=o(s),a=l.observe,v=n(l,c);return e.cloneElement(u,r({observe:a},v))},exports.useInView=o;