All files / src/components/ui ResponsiveImage.tsx

100% Statements 21/21
88.88% Branches 16/18
100% Functions 7/7
100% Lines 20/20

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    8x 8x 8x                                     144x                   20x     134x         8x                     31x   31x 1x 1x                         31x         31x       31x 217x       31x 21x                                       10x 10x           10x                                                                                            
import { memo, useCallback, useMemo, useRef } from "react";
 
const DEFAULT_SIZES = "100vw";
const DEFAULT_QUALITY = 80;
const BREAKPOINTS = [320, 480, 640, 800, 1024, 1280, 1536] as const;
 
interface ResponsiveImageProps {
	storageKey: string;
	alt: string;
	width: number;
	height: number;
	sizes?: string;
	quality?: number;
	loading?: "lazy" | "eager";
	fetchPriority?: "high" | "low" | "auto";
	className?: string;
}
 
function buildTransformUrl(
	base: string,
	storageKey: string,
	opts: { w: number; f: string; q: number },
): string {
	return `${base}/cdn-cgi/image/w=${opts.w},f=${opts.f},q=${opts.q}/${storageKey}`;
}
 
function buildSrcset(
	base: string,
	storageKey: string,
	breakpoints: number[],
	format: string,
	quality: number,
): string {
	return breakpoints
		.map(
			(bp) =>
				`${buildTransformUrl(base, storageKey, { w: bp, f: format, q: quality })} ${bp}w`,
		)
		.join(", ");
}
 
export const ResponsiveImage = memo(function ResponsiveImage({
	storageKey,
	alt,
	width,
	height,
	sizes = DEFAULT_SIZES,
	quality = DEFAULT_QUALITY,
	loading = "lazy",
	fetchPriority,
	className,
}: ResponsiveImageProps) {
	const containerRef = useRef<HTMLDivElement>(null);
 
	const handleLoad = useCallback(() => {
		Eif (containerRef.current) {
			containerRef.current.style.backgroundImage = "";
		}
	}, []);
 
	// Resolution order:
	//   1. VITE_IMAGE_URL — set in deployed envs (dev/preview/prod) to the
	//      Cloudflare-CDN-fronted bucket origin (e.g. https://images-dev...).
	//   2. ${VITE_API_URL}/api/images — local dev fallback. The API serves
	//      R2 objects directly at /api/images/:path. Without this fallback,
	//      `bun run dev` (no --mode flag) leaves imageBase empty and every
	//      uploaded preview renders a broken /cdn-cgi/... URL.
	//   3. /api/images — same-origin last resort.
	const imageBase =
		import.meta.env.VITE_IMAGE_URL ||
		`${import.meta.env.VITE_API_URL || ""}/api/images`;
	// Local mode strips Cloudflare cdn-cgi transforms (those only work on the
	// CDN-fronted host). Detect localhost OR a same-origin /api/images path.
	const isLocal =
		imageBase.includes("localhost") ||
		imageBase.startsWith("/api/images") ||
		imageBase.includes("127.0.0.1");
 
	const activeBreakpoints = useMemo(
		() => BREAKPOINTS.filter((bp) => bp <= width * 2),
		[width],
	);
 
	if (isLocal) {
		return (
			<div
				ref={containerRef}
				style={{
					aspectRatio: `${width} / ${height}`,
				}}
			>
				<img
					src={`${imageBase}/${storageKey}`}
					alt={alt}
					width={width}
					height={height}
					loading={loading}
					{...(fetchPriority ? { fetchPriority } : {})}
					className={className}
				/>
			</div>
		);
	}
 
	const lqipUrl = `${imageBase}/cdn-cgi/image/w=16,q=30,f=webp/${storageKey}`;
	const fallbackSrc = buildTransformUrl(imageBase, storageKey, {
		w: width,
		f: "auto",
		q: quality,
	});
 
	return (
		<div
			ref={containerRef}
			style={{
				backgroundImage: `url(${lqipUrl})`,
				backgroundSize: "cover",
				aspectRatio: `${width} / ${height}`,
			}}
		>
			<picture>
				<source
					type="image/avif"
					srcSet={buildSrcset(
						imageBase,
						storageKey,
						activeBreakpoints,
						"avif",
						quality,
					)}
					sizes={sizes}
				/>
				<source
					type="image/webp"
					srcSet={buildSrcset(
						imageBase,
						storageKey,
						activeBreakpoints,
						"webp",
						quality,
					)}
					sizes={sizes}
				/>
				<img
					src={fallbackSrc}
					alt={alt}
					width={width}
					height={height}
					loading={loading}
					{...(fetchPriority ? { fetchPriority } : {})}
					className={className}
					onLoad={handleLoad}
				/>
			</picture>
		</div>
	);
});