UNPKG

@penaprieto/design-system

Version:

Multi-brand React design system with design tokens from Figma

45 lines (44 loc) 1.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Image = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); require("./Image.css"); const Image = ({ src, alt, lazy = true, placeholder, fallback, fit = 'cover', className = '', ...rest }) => { const [isLoading, setIsLoading] = (0, react_1.useState)(true); const [hasError, setHasError] = (0, react_1.useState)(false); const [isInView, setIsInView] = (0, react_1.useState)(!lazy); const imgRef = (0, react_1.useRef)(null); (0, react_1.useEffect)(() => { if (!lazy) return; const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { setIsInView(true); observer.disconnect(); } }, { rootMargin: '50px' }); if (imgRef.current) { observer.observe(imgRef.current); } return () => observer.disconnect(); }, [lazy]); const handleLoad = () => { setIsLoading(false); }; const handleError = () => { setIsLoading(false); setHasError(true); }; const rootClassName = [ 'ds-image', `ds-image--${fit}`, isLoading && 'ds-image--loading', hasError && 'ds-image--error', className, ] .filter(Boolean) .join(' '); return ((0, jsx_runtime_1.jsxs)("div", { ref: imgRef, className: rootClassName, children: [isLoading && placeholder && ((0, jsx_runtime_1.jsx)("div", { className: "ds-image__placeholder", children: placeholder })), hasError && fallback ? ((0, jsx_runtime_1.jsx)("div", { className: "ds-image__fallback", children: fallback })) : (isInView && ((0, jsx_runtime_1.jsx)("img", { src: src, alt: alt, onLoad: handleLoad, onError: handleError, className: "ds-image__img", ...rest })))] })); }; exports.Image = Image;