'use client'; import React, { useState, useRef, useEffect, useCallback } from 'react'; import { Crop, RotateCcw } from 'lucide-react'; export interface CropRect { x: number; // 0 to 100% y: number; // 0 to 100% width: number; // 0 to 100% height: number; // 0 to 100% } interface ImageCropperProps { imageUrl: string; onCropChange?: (crop: CropRect, isFullImage: boolean) => void; onExportReady?: (getCroppedBlob: () => Promise) => void; disabled?: boolean; } type AspectRatioOption = 'freeform' | '1:1' | '4:5' | '16:9' | '9:16' | '4:3' | '3:4'; const RATIO_CONFIGS: Array<{ id: AspectRatioOption; label: string; ratio?: number }> = [ { id: 'freeform', label: 'Freeform' }, { id: '1:1', label: '1:1 Square', ratio: 1 / 1 }, { id: '4:5', label: '4:5 Portrait', ratio: 4 / 5 }, { id: '16:9', label: '16:9 Wide', ratio: 16 / 9 }, { id: '9:16', label: '9:16 Story', ratio: 9 / 16 }, { id: '4:3', label: '4:3 Photo', ratio: 4 / 3 }, { id: '3:4', label: '3:4 Classic', ratio: 3 / 4 }, ]; function clamp(min: number, val: number, max: number): number { return Math.max(min, Math.min(val, max)); } export function ImageCropper({ imageUrl, onCropChange, onExportReady, disabled = false, }: ImageCropperProps) { const [selectedRatio, setSelectedRatio] = useState('freeform'); const [crop, setCrop] = useState({ x: 0, y: 0, width: 100, height: 100 }); const [imageSize, setImageSize] = useState<{ width: number; height: number }>({ width: 0, height: 0 }); const [isInteracting, setIsInteracting] = useState(false); // Sync ref to avoid closure staleness and eliminate state re-registration churn const cropRef = useRef(crop); cropRef.current = crop; const containerRef = useRef(null); const boundsRef = useRef<{ left: number; top: number; width: number; height: number }>({ left: 0, top: 0, width: 0, height: 0, }); // Drag tracking state const dragModeRef = useRef<'move' | 'nw' | 'ne' | 'se' | 'sw' | 'n' | 'e' | 's' | 'w' | null>(null); const startPosRef = useRef<{ clientX: number; clientY: number }>({ clientX: 0, clientY: 0 }); const startCropRef = useRef({ x: 0, y: 0, width: 100, height: 100 }); const rafIdRef = useRef(null); // Reset to 100% full image const handleResetCrop = useCallback(() => { const full: CropRect = { x: 0, y: 0, width: 100, height: 100 }; setCrop(full); cropRef.current = full; setSelectedRatio('freeform'); onCropChange?.(full, true); }, [onCropChange]); // Image load handler const handleImageLoaded = (e: React.SyntheticEvent) => { const img = e.currentTarget; setImageSize({ width: img.naturalWidth, height: img.naturalHeight }); }; // Adjust crop to a predefined aspect ratio const applyAspectRatio = useCallback( (ratioId: AspectRatioOption) => { setSelectedRatio(ratioId); const conf = RATIO_CONFIGS.find((r) => r.id === ratioId); if (!conf?.ratio || !imageSize.width || !imageSize.height) { return; } const targetRatio = conf.ratio; const imgAspect = imageSize.width / imageSize.height; let newWidthPct = 90; let newHeightPct = (newWidthPct * imgAspect) / targetRatio; if (newHeightPct > 90) { newHeightPct = 90; newWidthPct = (newHeightPct * targetRatio) / imgAspect; } const newX = (100 - newWidthPct) / 2; const newY = (100 - newHeightPct) / 2; const newCrop: CropRect = { x: clamp(0, newX, 100), y: clamp(0, newY, 100), width: clamp(8, newWidthPct, 100), height: clamp(8, newHeightPct, 100), }; setCrop(newCrop); cropRef.current = newCrop; onCropChange?.(newCrop, false); }, [imageSize, onCropChange] ); // Silky smooth drag handler using cached bounds and continuous clamping const handlePointerDown = ( e: React.PointerEvent, mode: 'move' | 'nw' | 'ne' | 'se' | 'sw' | 'n' | 'e' | 's' | 'w' ) => { if (disabled || !containerRef.current) return; e.preventDefault(); e.stopPropagation(); // Cache element bounding rect ONCE at drag start to eliminate layout reflows during move const rect = containerRef.current.getBoundingClientRect(); boundsRef.current = { left: rect.left, top: rect.top, width: rect.width, height: rect.height, }; dragModeRef.current = mode; startPosRef.current = { clientX: e.clientX, clientY: e.clientY }; startCropRef.current = { ...cropRef.current }; setIsInteracting(true); const onWindowPointerMove = (ev: PointerEvent) => { if (!dragModeRef.current) return; ev.preventDefault(); const bounds = boundsRef.current; if (bounds.width <= 0 || bounds.height <= 0) return; const deltaXPct = ((ev.clientX - startPosRef.current.clientX) / bounds.width) * 100; const deltaYPct = ((ev.clientY - startPosRef.current.clientY) / bounds.height) * 100; const start = startCropRef.current; const mode = dragModeRef.current; const minSize = 6; // minimum 6% crop size let nextCrop = { ...start }; if (mode === 'move') { const maxX = 100 - start.width; const maxY = 100 - start.height; nextCrop.x = clamp(0, start.x + deltaXPct, maxX); nextCrop.y = clamp(0, start.y + deltaYPct, maxY); } else { // Freeform / Aspect Resize // Horizontal adjustment if (mode.includes('w')) { const maxLeft = start.x + start.width - minSize; const newLeft = clamp(0, start.x + deltaXPct, maxLeft); nextCrop.x = newLeft; nextCrop.width = (start.x + start.width) - newLeft; } else if (mode.includes('e')) { const maxW = 100 - start.x; nextCrop.width = clamp(minSize, start.width + deltaXPct, maxW); } // Vertical adjustment if (mode.includes('n')) { const maxTop = start.y + start.height - minSize; const newTop = clamp(0, start.y + deltaYPct, maxTop); nextCrop.y = newTop; nextCrop.height = (start.y + start.height) - newTop; } else if (mode.includes('s')) { const maxH = 100 - start.y; nextCrop.height = clamp(minSize, start.height + deltaYPct, maxH); } // Proportional constraint if non-freeform ratio selected const conf = RATIO_CONFIGS.find((r) => r.id === selectedRatio); if (conf?.ratio && imageSize.width && imageSize.height) { const imgAspect = imageSize.width / imageSize.height; const targetRatio = conf.ratio; // target height = (width% * imgAspect) / targetRatio let constrainedH = (nextCrop.width * imgAspect) / targetRatio; if (nextCrop.y + constrainedH <= 100) { nextCrop.height = constrainedH; } else { nextCrop.height = 100 - nextCrop.y; nextCrop.width = (nextCrop.height * targetRatio) / imgAspect; } } } // Schedule update via requestAnimationFrame for 60/120fps fluid response if (rafIdRef.current) cancelAnimationFrame(rafIdRef.current); rafIdRef.current = requestAnimationFrame(() => { cropRef.current = nextCrop; setCrop(nextCrop); }); }; const onWindowPointerUp = () => { dragModeRef.current = null; setIsInteracting(false); window.removeEventListener('pointermove', onWindowPointerMove); window.removeEventListener('pointerup', onWindowPointerUp); window.removeEventListener('pointercancel', onWindowPointerUp); const finalCrop = cropRef.current; const isFull = finalCrop.x <= 1 && finalCrop.y <= 1 && finalCrop.width >= 98 && finalCrop.height >= 98; onCropChange?.(finalCrop, isFull); }; window.addEventListener('pointermove', onWindowPointerMove, { passive: false }); window.addEventListener('pointerup', onWindowPointerUp); window.addEventListener('pointercancel', onWindowPointerUp); }; // Provide high-resolution canvas export blob function to parent (stable reference) useEffect(() => { if (!onExportReady) return; const getCroppedBlob = async (): Promise => { const activeCrop = cropRef.current; const isFull = activeCrop.x <= 0.5 && activeCrop.y <= 0.5 && activeCrop.width >= 99 && activeCrop.height >= 99; return new Promise((resolve) => { const img = new Image(); img.crossOrigin = 'anonymous'; img.onload = () => { const naturalW = img.naturalWidth; const naturalH = img.naturalHeight; if (isFull) { const canvas = document.createElement('canvas'); canvas.width = naturalW; canvas.height = naturalH; const ctx = canvas.getContext('2d'); if (!ctx) return resolve(null); ctx.drawImage(img, 0, 0); canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.95); return; } const pixelX = clamp(0, Math.round((activeCrop.x / 100) * naturalW), naturalW - 1); const pixelY = clamp(0, Math.round((activeCrop.y / 100) * naturalH), naturalH - 1); const pixelW = clamp(1, Math.round((activeCrop.width / 100) * naturalW), naturalW - pixelX); const pixelH = clamp(1, Math.round((activeCrop.height / 100) * naturalH), naturalH - pixelY); const canvas = document.createElement('canvas'); canvas.width = pixelW; canvas.height = pixelH; const ctx = canvas.getContext('2d'); if (!ctx) return resolve(null); ctx.drawImage(img, pixelX, pixelY, pixelW, pixelH, 0, 0, pixelW, pixelH); canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.95); }; img.onerror = () => resolve(null); img.src = imageUrl; }); }; onExportReady(getCroppedBlob); }, [imageUrl, onExportReady]); const isCropped = crop.x > 1 || crop.y > 1 || crop.width < 98 || crop.height < 98; return (
{/* Aspect Ratio Toolbar */}
Framing & Aspect:
{RATIO_CONFIGS.map((conf) => { const active = selectedRatio === conf.id; return ( ); })}
{/* Reset / Fit Full Button */} {isCropped && ( )}
{/* Interactive Cropper Stage */}
{/* Constrained Image Wrapper */}
{/* Base Image */} {/* eslint-disable-next-line @next/next/no-img-element */} Source photo for cropping {/* Instantaneous Dimmed Overlays (transition-none for zero drag latency) */}
{/* Active Fluid Crop Box */}
handlePointerDown(e, 'move')} className={`absolute border border-white cursor-move shadow-[0_0_0_1px_rgba(0,0,0,0.7)] transition-none ${ isInteracting ? 'ring-1 ring-accent/60' : '' }`} style={{ top: `${crop.y}%`, left: `${crop.x}%`, width: `${crop.width}%`, height: `${crop.height}%`, touchAction: 'none', }} > {/* Rule of Thirds Viewfinder Grid */}
{/* Corner L-Bracket Handles with Large Touch Hit Zones */} {/* Top-Left */}
handlePointerDown(e, 'nw')} className="absolute -top-1.5 -left-1.5 w-4 h-4 border-t-3 border-l-3 border-white shadow-md cursor-nwse-resize z-20 touch-none after:absolute after:-inset-3 after:content-['']" /> {/* Top-Right */}
handlePointerDown(e, 'ne')} className="absolute -top-1.5 -right-1.5 w-4 h-4 border-t-3 border-r-3 border-white shadow-md cursor-nesw-resize z-20 touch-none after:absolute after:-inset-3 after:content-['']" /> {/* Bottom-Right */}
handlePointerDown(e, 'se')} className="absolute -bottom-1.5 -right-1.5 w-4 h-4 border-b-3 border-r-3 border-white shadow-md cursor-nwse-resize z-20 touch-none after:absolute after:-inset-3 after:content-['']" /> {/* Bottom-Left */}
handlePointerDown(e, 'sw')} className="absolute -bottom-1.5 -left-1.5 w-4 h-4 border-b-3 border-l-3 border-white shadow-md cursor-nesw-resize z-20 touch-none after:absolute after:-inset-3 after:content-['']" /> {/* Edge Midpoint Bars with Generous Drag Zones */} {/* Top */}
handlePointerDown(e, 'n')} className="absolute -top-1 left-1/2 -translate-x-1/2 w-8 h-2 rounded-full bg-white/90 shadow-sm cursor-ns-resize z-10 touch-none after:absolute after:-inset-2 after:content-['']" /> {/* Bottom */}
handlePointerDown(e, 's')} className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-8 h-2 rounded-full bg-white/90 shadow-sm cursor-ns-resize z-10 touch-none after:absolute after:-inset-2 after:content-['']" /> {/* Left */}
handlePointerDown(e, 'w')} className="absolute top-1/2 -left-1 -translate-y-1/2 w-2 h-8 rounded-full bg-white/90 shadow-sm cursor-ew-resize z-10 touch-none after:absolute after:-inset-2 after:content-['']" /> {/* Right */}
handlePointerDown(e, 'e')} className="absolute top-1/2 -right-1 -translate-y-1/2 w-2 h-8 rounded-full bg-white/90 shadow-sm cursor-ew-resize z-10 touch-none after:absolute after:-inset-2 after:content-['']" />
); }