loadable-image
Version:
React Component to lazy load images
2 lines (1 loc) • 2.89 kB
JavaScript
"use strict";var e=require("react/jsx-runtime"),r=require("react-intersection-observer"),t=require("react"),o=require("transitions-kit");function s(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 s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)r.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(t[o[s]]=e[o[s]])}return t}"function"==typeof SuppressedError&&SuppressedError;const n=t.forwardRef(((r,t)=>{var{style:o}=r,n=s(r,["style"]);return e.jsx("div",Object.assign({ref:t},n,{className:`AsyncImage-root ${n.className}`.trim(),style:Object.assign(Object.assign({},o),{display:"flex",overflow:"hidden",backgroundRepeat:"no-repeat",boxSizing:"border-box",backgroundSize:"cover",position:"relative"})}))})),i={top:0,left:0,width:"100%",height:"100%",position:"absolute",boxSizing:"border-box"},a=e.jsx("div",{className:"AsyncImage-loader",style:{backgroundColor:"#eee"}}),c=e.jsx("div",{className:"Asyncimage-error",style:{backgroundColor:"#eee"},children:e.jsx("svg",{fill:"#00000061",viewBox:"0 0 24 24",style:{position:"absolute",inset:0,width:"50%",height:"50%",margin:"auto"},children:e.jsx("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 l;!function(e){e[e.LOADING=0]="LOADING",e[e.LOADED=1]="LOADED",e[e.FAILED=2]="FAILED"}(l||(l={}));const u=r=>{var{error:n,loader:a,onLoad:c,onError:u,objectFit:d="cover",Transition:b=o.Fade,timeout:j=1e3,sources:g=[],inView:p}=r,m=s(r,["error","loader","onLoad","onError","objectFit","Transition","timeout","sources","inView"]);const[O,y]=t.useState(l.LOADING);return e.jsxs(e.Fragment,{children:[e.jsx(o.Fade,{appear:!1,in:O===l.LOADING,timeout:j,unmountOnExit:!0,children:t.cloneElement(a,{style:Object.assign(Object.assign({},a.props.style),i)})}),p&&e.jsx(b,{in:O===l.LOADED,timeout:j,children:e.jsxs("picture",{style:i,children:[g.map((r=>e.jsx("source",Object.assign({},r),r.srcSet))),e.jsx("img",Object.assign({},m,{className:"AsyncImage-image",style:Object.assign({objectFit:d},i),onLoad:e=>{y(l.LOADED),null==c||c(e)},onError:e=>{y(l.FAILED),null==u||u(e)}}))]})}),e.jsx(b,{in:O===l.FAILED,timeout:j,mountOnEnter:!0,unmountOnExit:!0,children:t.cloneElement(n,{style:Object.assign(Object.assign({},n.props.style),i)})})]})};exports.AsyncImage=t=>{var{loader:o=a,error:i=c,rootMargin:l="600px 0px",objectFit:d="cover",style:b={},className:j=""}=t,g=s(t,["loader","error","rootMargin","objectFit","style","className"]);return e.jsx(r.InView,{rootMargin:l,triggerOnce:!0,children:({ref:r,inView:t})=>{var s;return e.jsx(n,{ref:r,className:j,style:b,children:e.jsx(u,Object.assign({error:i,loader:o,objectFit:null!==(s=b.objectFit)&&void 0!==s?s:d,inView:t},g))})}})};