Files
webb/src/components/tools/ImageCropper.tsx
T

420 lines
16 KiB
TypeScript
Raw Normal View History

'use client';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Crop, RotateCcw, Maximize2, Sparkles, Check } 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 },
];
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 containerRef = useRef<HTMLDivElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
// Drag interaction 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 });
// Reset crop to full
const handleResetCrop = useCallback(() => {
const full: CropRect = { x: 0, y: 0, width: 100, height: 100 };
setCrop(full);
setSelectedRatio('freeform');
onCropChange?.(full, true);
}, [onCropChange]);
// Handle image load to initialize dimensions
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
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: 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)),
};
setCrop(newCrop);
onCropChange?.(newCrop, false);
},
[imageSize, onCropChange]
);
// Dragging logic
const handlePointerDown = (
e: React.PointerEvent<HTMLDivElement>,
mode: 'move' | 'nw' | 'ne' | 'se' | 'sw' | 'n' | 'e' | 's' | 'w'
) => {
if (disabled) return;
e.preventDefault();
e.stopPropagation();
dragModeRef.current = mode;
startPosRef.current = { clientX: e.clientX, clientY: e.clientY };
startCropRef.current = { ...crop };
try {
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
} catch {}
};
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!dragModeRef.current || !containerRef.current || disabled) return;
const rect = containerRef.current.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
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 mode = dragModeRef.current;
const minSize = 8; // min 8% 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;
}
}
if (mode.includes('n')) {
const potentialH = start.height - deltaYPct;
if (potentialH >= minSize && start.y + deltaYPct >= 0) {
newCrop.y = start.y + deltaYPct;
newCrop.height = potentialH;
}
}
// 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;
}
}
}
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) {
dragModeRef.current = null;
try {
(e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
} catch {}
}
};
// Provide high-resolution canvas export blob function to parent
useEffect(() => {
if (!onExportReady) return;
const getCroppedBlob = async (): Promise<Blob | null> => {
const isFull =
crop.x <= 0.5 &&
crop.y <= 0.5 &&
crop.width >= 99 &&
crop.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) {
// Full image without crop clipping
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 = 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 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);
}, [crop, 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 px-2 text-xs font-semibold text-slate-700 shrink-0">
<Crop className="w-3.5 h-3.5 text-accent" />
<span className="hidden sm:inline">Aspect Ratio:</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 font-medium transition-all 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'
}`}
>
{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 image"
>
<RotateCcw className="w-3 h-3" />
<span>Fit Full Image</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
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
ref={imgRef}
src={imageUrl}
alt="Source for cropping"
onLoad={handleImageLoaded}
draggable={false}
className="max-h-[500px] w-auto max-w-full object-contain pointer-events-none block"
/>
{/* Semi-transparent Dimmed Outer Overlays */}
{/* Top Overlay */}
<div
className="absolute top-0 left-0 right-0 bg-black/60 pointer-events-none transition-all duration-75"
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"
style={{ height: `${100 - (crop.y + crop.height)}%` }}
/>
{/* Left Overlay */}
<div
className="absolute left-0 bg-black/60 pointer-events-none transition-all duration-75"
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"
style={{
top: `${crop.y}%`,
height: `${crop.height}%`,
width: `${100 - (crop.x + crop.width)}%`,
}}
/>
{/* Active 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"
style={{
top: `${crop.y}%`,
left: `${crop.x}%`,
width: `${crop.width}%`,
height: `${crop.height}%`,
touchAction: 'none',
}}
>
{/* Rule of Thirds Grid Lines (Subtle Framing Guides) */}
<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 Resize Handles */}
<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"
/>
<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"
/>
<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"
/>
<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"
/>
{/* Edge Midpoint Resize Handles */}
<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"
/>
<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"
/>
<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"
/>
<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"
/>
</div>
</div>
</div>
</div>
);
}