All files / src/components/blogs ImageCropper.tsx

100% Statements 53/53
100% Branches 9/9
100% Functions 16/16
100% Lines 47/47

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                                      36x 36x 36x 36x 36x   36x 5x     36x 6x 4x 4x 4x 1x   4x       36x                                           2x                   2x             1x               4x                                                           4x 3x 3x 3x   2x 2x 2x     2x 2x   2x 2x   2x 2x 2x 2x     2x 2x 2x 2x   2x 2x   2x               4x 4x 4x 4x 4x 4x      
import { useState, useCallback } from "react";
import Cropper from "react-easy-crop";
import type { Area } from "react-easy-crop";
import { RotateCw, ZoomIn, ZoomOut } from "lucide-react";
import { Button } from "../ui/button";
 
interface ImageCropperProps {
	imageSrc: string;
	onComplete: (croppedBlob: Blob) => void;
	onCancel: () => void;
	aspectRatio?: number;
}
 
export function ImageCropper({
	imageSrc,
	onComplete,
	onCancel,
	aspectRatio = 16 / 9,
}: ImageCropperProps) {
	const [crop, setCrop] = useState({ x: 0, y: 0 });
	const [zoom, setZoom] = useState(1);
	const [rotation, setRotation] = useState(0);
	const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
	const [processing, setProcessing] = useState(false);
 
	const onCropComplete = useCallback((_: Area, croppedPixels: Area) => {
		setCroppedAreaPixels(croppedPixels);
	}, []);
 
	const handleConfirm = async () => {
		if (!croppedAreaPixels) return;
		setProcessing(true);
		try {
			const blob = await getCroppedImage(imageSrc, croppedAreaPixels, rotation);
			onComplete(blob);
		} finally {
			setProcessing(false);
		}
	};
 
	return (
		<div className="space-y-4">
			<div className="relative w-full h-80 bg-black rounded-lg overflow-hidden">
				<Cropper
					image={imageSrc}
					crop={crop}
					zoom={zoom}
					rotation={rotation}
					aspect={aspectRatio}
					onCropChange={setCrop}
					onZoomChange={setZoom}
					onRotationChange={setRotation}
					onCropComplete={onCropComplete}
				/>
			</div>
 
			<div className="flex items-center justify-between">
				<div className="flex items-center gap-2">
					<Button
						type="button"
						variant="outline"
						size="sm"
						onClick={() => setZoom((z) => Math.max(1, z - 0.2))}
					>
						<ZoomOut className="h-4 w-4" />
					</Button>
					<input
						type="range"
						min={1}
						max={3}
						step={0.1}
						value={zoom}
						onChange={(e) => setZoom(Number(e.target.value))}
						className="w-24 accent-primary-500"
					/>
					<Button
						type="button"
						variant="outline"
						size="sm"
						onClick={() => setZoom((z) => Math.min(3, z + 0.2))}
					>
						<ZoomIn className="h-4 w-4" />
					</Button>
					<Button
						type="button"
						variant="outline"
						size="sm"
						onClick={() => setRotation((r) => (r + 90) % 360)}
					>
						<RotateCw className="h-4 w-4" />
					</Button>
				</div>
 
				<div className="flex items-center gap-2">
					<Button type="button" variant="outline" size="sm" onClick={onCancel}>
						Cancel
					</Button>
					<Button
						type="button"
						size="sm"
						onClick={handleConfirm}
						disabled={processing}
					>
						{processing ? "Processing..." : "Apply"}
					</Button>
				</div>
			</div>
		</div>
	);
}
 
// Canvas helper: crop + rotate an image and return a Blob
async function getCroppedImage(
	src: string,
	crop: Area,
	rotation: number,
): Promise<Blob> {
	const image = await loadImage(src);
	const canvas = document.createElement("canvas");
	const ctx = canvas.getContext("2d");
	if (!ctx) throw new Error("Canvas context not available");
 
	const radians = (rotation * Math.PI) / 180;
	const sin = Math.abs(Math.sin(radians));
	const cos = Math.abs(Math.cos(radians));
 
	// Size of the rotated bounding box
	const bBoxWidth = image.width * cos + image.height * sin;
	const bBoxHeight = image.width * sin + image.height * cos;
 
	canvas.width = bBoxWidth;
	canvas.height = bBoxHeight;
 
	ctx.translate(bBoxWidth / 2, bBoxHeight / 2);
	ctx.rotate(radians);
	ctx.translate(-image.width / 2, -image.height / 2);
	ctx.drawImage(image, 0, 0);
 
	// Extract the cropped area
	const data = ctx.getImageData(crop.x, crop.y, crop.width, crop.height);
	canvas.width = crop.width;
	canvas.height = crop.height;
	ctx.putImageData(data, 0, 0);
 
	return new Promise((resolve, reject) => {
		canvas.toBlob(
			(blob) =>
				blob ? resolve(blob) : reject(new Error("Canvas toBlob failed")),
			"image/jpeg",
			0.92,
		);
	});
}
 
function loadImage(src: string): Promise<HTMLImageElement> {
	return new Promise((resolve, reject) => {
		const img = new Image();
		img.crossOrigin = "anonymous";
		img.onload = () => resolve(img);
		img.onerror = reject;
		img.src = src;
	});
}