Lumen & Gesso / website · lumengesso.com / app / components / CropModal.tsx
| 1 | 'use client'; |
| 2 | |
| 3 | import { useCallback, useEffect, useRef, useState } from 'react'; |
| 4 | import { createPortal } from 'react-dom'; |
| 5 | |
| 6 | type CropModalProps = { |
| 7 | /** The freshly picked image to crop. */ |
| 8 | file: File; |
| 9 | /** Dismiss without producing a crop — the upload is abandoned. */ |
| 10 | onCancel: () => void; |
| 11 | /** Hands back the cropped image as a new File. */ |
| 12 | onCrop: (file: File) => void; |
| 13 | }; |
| 14 | |
| 15 | // Square crop box, expressed in on-screen (displayed-image) pixels. |
| 16 | type Box = { x: number; y: number; size: number }; |
| 17 | type Handle = 'tl' | 'tr' | 'bl' | 'br'; |
| 18 | |
| 19 | const HANDLES: Handle[] = ['tl', 'tr', 'bl', 'br']; |
| 20 | const MIN_FRACTION = 0.2; // crop can't shrink below 20% of the short edge |
| 21 | const MAX_OUTPUT = 1800; // px — cap on the exported crop's edge |
| 22 | |
| 23 | const clamp = (v: number, lo: number, hi: number) => |
| 24 | Math.max(lo, Math.min(hi, v)); |
| 25 | |
| 26 | // A square-locked crop tool shown before an uploaded photo is accepted. |
| 27 | // The crop is always 1:1 — the shape every Lumen & Gesso portrait is |
| 28 | // painted on — so the customer frames their pet exactly as it will sit |
| 29 | // on the canvas. Cropping happens entirely client-side via <canvas>. |
| 30 | export function CropModal({ file, onCancel, onCrop }: CropModalProps) { |
| 31 | const stageRef = useRef<HTMLDivElement>(null); |
| 32 | const imgRef = useRef<HTMLImageElement>(null); |
| 33 | const natRef = useRef({ w: 0, h: 0 }); |
| 34 | const dispRef = useRef({ w: 0, h: 0 }); |
| 35 | const boxRef = useRef<Box>({ x: 0, y: 0, size: 0 }); |
| 36 | |
| 37 | const [url, setUrl] = useState(''); |
| 38 | const [box, setBox] = useState<Box | null>(null); |
| 39 | const [ready, setReady] = useState(false); |
| 40 | const [failed, setFailed] = useState(false); |
| 41 | |
| 42 | // Object-URL lifecycle for the preview image. |
| 43 | useEffect(() => { |
| 44 | const u = URL.createObjectURL(file); |
| 45 | setUrl(u); |
| 46 | return () => URL.revokeObjectURL(u); |
| 47 | }, [file]); |
| 48 | |
| 49 | // Lock background scroll while the modal is open. |
| 50 | useEffect(() => { |
| 51 | const prev = document.body.style.overflow; |
| 52 | document.body.style.overflow = 'hidden'; |
| 53 | return () => { |
| 54 | document.body.style.overflow = prev; |
| 55 | }; |
| 56 | }, []); |
| 57 | |
| 58 | // Esc cancels. |
| 59 | useEffect(() => { |
| 60 | const onKey = (e: KeyboardEvent) => { |
| 61 | if (e.key === 'Escape') onCancel(); |
| 62 | }; |
| 63 | window.addEventListener('keydown', onKey); |
| 64 | return () => window.removeEventListener('keydown', onKey); |
| 65 | }, [onCancel]); |
| 66 | |
| 67 | const commitBox = (b: Box) => { |
| 68 | boxRef.current = b; |
| 69 | setBox(b); |
| 70 | }; |
| 71 | |
| 72 | // Measure the displayed image. On first measure, drop a centered crop |
| 73 | // box; on later measures (window resize) scale the box to keep it valid. |
| 74 | const measure = useCallback(() => { |
| 75 | const img = imgRef.current; |
| 76 | if (!img) return; |
| 77 | const w = img.clientWidth; |
| 78 | const h = img.clientHeight; |
| 79 | if (w === 0 || h === 0) return; |
| 80 | const prev = dispRef.current; |
| 81 | dispRef.current = { w, h }; |
| 82 | if (prev.w === 0) { |
| 83 | const size = Math.min(w, h) * 0.86; |
| 84 | commitBox({ x: (w - size) / 2, y: (h - size) / 2, size }); |
| 85 | setReady(true); |
| 86 | } else if (prev.w !== w) { |
| 87 | const r = w / prev.w; |
| 88 | const b = boxRef.current; |
| 89 | commitBox({ x: b.x * r, y: b.y * r, size: b.size * r }); |
| 90 | } |
| 91 | }, []); |
| 92 | |
| 93 | useEffect(() => { |
| 94 | window.addEventListener('resize', measure); |
| 95 | return () => window.removeEventListener('resize', measure); |
| 96 | }, [measure]); |
| 97 | |
| 98 | const onImgLoad = () => { |
| 99 | const img = imgRef.current; |
| 100 | if (!img) return; |
| 101 | natRef.current = { w: img.naturalWidth, h: img.naturalHeight }; |
| 102 | measure(); |
| 103 | }; |
| 104 | |
| 105 | // One handler drives both moving the box and resizing from any corner. |
| 106 | const startDrag = (mode: 'move' | Handle) => (e: React.PointerEvent) => { |
| 107 | e.preventDefault(); |
| 108 | e.stopPropagation(); |
| 109 | const stage = stageRef.current; |
| 110 | if (!stage) return; |
| 111 | const rect = stage.getBoundingClientRect(); |
| 112 | const disp = dispRef.current; |
| 113 | const start = boxRef.current; |
| 114 | const minSize = Math.min(disp.w, disp.h) * MIN_FRACTION; |
| 115 | |
| 116 | // The corner opposite the dragged handle stays pinned during resize. |
| 117 | const anchor = |
| 118 | mode === 'tl' |
| 119 | ? { x: start.x + start.size, y: start.y + start.size } |
| 120 | : mode === 'tr' |
| 121 | ? { x: start.x, y: start.y + start.size } |
| 122 | : mode === 'bl' |
| 123 | ? { x: start.x + start.size, y: start.y } |
| 124 | : { x: start.x, y: start.y }; // 'br' / 'move' |
| 125 | |
| 126 | const grabX = e.clientX - rect.left - start.x; |
| 127 | const grabY = e.clientY - rect.top - start.y; |
| 128 | |
| 129 | const onMove = (ev: PointerEvent) => { |
| 130 | const px = clamp(ev.clientX - rect.left, 0, disp.w); |
| 131 | const py = clamp(ev.clientY - rect.top, 0, disp.h); |
| 132 | |
| 133 | if (mode === 'move') { |
| 134 | commitBox({ |
| 135 | x: clamp(ev.clientX - rect.left - grabX, 0, disp.w - start.size), |
| 136 | y: clamp(ev.clientY - rect.top - grabY, 0, disp.h - start.size), |
| 137 | size: start.size, |
| 138 | }); |
| 139 | return; |
| 140 | } |
| 141 | |
| 142 | let raw: number; |
| 143 | let cap: number; |
| 144 | if (mode === 'br') { |
| 145 | raw = Math.max(px - anchor.x, py - anchor.y); |
| 146 | cap = Math.min(disp.w - anchor.x, disp.h - anchor.y); |
| 147 | } else if (mode === 'tl') { |
| 148 | raw = Math.max(anchor.x - px, anchor.y - py); |
| 149 | cap = Math.min(anchor.x, anchor.y); |
| 150 | } else if (mode === 'tr') { |
| 151 | raw = Math.max(px - anchor.x, anchor.y - py); |
| 152 | cap = Math.min(disp.w - anchor.x, anchor.y); |
| 153 | } else { |
| 154 | raw = Math.max(anchor.x - px, py - anchor.y); // bl |
| 155 | cap = Math.min(anchor.x, disp.h - anchor.y); |
| 156 | } |
| 157 | const size = clamp(raw, minSize, cap); |
| 158 | commitBox({ |
| 159 | x: mode === 'tl' || mode === 'bl' ? anchor.x - size : anchor.x, |
| 160 | y: mode === 'tl' || mode === 'tr' ? anchor.y - size : anchor.y, |
| 161 | size, |
| 162 | }); |
| 163 | }; |
| 164 | |
| 165 | const onUp = () => { |
| 166 | window.removeEventListener('pointermove', onMove); |
| 167 | window.removeEventListener('pointerup', onUp); |
| 168 | }; |
| 169 | window.addEventListener('pointermove', onMove); |
| 170 | window.addEventListener('pointerup', onUp); |
| 171 | }; |
| 172 | |
| 173 | // Paint the crop onto a canvas at source resolution and hand back a File. |
| 174 | const applyCrop = () => { |
| 175 | const img = imgRef.current; |
| 176 | const disp = dispRef.current; |
| 177 | const b = boxRef.current; |
| 178 | if (!img || disp.w === 0) { |
| 179 | onCrop(file); |
| 180 | return; |
| 181 | } |
| 182 | const scale = natRef.current.w / disp.w; |
| 183 | const sSize = b.size * scale; |
| 184 | const out = Math.min(Math.round(sSize), MAX_OUTPUT); |
| 185 | const canvas = document.createElement('canvas'); |
| 186 | canvas.width = out; |
| 187 | canvas.height = out; |
| 188 | const ctx = canvas.getContext('2d'); |
| 189 | if (!ctx) { |
| 190 | onCrop(file); |
| 191 | return; |
| 192 | } |
| 193 | ctx.drawImage(img, b.x * scale, b.y * scale, sSize, sSize, 0, 0, out, out); |
| 194 | canvas.toBlob( |
| 195 | (blob) => { |
| 196 | if (!blob) { |
| 197 | onCrop(file); |
| 198 | return; |
| 199 | } |
| 200 | const base = file.name.replace(/\.[^.]+$/, '') || 'photo'; |
| 201 | onCrop(new File([blob], `${base}-cropped.jpg`, { type: 'image/jpeg' })); |
| 202 | }, |
| 203 | 'image/jpeg', |
| 204 | 0.92, |
| 205 | ); |
| 206 | }; |
| 207 | |
| 208 | if (!url) return null; |
| 209 | |
| 210 | return createPortal( |
| 211 | <div className="cropmodal" role="dialog" aria-modal="true" aria-label="Crop your photo"> |
| 212 | <div className="cropmodal__scrim" onClick={onCancel} /> |
| 213 | <div className="cropmodal__panel"> |
| 214 | <div className="cropmodal__head"> |
| 215 | <h3 className="cropmodal__title">Crop your photo</h3> |
| 216 | <button |
| 217 | type="button" |
| 218 | className="cropmodal__close" |
| 219 | onClick={onCancel} |
| 220 | aria-label="Cancel cropping" |
| 221 | > |
| 222 | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"> |
| 223 | <path d="M4 4l8 8M12 4l-8 8" /> |
| 224 | </svg> |
| 225 | </button> |
| 226 | </div> |
| 227 | |
| 228 | {failed ? ( |
| 229 | <div className="cropmodal__failed"> |
| 230 | We couldn’t open <strong>{file.name}</strong> for cropping in |
| 231 | the browser — some formats (like HEIC) can’t preview |
| 232 | here. You can still use the photo as-is. |
| 233 | </div> |
| 234 | ) : ( |
| 235 | <div className="cropmodal__stagewrap"> |
| 236 | <div className="cropmodal__stage" ref={stageRef}> |
| 237 | {/* eslint-disable-next-line @next/next/no-img-element */} |
| 238 | <img |
| 239 | ref={imgRef} |
| 240 | src={url} |
| 241 | alt="" |
| 242 | className="cropmodal__img" |
| 243 | draggable={false} |
| 244 | onLoad={onImgLoad} |
| 245 | onError={() => setFailed(true)} |
| 246 | /> |
| 247 | {ready && box && ( |
| 248 | <div |
| 249 | className="cropmodal__crop" |
| 250 | style={{ left: box.x, top: box.y, width: box.size, height: box.size }} |
| 251 | onPointerDown={startDrag('move')} |
| 252 | > |
| 253 | {HANDLES.map((h) => ( |
| 254 | <span |
| 255 | key={h} |
| 256 | className={`cropmodal__handle cropmodal__handle--${h}`} |
| 257 | onPointerDown={startDrag(h)} |
| 258 | /> |
| 259 | ))} |
| 260 | </div> |
| 261 | )} |
| 262 | </div> |
| 263 | </div> |
| 264 | )} |
| 265 | |
| 266 | <p className="cropmodal__hint"> |
| 267 | {failed |
| 268 | ? 'No problem — the studio will frame it for you when your proof is prepared.' |
| 269 | : 'Drag the corner handles to resize, or drag inside the box to move it. The crop is locked to a square — the shape every portrait is painted on.'} |
| 270 | </p> |
| 271 | |
| 272 | <div className="cropmodal__actions"> |
| 273 | {failed ? ( |
| 274 | <button type="button" className="btn btn--rose btn--md" onClick={() => onCrop(file)}> |
| 275 | Use photo anyway |
| 276 | </button> |
| 277 | ) : ( |
| 278 | <button |
| 279 | type="button" |
| 280 | className="btn btn--rose btn--md" |
| 281 | onClick={applyCrop} |
| 282 | disabled={!ready} |
| 283 | > |
| 284 | Crop photo |
| 285 | </button> |
| 286 | )} |
| 287 | <button type="button" className="btn btn--secondary btn--md" onClick={onCancel}> |
| 288 | Cancel |
| 289 | </button> |
| 290 | </div> |
| 291 | </div> |
| 292 | </div>, |
| 293 | document.body, |
| 294 | ); |
| 295 | } |