UNPKG

react-lazy-img-observer

Version:

A React component for lazy loading images with Intersection Observer

1 lines 2.02 kB
"use strict";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:y="20px",fallbackSrc:p,threshold:_=.5,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)((()=>{"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.useLayoutEffect)((()=>{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:_});return t.observe(w.current),()=>t.disconnect()}),[e,_,h]);const $="custom"===b?{}:"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(${y})`,transition:`filter ${g}`};return(0,jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment,{children:[!I&&x,!j&&(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,loading:"lazy",id:s?.toString(),onLoad:()=>{S(!0),v?.()},onError:()=>{p&&L!==p?z(p):k(!0)},srcSet:L?r:void 0,sizes:L?a:void 0,style:{backgroundColor:!I&&f?f:void 0,backgroundSize:"cover",backgroundPosition:"center",...d?{viewTransitionName:d}:{},...$,...m},...c})]})};exports.ImageLazy=ImageLazy,exports.default=ImageLazy;