loadable-image
Version:
React Component to lazy load images
2 lines (1 loc) • 2.85 kB
JavaScript
import{jsx as e,jsxs as r,Fragment as t}from"react/jsx-runtime";import{InView as o}from"react-intersection-observer";import{forwardRef as i,useState as n,cloneElement as s}from"react";import{Fade as a}from"transitions-kit";function c(e,r){var t={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&r.indexOf(o)<0&&(t[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)r.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(t[o[i]]=e[o[i]])}return t}"function"==typeof SuppressedError&&SuppressedError;const l=i(((r,t)=>{var{style:o}=r,i=c(r,["style"]);return e("div",Object.assign({ref:t},i,{className:`AsyncImage-root ${i.className}`.trim(),style:Object.assign(Object.assign({},o),{display:"flex",overflow:"hidden",backgroundRepeat:"no-repeat",boxSizing:"border-box",backgroundSize:"cover",position:"relative"})}))})),b={top:0,left:0,width:"100%",height:"100%",position:"absolute",boxSizing:"border-box"},d=e("div",{className:"AsyncImage-loader",style:{backgroundColor:"#eee"}}),p=e("div",{className:"Asyncimage-error",style:{backgroundColor:"#eee"},children:e("svg",{fill:"#00000061",viewBox:"0 0 24 24",style:{position:"absolute",inset:0,width:"50%",height:"50%",margin:"auto"},children:e("path",{d:"M21 5c0-1.1-.9-2-2-2H5.83L21 18.17V5zM2.81 2.81 1.39 4.22 3 5.83V19c0 1.1.9 2 2 2h13.17l1.61 1.61 1.41-1.41L2.81 2.81zM6 17l3-4 2.25 3 .82-1.1 2.1 2.1H6z"})})});var u;!function(e){e[e.LOADING=0]="LOADING",e[e.LOADED=1]="LOADED",e[e.FAILED=2]="FAILED"}(u||(u={}));const m=o=>{var{error:i,loader:l,onLoad:d,onError:p,objectFit:m="cover",Transition:g=a,timeout:O=1e3,sources:y=[],inView:j}=o,f=c(o,["error","loader","onLoad","onError","objectFit","Transition","timeout","sources","inView"]);const[h,v]=n(u.LOADING);return r(t,{children:[e(a,{appear:!1,in:h===u.LOADING,timeout:O,unmountOnExit:!0,children:s(l,{style:Object.assign(Object.assign({},l.props.style),b)})}),j&&e(g,{in:h===u.LOADED,timeout:O,children:r("picture",{style:b,children:[y.map((r=>e("source",Object.assign({},r),r.srcSet))),e("img",Object.assign({},f,{className:"AsyncImage-image",style:Object.assign({objectFit:m},b),onLoad:e=>{v(u.LOADED),null==d||d(e)},onError:e=>{v(u.FAILED),null==p||p(e)}}))]})}),e(g,{in:h===u.FAILED,timeout:O,mountOnEnter:!0,unmountOnExit:!0,children:s(i,{style:Object.assign(Object.assign({},i.props.style),b)})})]})},g=r=>{var{loader:t=d,error:i=p,rootMargin:n="600px 0px",objectFit:s="cover",style:a={},className:b=""}=r,u=c(r,["loader","error","rootMargin","objectFit","style","className"]);return e(o,{rootMargin:n,triggerOnce:!0,children:({ref:r,inView:o})=>{var n;return e(l,{ref:r,className:b,style:a,children:e(m,Object.assign({error:i,loader:t,objectFit:null!==(n=a.objectFit)&&void 0!==n?n:s,inView:o},u))})}})};export{g as AsyncImage};