451 lines
18 KiB
TypeScript
451 lines
18 KiB
TypeScript
'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<Blob | null>) => 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<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 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<CropRect>({ x: 0, y: 0, width: 100, height: 100 });
|
|
const rafIdRef = useRef<number | null>(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<HTMLImageElement>) => {
|
|
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<HTMLDivElement>,
|
|
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<Blob | null> => {
|
|
const activeCrop = cropRef.current;
|
|
const isFull =
|
|
activeCrop.x <= 0.5 &&
|
|
activeCrop.y <= 0.5 &&
|
|
activeCrop.width >= 99 &&
|
|
activeCrop.height >= 99;
|
|
|
|
return new Promise<Blob | null>((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 (
|
|
<div className="space-y-3.5 select-none">
|
|
|
|
{/* 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.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">Framing & Aspect:</span>
|
|
</div>
|
|
|
|
{RATIO_CONFIGS.map((conf) => {
|
|
const active = selectedRatio === conf.id;
|
|
return (
|
|
<button
|
|
key={conf.id}
|
|
type="button"
|
|
onClick={() => applyAspectRatio(conf.id)}
|
|
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 hover:bg-slate-100 text-slate-700 border border-slate-200 hover:border-slate-300 font-medium'
|
|
}`}
|
|
>
|
|
{conf.label}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
{/* Reset / Fit Full Button */}
|
|
{isCropped && (
|
|
<button
|
|
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 original image"
|
|
>
|
|
<RotateCcw className="w-3 h-3" />
|
|
<span>Reset Crop</span>
|
|
</button>
|
|
)}
|
|
</div>
|
|
|
|
{/* Interactive Cropper Stage */}
|
|
<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' }}
|
|
>
|
|
{/* Base Image */}
|
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
|
<img
|
|
src={imageUrl}
|
|
alt="Source photo for cropping"
|
|
onLoad={handleImageLoaded}
|
|
draggable={false}
|
|
className="max-h-[520px] w-auto max-w-full object-contain pointer-events-none block select-none"
|
|
/>
|
|
|
|
{/* 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-none"
|
|
style={{ height: `${crop.y}%` }}
|
|
/>
|
|
<div
|
|
className="absolute bottom-0 left-0 right-0 bg-black/60 pointer-events-none transition-none"
|
|
style={{ height: `${100 - (crop.y + crop.height)}%` }}
|
|
/>
|
|
<div
|
|
className="absolute left-0 bg-black/60 pointer-events-none transition-none"
|
|
style={{
|
|
top: `${crop.y}%`,
|
|
height: `${crop.height}%`,
|
|
width: `${crop.x}%`,
|
|
}}
|
|
/>
|
|
<div
|
|
className="absolute right-0 bg-black/60 pointer-events-none transition-none"
|
|
style={{
|
|
top: `${crop.y}%`,
|
|
height: `${crop.height}%`,
|
|
width: `${100 - (crop.x + crop.width)}%`,
|
|
}}
|
|
/>
|
|
|
|
{/* Active Fluid Crop Box */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<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" />
|
|
<div className="border-b border-white" />
|
|
<div className="border-r border-b border-white" />
|
|
<div className="border-r border-b border-white" />
|
|
<div className="border-b border-white" />
|
|
<div className="border-r border-white" />
|
|
<div className="border-r border-white" />
|
|
<div />
|
|
</div>
|
|
|
|
{/* Corner L-Bracket Handles with Large Touch Hit Zones */}
|
|
{/* Top-Left */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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 */}
|
|
<div
|
|
onPointerDown={(e) => 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-['']"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
);
|
|
}
|