All files / src/components/ui/Image index.tsx

94.42% Statements 271/287
75.75% Branches 25/33
80% Functions 4/5
94.42% Lines 271/287

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 2881x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 35x 37x 37x 37x 37x 37x 37x 37x 37x 37x 9x 9x 37x 37x 37x 37x 2x 2x 37x 37x 37x 37x 2x 2x 2x 37x 37x 37x 37x 33x                                 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 32x 32x 32x 32x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x  
'use client';
 
/**
 * Unified Image Component
 *
 * A flexible image component that combines the best features from all image components:
 * - Error handling with fallback
 * - Loading skeleton/blur placeholder
 * - Cloudinary integration
 * - Aspect ratio support
 * - Lazy loading via IntersectionObserver
 * - Dark mode support
 *
 * @example
 * ```tsx
 * // Basic usage
 * <Image
 *   src="/images/product.jpg"
 *   alt="Product"
 *   width={300}
 *   height={300}
 * />
 *
 * // With Cloudinary
 * <Image
 *   publicId="products/shirt"
 *   alt="Shirt"
 *   width={400}
 *   height={400}
 * />
 *
 * // With loading effects
 * <Image
 *   src="/images/hero.jpg"
 *   alt="Hero"
 *   width={1200}
 *   height={600}
 *   placeholder="blur"
 *   showSkeleton
 * />
 * ```
 */
 
import { useState, useCallback, useRef, useEffect, memo } from 'react';
import NextImage, { ImageProps as NextImageProps } from 'next/image';
import { cn } from '@/lib/core';
import {
  buildCloudinaryUrl,
  buildCloudinaryBlurPlaceholder,
  generateBlurPlaceholder,
  aspectRatioClasses,
  objectFitClasses,
  DEFAULT_PLACEHOLDER,
} from '@/lib/image';
 
export interface ImageProps extends Omit<NextImageProps, 'src' | 'placeholder'> {
  /** Image source URL */
  src?: string | null;
  /** Cloudinary public ID (alternative to src) */
  publicId?: string;
  /** Fallback image URL on error */
  fallback?: string;
  /** Aspect ratio for container */
  aspectRatio?: '1:1' | '4:3' | '16:9' | '3:4' | '21:9' | 'auto';
  /** Object fit behavior */
  objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down';
  /** Placeholder type */
  placeholder?: 'blur' | 'skeleton' | 'none';
  /** Custom placeholder color (for blur) */
  placeholderColor?: string;
  /** Show loading skeleton */
  showSkeleton?: boolean;
  /** Lazy load with IntersectionObserver */
  lazyLoad?: boolean;
  /** IntersectionObserver root margin */
  rootMargin?: string;
  /** Container className */
  containerClassName?: string;
  /** Callback when image loads */
  onLoadComplete?: () => void;
  /** Callback when image fails */
  onLoadError?: () => void;
}
 
// Check if IntersectionObserver is available
const hasIntersectionObserver =
  typeof window !== 'undefined' && typeof IntersectionObserver !== 'undefined';
 
export const Image = memo(function Image({
  src,
  publicId,
  fallback = DEFAULT_PLACEHOLDER,
  alt,
  width,
  height,
  aspectRatio,
  objectFit = 'cover',
  placeholder = 'skeleton',
  placeholderColor = '#e5e7eb',
  showSkeleton = true,
  lazyLoad = false,
  rootMargin = '200px',
  className,
  containerClassName,
  priority,
  onLoadComplete,
  onLoadError,
  ...props
}: ImageProps) {
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);
  const [isInView, setIsInView] = useState(!lazyLoad || !hasIntersectionObserver);
  const containerRef = useRef<HTMLDivElement>(null);
 
  // Determine image source
  const imageSrc = hasError
    ? fallback
    : publicId
      ? buildCloudinaryUrl(publicId)
      : src || fallback;
 
  // Generate blur placeholder
  const numWidth = typeof width === 'number' ? width : parseInt(String(width), 10) || 300;
  const numHeight = typeof height === 'number' ? height : parseInt(String(height), 10) || 300;
 
  const blurDataURL =
    placeholder === 'blur'
      ? publicId
        ? buildCloudinaryBlurPlaceholder(publicId)
        : generateBlurPlaceholder(numWidth, numHeight, placeholderColor)
      : undefined;
 
  // Handle load
  const handleLoad = useCallback(() => {
    setIsLoading(false);
    onLoadComplete?.();
  }, [onLoadComplete]);
 
  // Handle error
  const handleError = useCallback(() => {
    setHasError(true);
    setIsLoading(false);
    onLoadError?.();
  }, [onLoadError]);
 
  // Lazy loading with IntersectionObserver
  useEffect(() => {
    if (!lazyLoad || !hasIntersectionObserver || isInView) return;

    const container = containerRef.current;
    if (!container) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsInView(true);
          observer.disconnect();
        }
      },
      { rootMargin, threshold: 0.1 }
    );

    observer.observe(container);
    return () => observer.disconnect();
  }, [lazyLoad, rootMargin, isInView]);
 
  // Determine if we should show placeholder
  const showPlaceholderState =
    (placeholder === 'skeleton' || showSkeleton) && isLoading;
 
  return (
    <div
      ref={containerRef}
      className={cn(
        'relative overflow-hidden',
        aspectRatio && aspectRatioClasses[aspectRatio],
        containerClassName
      )}
    >
      {/* Loading skeleton */}
      {showPlaceholderState && (
        <div
          className="absolute inset-0 bg-gray-200 dark:bg-gray-700 animate-pulse"
          aria-hidden="true"
        />
      )}
 
      {/* Only render image when in view (for lazy loading) */}
      {isInView && (
        <NextImage
          src={imageSrc}
          alt={alt}
          width={width}
          height={height}
          priority={priority}
          placeholder={placeholder === 'blur' && blurDataURL ? 'blur' : 'empty'}
          blurDataURL={blurDataURL}
          className={cn(
            'transition-opacity duration-300',
            isLoading ? 'opacity-0' : 'opacity-100',
            objectFitClasses[objectFit],
            className
          )}
          onLoad={handleLoad}
          onError={handleError}
          {...props}
        />
      )}
    </div>
  );
});
 
/**
 * HeroImage - Optimized for large hero/banner images
 */
export interface HeroImageProps extends Omit<ImageProps, 'priority' | 'aspectRatio'> {
  /** Hero aspect ratio */
  heroAspectRatio?: '16:9' | '21:9' | '4:3';
}
 
export const HeroImage = memo(function HeroImage({
  heroAspectRatio = '16:9',
  placeholder = 'blur',
  ...props
}: HeroImageProps) {
  return (
    // eslint-disable-next-line jsx-a11y/alt-text -- alt is passed via props spread
    <Image
      {...props}
      aspectRatio={heroAspectRatio}
      placeholder={placeholder}
      priority
    />
  );
});
 
/**
 * ThumbnailImage - Optimized for small thumbnails
 */
export interface ThumbnailImageProps extends Omit<ImageProps, 'width' | 'height'> {
  /** Thumbnail size in pixels */
  size?: number;
}
 
export const ThumbnailImage = memo(function ThumbnailImage({
  size = 80,
  showSkeleton = true,
  ...props
}: ThumbnailImageProps) {
  return (
    // eslint-disable-next-line jsx-a11y/alt-text -- alt is passed via props spread
    <Image {...props} width={size} height={size} showSkeleton={showSkeleton} />
  );
});
 
/**
 * CardImage - Optimized for card/grid layouts
 */
export interface CardImageProps extends Omit<ImageProps, 'width' | 'height'> {
  /** Card image size preset */
  size?: 'sm' | 'md' | 'lg';
}
 
const cardSizes = {
  sm: { width: 200, height: 200 },
  md: { width: 300, height: 300 },
  lg: { width: 400, height: 400 },
};
 
export const CardImage = memo(function CardImage({
  size = 'md',
  placeholder = 'blur',
  ...props
}: CardImageProps) {
  const dimensions = cardSizes[size];
  return (
    // eslint-disable-next-line jsx-a11y/alt-text -- alt is passed via props spread
    <Image
      {...props}
      width={dimensions.width}
      height={dimensions.height}
      placeholder={placeholder}
    />
  );
});
 
export default Image;