fix(cropper): make freeform cropper ultra-smooth and fluid with RAF, window pointer tracking, and zero layout thrashing

This commit is contained in:
2026-11-11 14:46:14 +05:30
parent 0b00b9d178
commit ed7115e785
+168 -137
View File
@@ -1,7 +1,7 @@
'use client';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Crop, RotateCcw, Maximize2, Sparkles, Check } from 'lucide-react';
import { Crop, RotateCcw } from 'lucide-react';
export interface CropRect {
x: number; // 0 to 100%
@@ -29,6 +29,10 @@ const RATIO_CONFIGS: Array<{ id: AspectRatioOption; label: string; ratio?: numbe
{ 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,
@@ -38,30 +42,42 @@ export function ImageCropper({
const [selectedRatio, setSelectedRatio] = useState<AspectRatioOption>('freeform');
const [crop, setCrop] = useState<CropRect>({ 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<CropRect>(crop);
cropRef.current = crop;
const containerRef = useRef<HTMLDivElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
const boundsRef = useRef<{ left: number; top: number; width: number; height: number }>({
left: 0,
top: 0,
width: 0,
height: 0,
});
// Drag interaction state
// 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<CropRect>({ x: 0, y: 0, width: 100, height: 100 });
const rafIdRef = useRef<number | null>(null);
// Reset crop to full
// 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]);
// Handle image load to initialize dimensions
// Image load handler
const handleImageLoaded = (e: React.SyntheticEvent<HTMLImageElement>) => {
const img = e.currentTarget;
setImageSize({ width: img.naturalWidth, height: img.naturalHeight });
};
// Adjust crop box to a specified aspect ratio while keeping it within bounds
// Adjust crop to a predefined aspect ratio
const applyAspectRatio = useCallback(
(ratioId: AspectRatioOption) => {
setSelectedRatio(ratioId);
@@ -86,127 +102,143 @@ export function ImageCropper({
const newY = (100 - newHeightPct) / 2;
const newCrop: CropRect = {
x: Math.max(0, Math.min(100, newX)),
y: Math.max(0, Math.min(100, newY)),
width: Math.max(10, Math.min(100, newWidthPct)),
height: Math.max(10, Math.min(100, newHeightPct)),
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]
);
// Dragging logic
// Silky smooth drag handler using cached bounds and continuous clamping
const handlePointerDown = (
e: React.PointerEvent<HTMLDivElement>,
mode: 'move' | 'nw' | 'ne' | 'se' | 'sw' | 'n' | 'e' | 's' | 'w'
) => {
if (disabled) return;
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 = { ...crop };
startCropRef.current = { ...cropRef.current };
setIsInteracting(true);
try {
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
} catch {}
};
const onWindowPointerMove = (ev: PointerEvent) => {
if (!dragModeRef.current) return;
ev.preventDefault();
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!dragModeRef.current || !containerRef.current || disabled) return;
const bounds = boundsRef.current;
if (bounds.width <= 0 || bounds.height <= 0) return;
const rect = containerRef.current.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
const deltaXPct = ((ev.clientX - startPosRef.current.clientX) / bounds.width) * 100;
const deltaYPct = ((ev.clientY - startPosRef.current.clientY) / bounds.height) * 100;
const deltaXPct = ((e.clientX - startPosRef.current.clientX) / rect.width) * 100;
const deltaYPct = ((e.clientY - startPosRef.current.clientY) / rect.height) * 100;
const start = startCropRef.current;
let newCrop = { ...start };
if (dragModeRef.current === 'move') {
let nextX = start.x + deltaXPct;
let nextY = start.y + deltaYPct;
nextX = Math.max(0, Math.min(100 - start.width, nextX));
nextY = Math.max(0, Math.min(100 - start.height, nextY));
newCrop.x = nextX;
newCrop.y = nextY;
} else {
// Handle corner and edge resizing
const start = startCropRef.current;
const mode = dragModeRef.current;
const minSize = 8; // min 8% size
const minSize = 6; // minimum 6% crop size
if (mode.includes('e')) {
newCrop.width = Math.max(minSize, Math.min(100 - start.x, start.width + deltaXPct));
}
if (mode.includes('s')) {
newCrop.height = Math.max(minSize, Math.min(100 - start.y, start.height + deltaYPct));
}
if (mode.includes('w')) {
const potentialW = start.width - deltaXPct;
if (potentialW >= minSize && start.x + deltaXPct >= 0) {
newCrop.x = start.x + deltaXPct;
newCrop.width = potentialW;
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);
}
}
if (mode.includes('n')) {
const potentialH = start.height - deltaYPct;
if (potentialH >= minSize && start.y + deltaYPct >= 0) {
newCrop.y = start.y + deltaYPct;
newCrop.height = potentialH;
// 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;
}
}
}
// Constrain aspect ratio if a fixed ratio is 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;
// height in % = (width% * imgAspect) / targetRatio
const constrainedHeight = (newCrop.width * imgAspect) / targetRatio;
if (newCrop.y + constrainedHeight <= 100) {
newCrop.height = constrainedHeight;
} else {
newCrop.height = 100 - newCrop.y;
newCrop.width = (newCrop.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);
});
};
setCrop(newCrop);
const isFull =
newCrop.x <= 1 &&
newCrop.y <= 1 &&
newCrop.width >= 98 &&
newCrop.height >= 98;
onCropChange?.(newCrop, isFull);
};
const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (dragModeRef.current) {
const onWindowPointerUp = () => {
dragModeRef.current = null;
try {
(e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
} catch {}
}
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
// Provide high-resolution canvas export blob function to parent (stable reference)
useEffect(() => {
if (!onExportReady) return;
const getCroppedBlob = async (): Promise<Blob | null> => {
const activeCrop = cropRef.current;
const isFull =
crop.x <= 0.5 &&
crop.y <= 0.5 &&
crop.width >= 99 &&
crop.height >= 99;
activeCrop.x <= 0.5 &&
activeCrop.y <= 0.5 &&
activeCrop.width >= 99 &&
activeCrop.height >= 99;
return new Promise<Blob | null>((resolve) => {
const img = new Image();
@@ -216,7 +248,6 @@ export function ImageCropper({
const naturalH = img.naturalHeight;
if (isFull) {
// Full image without crop clipping
const canvas = document.createElement('canvas');
canvas.width = naturalW;
canvas.height = naturalH;
@@ -227,10 +258,10 @@ export function ImageCropper({
return;
}
const pixelX = Math.max(0, Math.round((crop.x / 100) * naturalW));
const pixelY = Math.max(0, Math.round((crop.y / 100) * naturalH));
const pixelW = Math.min(naturalW - pixelX, Math.round((crop.width / 100) * naturalW));
const pixelH = Math.min(naturalH - pixelY, Math.round((crop.height / 100) * naturalH));
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;
@@ -247,7 +278,7 @@ export function ImageCropper({
};
onExportReady(getCroppedBlob);
}, [crop, imageUrl, onExportReady]);
}, [imageUrl, onExportReady]);
const isCropped = crop.x > 1 || crop.y > 1 || crop.width < 98 || crop.height < 98;
@@ -257,9 +288,9 @@ export function ImageCropper({
{/* Aspect Ratio Toolbar */}
<div className="flex flex-wrap items-center justify-between gap-2.5 p-2 rounded-2xl bg-paper-2 border border-rule">
<div className="flex items-center gap-1.5 overflow-x-auto no-scrollbar py-0.5">
<div className="flex items-center gap-1 px-2 text-xs font-semibold text-slate-700 shrink-0">
<div className="flex items-center gap-1.5 px-2 text-xs font-bold text-slate-800 shrink-0">
<Crop className="w-3.5 h-3.5 text-accent" />
<span className="hidden sm:inline">Aspect Ratio:</span>
<span className="hidden sm:inline">Framing & Aspect:</span>
</div>
{RATIO_CONFIGS.map((conf) => {
@@ -269,10 +300,10 @@ export function ImageCropper({
key={conf.id}
type="button"
onClick={() => applyAspectRatio(conf.id)}
className={`px-3 py-1.5 rounded-xl text-xs font-sans font-medium transition-all cursor-pointer whitespace-nowrap ${
className={`px-3 py-1.5 rounded-xl text-xs font-sans transition-colors cursor-pointer whitespace-nowrap ${
active
? 'bg-slate-900 text-white shadow-xs font-semibold'
: 'bg-white/80 hover:bg-white text-slate-700 border border-slate-200/80 hover:border-slate-300'
: 'bg-white hover:bg-slate-100 text-slate-700 border border-slate-200 hover:border-slate-300 font-medium'
}`}
>
{conf.label}
@@ -287,62 +318,52 @@ export function ImageCropper({
type="button"
onClick={handleResetCrop}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold text-rose-600 bg-rose-50 hover:bg-rose-100 border border-rose-200 transition-colors cursor-pointer shrink-0 ml-auto"
title="Reset to full image"
title="Reset to full original image"
>
<RotateCcw className="w-3 h-3" />
<span>Fit Full Image</span>
<span>Reset Crop</span>
</button>
)}
</div>
{/* Interactive Cropper Stage */}
<div
className="relative w-full aspect-[4/3] sm:aspect-[16/10] max-h-[540px] rounded-2xl overflow-hidden bg-slate-950/90 border border-rule flex items-center justify-center p-2 sm:p-4 touch-none"
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
>
{/* Constrained Image Wrapper matching exact image aspect ratio */}
<div className="relative w-full aspect-[4/3] sm:aspect-[16/10] max-h-[560px] rounded-2xl overflow-hidden bg-slate-950 border border-rule flex items-center justify-center p-2 sm:p-4 touch-none select-none">
{/* Constrained Image Wrapper */}
<div
ref={containerRef}
className="relative max-w-full max-h-full overflow-hidden shadow-2xl rounded-lg"
style={{
touchAction: 'none',
}}
style={{ touchAction: 'none' }}
>
{/* Base Image */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
ref={imgRef}
src={imageUrl}
alt="Source for cropping"
alt="Source photo for cropping"
onLoad={handleImageLoaded}
draggable={false}
className="max-h-[500px] w-auto max-w-full object-contain pointer-events-none block"
className="max-h-[520px] w-auto max-w-full object-contain pointer-events-none block select-none"
/>
{/* Semi-transparent Dimmed Outer Overlays */}
{/* Top Overlay */}
{/* Instantaneous Dimmed Overlays (transition-none for zero drag latency) */}
<div
className="absolute top-0 left-0 right-0 bg-black/60 pointer-events-none transition-all duration-75"
className="absolute top-0 left-0 right-0 bg-black/60 pointer-events-none transition-none"
style={{ height: `${crop.y}%` }}
/>
{/* Bottom Overlay */}
<div
className="absolute bottom-0 left-0 right-0 bg-black/60 pointer-events-none transition-all duration-75"
className="absolute bottom-0 left-0 right-0 bg-black/60 pointer-events-none transition-none"
style={{ height: `${100 - (crop.y + crop.height)}%` }}
/>
{/* Left Overlay */}
<div
className="absolute left-0 bg-black/60 pointer-events-none transition-all duration-75"
className="absolute left-0 bg-black/60 pointer-events-none transition-none"
style={{
top: `${crop.y}%`,
height: `${crop.height}%`,
width: `${crop.x}%`,
}}
/>
{/* Right Overlay */}
<div
className="absolute right-0 bg-black/60 pointer-events-none transition-all duration-75"
className="absolute right-0 bg-black/60 pointer-events-none transition-none"
style={{
top: `${crop.y}%`,
height: `${crop.height}%`,
@@ -350,10 +371,12 @@ export function ImageCropper({
}}
/>
{/* Active Crop Box */}
{/* Active Fluid Crop Box */}
<div
onPointerDown={(e) => handlePointerDown(e, 'move')}
className="absolute border border-white/90 shadow-[0_0_0_1px_rgba(0,0,0,0.6)] cursor-move transition-[border-color] hover:border-white"
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}%`,
@@ -362,7 +385,7 @@ export function ImageCropper({
touchAction: 'none',
}}
>
{/* Rule of Thirds Grid Lines (Subtle Framing Guides) */}
{/* Rule of Thirds Viewfinder Grid */}
<div className="absolute inset-0 pointer-events-none grid grid-cols-3 grid-rows-3 opacity-30">
<div className="border-r border-b border-white" />
<div className="border-r border-b border-white" />
@@ -375,40 +398,48 @@ export function ImageCropper({
<div />
</div>
{/* Corner Resize Handles */}
{/* Corner L-Bracket Handles with Large Touch Hit Zones */}
{/* Top-Left */}
<div
onPointerDown={(e) => handlePointerDown(e, 'nw')}
className="absolute -top-2 -left-2 w-4 h-4 rounded-sm bg-white border-2 border-slate-900 shadow-md cursor-nwse-resize z-20 touch-none"
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 */}
<div
onPointerDown={(e) => handlePointerDown(e, 'ne')}
className="absolute -top-2 -right-2 w-4 h-4 rounded-sm bg-white border-2 border-slate-900 shadow-md cursor-nesw-resize z-20 touch-none"
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 */}
<div
onPointerDown={(e) => handlePointerDown(e, 'se')}
className="absolute -bottom-2 -right-2 w-4 h-4 rounded-sm bg-white border-2 border-slate-900 shadow-md cursor-nwse-resize z-20 touch-none"
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 */}
<div
onPointerDown={(e) => handlePointerDown(e, 'sw')}
className="absolute -bottom-2 -left-2 w-4 h-4 rounded-sm bg-white border-2 border-slate-900 shadow-md cursor-nesw-resize z-20 touch-none"
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 Resize Handles */}
{/* Edge Midpoint Bars with Generous Drag Zones */}
{/* Top */}
<div
onPointerDown={(e) => handlePointerDown(e, 'n')}
className="absolute -top-1.5 left-1/2 -translate-x-1/2 w-6 h-2 rounded-full bg-white border border-slate-900 shadow-xs cursor-ns-resize z-10 touch-none"
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 */}
<div
onPointerDown={(e) => handlePointerDown(e, 's')}
className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-6 h-2 rounded-full bg-white border border-slate-900 shadow-xs cursor-ns-resize z-10 touch-none"
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 */}
<div
onPointerDown={(e) => handlePointerDown(e, 'w')}
className="absolute top-1/2 -left-1.5 -translate-y-1/2 w-2 h-6 rounded-full bg-white border border-slate-900 shadow-xs cursor-ew-resize z-10 touch-none"
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 */}
<div
onPointerDown={(e) => handlePointerDown(e, 'e')}
className="absolute top-1/2 -right-1.5 -translate-y-1/2 w-2 h-6 rounded-full bg-white border border-slate-900 shadow-xs cursor-ew-resize z-10 touch-none"
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-['']"
/>
</div>
</div>