react-lazy-img-observer
Version:
A React component for lazy loading images with Intersection Observer
1 lines • 2.16 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageLazy=void 0;const jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),ImageLazy=({src:e,alt:t,srcSet:r,sizes:a,width:o,height:n,className:i,id:s,extraData:c,title:l,useTitleFromAlt:u=!1,viewTransitionName:d,style:m,backgroundColor:f,animationDuration:g="0.9s",blurAmount:p="20px",fallbackSrc:_,threshold:y=.1,transitionType:b="blur",onLoadComplete:v,visibleByDefault:h=!1,loadingComponent:x})=>{const w=(0,react_1.useRef)(null),[L,z]=(0,react_1.useState)(h?e:null),[I,S]=(0,react_1.useState)(!1),[j,k]=(0,react_1.useState)(!1);(0,react_1.useEffect)((()=>{S(!1),k(!1),z(h?e:null)}),[e,h]),(0,react_1.useEffect)((()=>{"undefined"!=typeof window&&window?.location?.hostname?.includes("localhost")&&(t||console.warn("[ImageLazy] ⚠️ Se recomienda definir el atributo 'alt' por accesibilidad."),e||console.warn("[ImageLazy] ⚠️ La prop 'src' está vacía o nula. La imagen no se cargará."))}),[t,e]),(0,react_1.useEffect)((()=>{if("undefined"==typeof window||h)return;if("undefined"==typeof IntersectionObserver||!w.current)return;const t=new IntersectionObserver((r=>{r.forEach((r=>{r.isIntersecting&&(z(e),t.unobserve(r.target))}))}),{root:null,rootMargin:"0px",threshold:y});return t.observe(w.current),()=>t.disconnect()}),[e,y,h,L]);const E="custom"===b,$=(0,react_1.useMemo)((()=>E?{}:"fade"===b?{opacity:I?1:0,transition:`opacity ${g}`}:"scale"===b?{transform:I?"scale(1)":"scale(1.05)",opacity:I?1:0,transition:`transform ${g}, opacity ${g}`}:{filter:I?"none":`blur(${p})`,transition:`filter ${g}`}),[b,I,g,p,E]),C=(0,react_1.useMemo)((()=>({backgroundColor:!I&&f?f:void 0,backgroundSize:"cover",backgroundPosition:"center",...d?{viewTransitionName:d}:{},...$,...m})),[I,f,d,$,m]);return(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[!I&&x,(!j||null===L)&&(0,jsx_runtime_1.jsx)("img",{ref:w,src:L??void 0,alt:t,title:l??(u?t:void 0),className:i,width:o,height:n,id:s?.toString(),onLoad:()=>{S(!0),v?.()},onError:()=>{_&&L!==_?z(_):k(!0)},srcSet:L?r:void 0,sizes:L?a:void 0,style:C,...c})]})};exports.ImageLazy=ImageLazy,exports.default=ImageLazy;