react-load-on-view
Version:
React Higher-Order Component (HOC) that tracks UI elements to dynamically fetch data, load images, or trigger animations based on visibility.
2 lines (1 loc) • 1.94 kB
JavaScript
;var e=require("react");const t=(void 0)("/src/assets/**/*");function r(r,n){const[s,a]=e.useState({}),[i,o]=e.useState(""),[c,u]=e.useState(!1),[l,f]=e.useState(!1),g=n&&Array.isArray(r)&&r.length>0&&!l;return e.useEffect((()=>{if(!g)return;let e=!0;return(async()=>{u(!0),o("");try{const n=await async function(e){return Promise.all(e.map((async e=>{if(!t[e])throw new Error(`${e} not found`);const r=await t[e]();return"string"==typeof r.default&&/\.(jpg|jpeg|png|gif|webp|svg)$/i.test(r.default)?{src:r.default}:r.default||r})))}(r);e&&(!function(e,t){e.every((e=>e&&e.src))?t({images:e}):t(function(e){return e.reduce(((e,t)=>(t&&t.src?(e.images=e.images||[],e.images.push(t)):"object"==typeof t&&(e={...e,...t}),e)),{})}(e))}(n,a),f(!0))}catch(t){e&&function(e,t,r){e(r.message||"Failed to load data"),t({})}(o,a,t)}finally{e&&u(!1)}})(),()=>{e=!1}}),[r,n,l]),{data:s,error:i,loading:c}}function n({rootMargin:t="0px",threshold:r=0,triggerOnce:n=!0,root:s=null}={}){const[a,i]=e.useState(!1),[o,c]=e.useState(null),u=e.useRef(null);return e.useEffect((()=>{let e=!0;const a=new IntersectionObserver((([t])=>{e&&(c(t),i(t.isIntersecting),t.isIntersecting&&n&&a.disconnect())}),{root:s,rootMargin:t,threshold:r}),o=u.current;return o&&a.observe(o),()=>{e=!1,o&&a.unobserve(o),a.disconnect()}}),[t,r,n,s]),{ref:u,inView:a}}exports.useElementObserver=n,exports.useLazyLoadAssets=r,exports.withViewObserver=function(t,{animate:s=!1,afterWrapperIsVisibleClass:a="visible_wrapper",initialWrapperClass:i=(s?"invisible_wrapper":""),rootMargin:o="0px",threshold:c=0,root:u=null,triggerOnce:l=!0,lazyLoad:f=!1,paths:g=[]}={}){return function(d){const{ref:p,inView:h}=n({rootMargin:o,threshold:c,root:u,triggerOnce:l}),{data:m,error:v,loading:w}=f?r(g,h):{data:{},error:"",loading:!1},y=f?{...d,data:m,error:v,loading:w}:d,b=s&&h?d.special_animation||a:i;return e.createElement("div",{ref:p,className:b},e.createElement(t,y))}};