"use client";/* ───────────────────────────────────────────────────────── * IMAGE CROP: frame it, straighten it, get exact pixels back * * A fixed window over the photo, the photo moving under it: drag * to place it, wheel or pinch to zoom, pick an aspect and the * window reshapes. Straighten with the dial and the photo turns * under the window while zooming itself just enough that no * corner ever shows empty. Every change reports the crop in the * image's own pixels; cropImage() turns that into a Blob. * ───────────────────────────────────────────────────────── */import * as React from "react";import { RotateCcw, RotateCw } from "lucide-react";import { createSpring, projectInertia, rubberBand, type Spring } from "./ui-interaction-motion";export interface CropArea { /** Top-left of the crop in the image's own pixels (exact when rotation is 0). */ x: number; y: number; width: number; height: number; /** Degrees clockwise the image is turned under the crop, quarter turns included. */ rotation: number; /** The crop's centre in the image's own pixels, before rotation. */ centerX: number; centerY: number;}export interface CropAspect { label: string; /** Width over height, or null for the image's own shape. */ value: number | null;}export interface ImageCropProps { src: string; alt: string; aspects?: CropAspect[]; /** Index into aspects to start with. */ defaultAspect?: number; /** Called with the crop each time a change settles (and once the image has loaded). */ onChange?: (area: CropArea) => void; crossOrigin?: "anonymous" | "use-credentials"; maxZoom?: number; labels?: { straighten?: string; rotateLeft?: string; rotateRight?: string; reset?: string; frame?: string }; className?: string;}const ASPECTS: CropAspect[] = [ { label: "Original", value: null }, { label: "1:1", value: 1 }, { label: "4:5", value: 4 / 5 }, { label: "16:9", value: 16 / 9 },];const SNAP = { stiffness: 380, damping: 38 };const DEG = Math.PI / 180;const TICK = 6; // px per degree on the dial/** The smallest scale at which the image, turned by theta, still covers a W × H window. */function coverScale(w: number, h: number, W: number, H: number, theta: number) { const c = Math.abs(Math.cos(theta)); const s = Math.abs(Math.sin(theta)); return Math.max((W * c + H * s) / w, (W * s + H * c) / h);}/** How far the window's centre may sit from the image's centre, in the image's own turned frame. */function slack(w: number, h: number, W: number, H: number, theta: number, scale: number) { const c = Math.abs(Math.cos(theta)); const s = Math.abs(Math.sin(theta)); return { u: Math.max(0, (w * scale - (W * c + H * s)) / 2), v: Math.max(0, (h * scale - (W * s + H * c)) / 2) };}/** Keeps a pan inside what the window allows, worked out in the image's frame and turned back. */function clampPan(px: number, py: number, w: number, h: number, W: number, H: number, theta: number, scale: number) { const cos = Math.cos(theta); const sin = Math.sin(theta); // The window's offset from the image centre is -pan; into the image frame by -theta. let u = -px * cos - py * sin; let v = px * sin - py * cos; const lim = slack(w, h, W, H, theta, scale); u = Math.max(-lim.u, Math.min(lim.u, u)); v = Math.max(-lim.v, Math.min(lim.v, v)); return { x: -(u * cos - v * sin), y: -(u * sin + v * cos) };}/** Draws the cropped picture into a Blob, at the image's own resolution (or capped by maxSize on the longer side). */export async function cropImage(source: string | HTMLImageElement, area: CropArea, options: { type?: string; quality?: number; maxSize?: number } = {}): Promise<Blob> { const img = typeof source === "string" ? await new Promise<HTMLImageElement>((resolve, reject) => { const i = new Image(); i.crossOrigin = "anonymous"; i.onload = () => resolve(i); i.onerror = reject; i.src = source; }) : source; const k = options.maxSize ? Math.min(1, options.maxSize / Math.max(area.width, area.height)) : 1; const canvas = document.createElement("canvas"); canvas.width = Math.max(1, Math.round(area.width * k)); canvas.height = Math.max(1, Math.round(area.height * k)); const ctx = canvas.getContext("2d")!; ctx.imageSmoothingQuality = "high"; ctx.translate(canvas.width / 2, canvas.height / 2); ctx.scale(k, k); ctx.rotate(area.rotation * DEG); ctx.drawImage(img, -area.centerX, -area.centerY); return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("The crop couldn’t be encoded."))), options.type ?? "image/jpeg", options.quality ?? 0.92));}export function ImageCrop({ src, alt, aspects = ASPECTS, defaultAspect = 0, onChange, crossOrigin, maxZoom = 5, labels, className = "" }: ImageCropProps) { const stage = React.useRef<HTMLDivElement>(null); const photo = React.useRef<HTMLImageElement>(null); const dial = React.useRef<HTMLDivElement>(null); const dialText = React.useRef<HTMLSpanElement>(null); const [aspect, setAspect] = React.useState(defaultAspect); const [natural, setNatural] = React.useState<{ w: number; h: number; src: string } | null>(null); const [size, setSize] = React.useState({ w: 0, h: 0 }); const [busy, setBusy] = React.useState(false); const [quarter, setQuarter] = React.useState(0); const st = React.useRef({ w: 1, h: 1, W: 1, H: 1, fine: 0, quarter: 0, settle: 0, src: "" }); const springs = React.useRef<{ x: Spring; y: Spring; z: Spring } | null>(null); const changed = React.useRef(onChange); React.useLayoutEffect(() => { changed.current = onChange; }); // The window: as large as fits the stage at the chosen aspect. const ratio = aspects[aspect]?.value ?? (natural ? (quarter % 2 ? natural.h / natural.w : natural.w / natural.h) : 1); const pad = 24; const fitW = Math.max(1, Math.min(size.w - pad * 2, (size.h - pad * 2) * ratio)); const fitH = fitW / ratio; const theta = () => (st.current.quarter * 90 + st.current.fine) * DEG; const paint = React.useCallback(() => { const sp = springs.current; if (!sp || !photo.current) return; const { w, h, fine, quarter: q } = st.current; photo.current.style.width = `${w}px`; photo.current.style.height = `${h}px`; photo.current.style.transform = `translate(-50%, -50%) translate3d(${sp.x.get()}px, ${sp.y.get()}px, 0) rotate(${q * 90 + fine}deg) scale(${sp.z.get()})`; if (dial.current) dial.current.style.transform = `translateX(${-fine * TICK}px)`; if (dialText.current) dialText.current.textContent = `${fine > 0 ? "+" : fine < 0 ? "−" : ""}${Math.abs(fine).toFixed(1)}°`; }, []); const report = React.useCallback(() => { const sp = springs.current; if (!sp) return; const { w, h, W, H } = st.current; const t = theta(); const z = sp.z.getTarget(); const px = sp.x.getTarget(); const py = sp.y.getTarget(); const u = (-px * Math.cos(t) - py * Math.sin(t)) / z; const v = (px * Math.sin(t) - py * Math.cos(t)) / z; const width = W / z; const height = H / z; const centerX = w / 2 + u; const centerY = h / 2 + v; changed.current?.({ x: centerX - width / 2, y: centerY - height / 2, width, height, rotation: st.current.quarter * 90 + st.current.fine, centerX, centerY }); }, []); /** Re-fits zoom and pan to the window after anything changed, animated unless told otherwise. */ const settle = React.useCallback( (animate = true) => { const sp = springs.current; if (!sp) return; const { w, h, W, H } = st.current; const t = theta(); const min = coverScale(w, h, W, H, t); const z = Math.max(min, Math.min(min * maxZoom, sp.z.getTarget())); const p = clampPan(sp.x.getTarget(), sp.y.getTarget(), w, h, W, H, t, z); if (animate) { sp.z.set(z); sp.x.set(p.x); sp.y.set(p.y); } else { sp.z.jump(z); sp.x.jump(p.x); sp.y.jump(p.y); } report(); }, [maxZoom, report], ); // Measure the stage. React.useEffect(() => { const el = stage.current; if (!el) return; const ro = new ResizeObserver(() => setSize((s) => (s.w === el.clientWidth && s.h === el.clientHeight ? s : { w: el.clientWidth, h: el.clientHeight }))); ro.observe(el); return () => ro.disconnect(); }, []); // A new image starts covered, centred, unturned. const loaded = React.useCallback((img: HTMLImageElement) => { // Once per picture: the attach check and onLoad can both see a cached image. if (st.current.src === img.src) return; st.current.src = img.src; st.current.w = img.naturalWidth; st.current.h = img.naturalHeight; st.current.fine = 0; st.current.quarter = 0; // A new picture starts from rest, not from the last one's zoom and place. springs.current?.z.jump(1); springs.current?.x.jump(0); springs.current?.y.jump(0); setQuarter(0); setNatural((n) => (n && n.w === img.naturalWidth && n.h === img.naturalHeight && n.src === img.src ? n : { w: img.naturalWidth, h: img.naturalHeight, src: img.src })); }, []); const onLoad = (event: React.SyntheticEvent<HTMLImageElement>) => loaded(event.currentTarget); // A server-rendered photo can finish loading before React attaches onLoad; catch that when the element arrives. const photoRef = React.useCallback( (img: HTMLImageElement | null) => { photo.current = img; if (img?.complete && img.naturalWidth) loaded(img); }, [loaded], ); // The window changed size (aspect, stage, quarter turn): keep the picture covering it. React.useEffect(() => { if (!natural || !size.w) return; st.current.W = fitW; st.current.H = fitH; springs.current ??= { x: createSpring(0, SNAP, paint, 0.05), y: createSpring(0, SNAP, paint, 0.05), z: createSpring(1, SNAP, paint, 0.0005) }; const first = springs.current.z.getTarget() === 1 && springs.current.x.getTarget() === 0; if (first) springs.current.z.jump(coverScale(natural.w, natural.h, fitW, fitH, theta())); settle(!first); // eslint-disable-next-line react-hooks/exhaustive-deps }, [natural, fitW, fitH, settle]); /* ── gestures ─────────────────────────────────────────── */ const g = React.useRef({ points: new Map<number, { x: number; y: number }>(), x0: 0, y0: 0, px: 0, py: 0, z: 1, dist: 0, samples: [] as { x: number; y: number; t: number }[] }); const zoomTo = (z: number, cx: number, cy: number, animate: boolean) => { const sp = springs.current; if (!sp) return; const { w, h, W, H } = st.current; const t = theta(); const min = coverScale(w, h, W, H, t); const z0 = sp.z.getTarget(); const z1 = Math.max(min, Math.min(min * maxZoom, z)); // Keep the point under the pointer still: offsets are measured from the stage centre. const nx = sp.x.getTarget() + (cx - sp.x.getTarget()) * (1 - z1 / z0); const ny = sp.y.getTarget() + (cy - sp.y.getTarget()) * (1 - z1 / z0); const p = clampPan(nx, ny, w, h, W, H, t, z1); if (animate) { sp.z.set(z1); sp.x.set(p.x); sp.y.set(p.y); } else { sp.z.jump(z1); sp.x.jump(p.x); sp.y.jump(p.y); } }; // Wheel zooms at the pointer; a quiet moment afterwards reports the crop. React.useEffect(() => { const el = stage.current; if (!el) return; const wheel = (event: WheelEvent) => { event.preventDefault(); const r = el.getBoundingClientRect(); const z = springs.current?.z.getTarget() ?? 1; zoomTo(z * Math.exp(-event.deltaY * (event.ctrlKey ? 0.01 : 0.002)), event.clientX - r.left - r.width / 2, event.clientY - r.top - r.height / 2, false); window.clearTimeout(st.current.settle); st.current.settle = window.setTimeout(report, 220); }; el.addEventListener("wheel", wheel, { passive: false }); return () => el.removeEventListener("wheel", wheel); // eslint-disable-next-line react-hooks/exhaustive-deps }, [report]); const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => { const sp = springs.current; if (!sp) return; event.currentTarget.setPointerCapture(event.pointerId); const s = g.current; s.points.set(event.pointerId, { x: event.clientX, y: event.clientY }); s.px = sp.x.get(); s.py = sp.y.get(); s.z = sp.z.get(); sp.x.jump(s.px); sp.y.jump(s.py); if (s.points.size === 2) { const [a, b] = [...s.points.values()]; s.dist = Math.hypot(a.x - b.x, a.y - b.y); s.x0 = (a.x + b.x) / 2; s.y0 = (a.y + b.y) / 2; } else { s.x0 = event.clientX; s.y0 = event.clientY; } s.samples = [{ x: event.clientX, y: event.clientY, t: event.timeStamp }]; setBusy(true); }; const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => { const sp = springs.current; const s = g.current; if (!sp || !s.points.has(event.pointerId)) return; s.points.set(event.pointerId, { x: event.clientX, y: event.clientY }); const { w, h, W, H } = st.current; const t = theta(); if (s.points.size >= 2) { const [a, b] = [...s.points.values()]; const r = stage.current!.getBoundingClientRect(); const mx = (a.x + b.x) / 2; const my = (a.y + b.y) / 2; const min = coverScale(w, h, W, H, t); const z = Math.max(min * 0.9, Math.min(min * maxZoom * 1.1, (s.z * Math.hypot(a.x - b.x, a.y - b.y)) / Math.max(1, s.dist))); const cx = s.x0 - r.left - r.width / 2; const cy = s.y0 - r.top - r.height / 2; sp.z.jump(z); sp.x.jump(s.px + (cx - s.px) * (1 - z / s.z) + (mx - s.x0)); sp.y.jump(s.py + (cy - s.py) * (1 - z / s.z) + (my - s.y0)); return; } s.samples.push({ x: event.clientX, y: event.clientY, t: event.timeStamp }); while (s.samples.length > 2 && event.timeStamp - s.samples[0].t > 100) s.samples.shift(); const want = { x: s.px + event.clientX - s.x0, y: s.py + event.clientY - s.y0 }; const z = sp.z.get(); const inside = clampPan(want.x, want.y, w, h, W, H, t, z); // Past the edge it gives, it doesn't stop. sp.x.jump(inside.x + rubberBand(want.x - inside.x, W)); sp.y.jump(inside.y + rubberBand(want.y - inside.y, H)); }; const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => { const sp = springs.current; const s = g.current; if (!sp || !s.points.has(event.pointerId)) return; s.points.delete(event.pointerId); if (s.points.size) { const [p] = [...s.points.values()]; s.x0 = p.x; s.y0 = p.y; s.px = sp.x.get(); s.py = sp.y.get(); s.z = sp.z.get(); return; } const first = s.samples[0]; const end = s.samples[s.samples.length - 1]; const fresh = event.timeStamp - end.t < 100; const span = Math.max(1, end.t - first.t); sp.x.set(projectInertia(sp.x.get(), fresh ? (end.x - first.x) / span : 0, 0.2)); sp.y.set(projectInertia(sp.y.get(), fresh ? (end.y - first.y) / span : 0, 0.2)); settle(); setBusy(false); }; const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { const sp = springs.current; if (!sp) return; const step = event.shiftKey ? 40 : 10; const move = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] }[event.key]; if (move) { event.preventDefault(); sp.x.set(sp.x.getTarget() + move[0]); sp.y.set(sp.y.getTarget() + move[1]); settle(); } else if (event.key === "+" || event.key === "=" || event.key === "-") { event.preventDefault(); zoomTo(sp.z.getTarget() * (event.key === "-" ? 1 / 1.25 : 1.25), 0, 0, true); report(); } }; /* ── straighten dial ──────────────────────────────────── */ const dialDrag = React.useRef({ on: false, x: 0, from: 0 }); const setFine = (deg: number) => { // A soft detent at level. const d = Math.abs(deg) < 0.6 ? 0 : Math.max(-45, Math.min(45, deg)); st.current.fine = Math.round(d * 10) / 10; settle(false); paint(); }; const onDialDown = (event: React.PointerEvent<HTMLDivElement>) => { event.currentTarget.setPointerCapture(event.pointerId); dialDrag.current = { on: true, x: event.clientX, from: st.current.fine }; setBusy(true); }; const onDialMove = (event: React.PointerEvent<HTMLDivElement>) => { if (!dialDrag.current.on) return; setFine(dialDrag.current.from - (event.clientX - dialDrag.current.x) / TICK); }; const onDialUp = () => { if (!dialDrag.current.on) return; dialDrag.current.on = false; setBusy(false); report(); }; const onDialKey = (event: React.KeyboardEvent<HTMLDivElement>) => { const step = event.shiftKey ? 5 : 0.5; const next = { ArrowLeft: st.current.fine - step, ArrowRight: st.current.fine + step, ArrowDown: st.current.fine - step, ArrowUp: st.current.fine + step, Home: 0 }[event.key]; if (next === undefined) return; event.preventDefault(); setFine(next); report(); }; const turn = (dir: 1 | -1) => { st.current.quarter = (st.current.quarter + dir + 4) % 4; setQuarter(st.current.quarter); settle(); }; const reset = () => { st.current.fine = 0; st.current.quarter = 0; setQuarter(0); if (springs.current) { springs.current.z.set(0.0001); springs.current.x.set(0); springs.current.y.set(0); } settle(); }; const ticks = React.useMemo(() => Array.from({ length: 91 }, (_, i) => i - 45), []); const action = "grid size-8 cursor-pointer place-items-center rounded-full text-muted-foreground transition-[background-color,color,scale] duration-150 hover:bg-accent hover:text-foreground active:scale-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"; return ( <div className={`flex [:where(&)]:w-full flex-col gap-3 ${className}`}> <div ref={stage} role="group" tabIndex={0} aria-label={`${alt}. ${labels?.frame ?? "Drag to place, scroll or pinch to zoom; arrow keys move, plus and minus zoom."}`} onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp} onKeyDown={onKeyDown} className="relative aspect-[4/3] w-full cursor-grab touch-none overflow-clip rounded-[18px] bg-muted outline-none select-none active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring/60" > {/* eslint-disable-next-line @next/next/no-img-element */} <img ref={photoRef} key={src} src={src} alt="" crossOrigin={crossOrigin} onLoad={onLoad} draggable={false} className="pointer-events-none absolute top-1/2 left-1/2 max-w-none origin-center will-change-transform" style={{ opacity: natural ? 1 : 0, transition: "opacity 300ms ease-out" }} /> {/* The window: everything outside it is dimmed; thirds show while you adjust. */} <div aria-hidden="true" className="pointer-events-none absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-[4px] ring-1 ring-background/90" style={{ width: fitW, height: fitH, boxShadow: "0 0 0 9999px color-mix(in oklab, var(--background) 62%, transparent)", transition: "width 360ms cubic-bezier(0.16,1,0.3,1), height 360ms cubic-bezier(0.16,1,0.3,1)", }} > <div className="absolute inset-0 transition-opacity duration-300" style={{ opacity: busy ? 1 : 0 }}> {[1, 2].map((n) => ( <React.Fragment key={n}> <span className="absolute inset-y-0 w-px bg-background/70" style={{ left: `${(n * 100) / 3}%` }} /> <span className="absolute inset-x-0 h-px bg-background/70" style={{ top: `${(n * 100) / 3}%` }} /> </React.Fragment> ))} </div> </div> </div> <div className="flex flex-col gap-1"> <div className="flex items-center justify-between px-0.5 text-[12px] text-muted-foreground"> <span>{labels?.straighten ?? "Straighten"}</span> <span ref={dialText} aria-hidden="true" className="tabular-nums text-foreground"> 0.0° </span> </div> <div role="slider" tabIndex={0} aria-label={labels?.straighten ?? "Straighten"} aria-valuemin={-45} aria-valuemax={45} aria-valuenow={0} aria-valuetext="Drag or use the arrow keys" onPointerDown={onDialDown} onPointerMove={onDialMove} onPointerUp={onDialUp} onPointerCancel={onDialUp} onKeyDown={onDialKey} onKeyUp={(e) => e.currentTarget.setAttribute("aria-valuenow", String(st.current.fine))} className="relative h-9 cursor-ew-resize touch-none overflow-clip rounded-full outline-none select-none focus-visible:ring-2 focus-visible:ring-ring/50" style={{ maskImage: "linear-gradient(90deg, transparent, #000 22%, #000 78%, transparent)" }} > <div ref={dial} className="absolute inset-y-0 left-1/2 will-change-transform"> {ticks.map((d) => ( <span key={d} className={`absolute bottom-2 w-px ${d === 0 ? "h-4 bg-foreground/70" : d % 5 === 0 ? "h-3 bg-muted-foreground/70" : "h-2 bg-muted-foreground/40"}`} style={{ left: d * TICK }} /> ))} </div> <span aria-hidden="true" className="absolute bottom-1.5 left-1/2 h-5 w-[2px] -translate-x-1/2 rounded-full bg-primary" /> </div> </div> <div className="flex items-center justify-between gap-2"> <div role="radiogroup" aria-label="Aspect ratio" className="inline-flex h-8 items-center gap-0.5 rounded-full p-0.5 ring-1 ring-border"> {aspects.map((a, i) => ( <button key={a.label} type="button" role="radio" aria-checked={aspect === i} onClick={() => setAspect(i)} className={`h-7 cursor-pointer rounded-full px-2.5 text-[12px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${aspect === i ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground"}`} > {a.label} </button> ))} </div> <div className="flex items-center gap-0.5"> <button type="button" className={action} aria-label={labels?.rotateLeft ?? "Turn left"} onClick={() => turn(-1)}> <RotateCcw className="size-3.5" aria-hidden="true" /> </button> <button type="button" className={action} aria-label={labels?.rotateRight ?? "Turn right"} onClick={() => turn(1)}> <RotateCw className="size-3.5" aria-hidden="true" /> </button> <button type="button" className={`${action} w-auto px-2.5 text-[12px] font-medium`} onClick={reset}> {labels?.reset ?? "Reset"} </button> </div> </div> </div> );}