UNPKG

@trail-ui/react

Version:
92 lines (90 loc) 2.46 kB
// src/image/image.tsx import { useImage as useImageBase } from "@trail-ui/hooks"; import { clsx, dataAttr } from "@trail-ui/shared-utils"; import { filterVariantProps, image } from "@trail-ui/theme"; import { forwardRef, useMemo } from "react"; import { jsx } from "react/jsx-runtime"; function Image(props, ref) { const variantProps = filterVariantProps(props, image.variantKeys); const { as, src, srcSet, sizes, crossOrigin, className, classNames, isLoading: isLoadingProp, fallbackSrc, disableSkeleton = !!fallbackSrc, loading, removeWrapper, onLoad, onError, ...otherProps } = props; const Component = as || "img"; const imageStatus = useImageBase({ src, srcSet, sizes, crossOrigin, loading, onLoad, onError, ignoreFallback: false }); const isImgLoaded = imageStatus === "loaded" && !isLoadingProp; const isLoading = imageStatus === "loading" || isLoadingProp; const isZoomed = props.isZoomed; const showFallback = (!src || !isImgLoaded) && !!fallbackSrc; const showSkeleton = isLoading && !disableSkeleton; const { w } = useMemo(() => { return { w: props.width ? typeof props.width === "number" ? `${props.width}px` : props.width : "fit-content" }; }, [props == null ? void 0 : props.width]); const slots = useMemo( () => image({ ...variantProps, showSkeleton }), [showSkeleton, variantProps] ); const imgStyles = clsx(className, classNames == null ? void 0 : classNames.img); const img = /* @__PURE__ */ jsx( Component, { ref, className: slots.img({ class: imgStyles }), src, srcSet, sizes, crossOrigin, "data-loaded": dataAttr(isImgLoaded), ...otherProps } ); if (removeWrapper) { return img; } const zoomed = /* @__PURE__ */ jsx("div", { className: slots.zoomedWrapper({ class: classNames == null ? void 0 : classNames.zoomedWrapper }), children: img }); if (isZoomed || !disableSkeleton || fallbackSrc) { return /* @__PURE__ */ jsx( "div", { className: slots.wrapper({ class: classNames == null ? void 0 : classNames.wrapper }), style: { maxWidth: w, backgroundImage: showFallback ? `url(${fallbackSrc})` : void 0 }, children: isZoomed ? zoomed : img } ); } return img; } var _Image = forwardRef(Image); export { _Image };