import { Loader2 } from 'lucide-react' import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react' import { t } from '../../i18n' import { cropToJpeg, loadImage } from '../../lib/image' import { cx } from '../../lib/utils' import Sheet from './Sheet' /** Format de sortie : photo ronde (400 × 400) ou bannière 3:1 (1500 × 500), comme à l'affichage. */ const FORMATS = { avatar: { width: 400, height: 400, quality: 0.86, title: 'crop.avatarTitle' }, banner: { width: 1500, height: 500, quality: 0.84, title: 'crop.bannerTitle' }, } as const const MAX_ZOOM = 5 /** Cadrage : zoom (1 = l'image couvre juste le cadre) et point de l'image au centre du cadre (en pixels de l'image). */ interface View { z: number cx: number cy: number } /** * Recadrer une photo de profil ou une bannière avant l'envoi : glisser pour déplacer, pincer, molette ou curseur * pour zoomer, flèches du clavier pour ajuster. L'image couvre toujours tout le cadre (pas de bord vide). */ export default function ImageCropper({ file, kind, onCancel, onDone }: { file: File; kind: 'avatar' | 'banner'; onCancel: () => void; onDone: (blob: Blob) => void }) { const format = FORMATS[kind] const frameRef = useRef(null) const [img, setImg] = useState() const [error, setError] = useState() const [frame, setFrame] = useState({ w: 0, h: 0 }) const [view, setView] = useState({ z: 1, cx: 0, cy: 0 }) const [busy, setBusy] = useState(false) const pointers = useRef(new Map()) const pinch = useRef<{ dist: number; z: number } | null>(null) // Adresse locale de la photo, libérée en fermant const [src] = useState(() => URL.createObjectURL(file)) useEffect(() => () => URL.revokeObjectURL(src), [src]) useEffect(() => { let alive = true loadImage(src) .then((i) => { if (!alive) return setImg(i) setView({ z: 1, cx: i.naturalWidth / 2, cy: i.naturalHeight / 2 }) }) .catch((e: Error) => alive && setError(e.message)) return () => { alive = false } }, [src]) // Taille du cadre à l'écran (suit la rotation du téléphone) useLayoutEffect(() => { const el = frameRef.current if (!el) return const measure = () => setFrame({ w: el.clientWidth, h: el.clientHeight }) measure() const ro = new ResizeObserver(measure) ro.observe(el) return () => ro.disconnect() }, [img]) const iw = img?.naturalWidth ?? 1 const ih = img?.naturalHeight ?? 1 // Pixels d'écran par pixel d'image, au zoom 1 : l'image couvre juste le cadre const base = frame.w && frame.h ? Math.max(frame.w / iw, frame.h / ih) : 1 /** Garde l'image dans le cadre : jamais de bord vide, zoom entre 1 et MAX_ZOOM. */ const clamp = (v: View): View => { const z = Math.min(MAX_ZOOM, Math.max(1, v.z)) const s = base * z const hw = frame.w / (2 * s) const hh = frame.h / (2 * s) return { z, cx: Math.min(iw - hw, Math.max(hw, v.cx)), cy: Math.min(ih - hh, Math.max(hh, v.cy)) } } // Cadre redimensionné (rotation de l'écran) : l'image doit toujours le couvrir // eslint-disable-next-line react-hooks/exhaustive-deps useEffect(() => setView((v) => clamp(v)), [frame.w, frame.h]) const pan = (dx: number, dy: number) => setView((v) => clamp({ ...v, cx: v.cx - dx / (base * v.z), cy: v.cy - dy / (base * v.z) })) /** Zoom autour d'un point du cadre (le doigt, le curseur) : ce point de l'image ne bouge pas. */ const zoomAt = (fx: number, fy: number, z: number) => setView((v) => { const ox = fx - frame.w / 2 const oy = fy - frame.h / 2 const nx = v.cx + ox / (base * v.z) const ny = v.cy + oy / (base * v.z) const nz = Math.min(MAX_ZOOM, Math.max(1, z)) return clamp({ z: nz, cx: nx - ox / (base * nz), cy: ny - oy / (base * nz) }) }) // Molette (ordinateur) : écouteur non passif pour que la page ne défile pas en même temps const zoomAtRef = useRef(zoomAt) zoomAtRef.current = zoomAt const zoomRef = useRef(view.z) zoomRef.current = view.z useEffect(() => { const el = frameRef.current if (!el || !img) return const onWheel = (e: WheelEvent) => { e.preventDefault() const r = el.getBoundingClientRect() zoomAtRef.current(e.clientX - r.left, e.clientY - r.top, zoomRef.current * Math.exp(-e.deltaY * 0.002)) } el.addEventListener('wheel', onWheel, { passive: false }) return () => el.removeEventListener('wheel', onWheel) }, [img]) const local = (e: PointerEvent) => { const r = frameRef.current!.getBoundingClientRect() return { x: e.clientX - r.left, y: e.clientY - r.top } } const onPointerDown = (e: PointerEvent) => { e.currentTarget.setPointerCapture(e.pointerId) pointers.current.set(e.pointerId, local(e)) if (pointers.current.size === 2) { const [a, b] = [...pointers.current.values()] pinch.current = { dist: Math.hypot(a.x - b.x, a.y - b.y) || 1, z: view.z } } } const onPointerMove = (e: PointerEvent) => { const prev = pointers.current.get(e.pointerId) if (!prev) return const p = local(e) pointers.current.set(e.pointerId, p) if (pointers.current.size === 1) pan(p.x - prev.x, p.y - prev.y) else if (pointers.current.size === 2 && pinch.current) { const [a, b] = [...pointers.current.values()] zoomAt((a.x + b.x) / 2, (a.y + b.y) / 2, (pinch.current.z * Math.hypot(a.x - b.x, a.y - b.y)) / pinch.current.dist) } } const onPointerUp = (e: PointerEvent) => { pointers.current.delete(e.pointerId) if (pointers.current.size < 2) pinch.current = null } const onKeyDown = (e: KeyboardEvent) => { const step = e.shiftKey ? 40 : 10 const moves: Record = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] } if (moves[e.key]) { e.preventDefault() pan(...moves[e.key]) } } const apply = async () => { if (!img || busy) return setBusy(true) try { const s = base * view.z const w = frame.w / s const h = frame.h / s onDone(await cropToJpeg(img, { x: view.cx - w / 2, y: view.cy - h / 2, w, h }, format.width, format.height, format.quality)) } catch (e) { setError((e as Error).message) setBusy(false) } } const s = base * view.z return ( {busy ? : t('crop.apply')} } >
{error ? (

{error}

) : !img ? (
) : ( <>
{/* Photo de profil : ce qui sort du rond est assombri ; bannière : le cadre est la bannière */} {kind === 'avatar' ? ( ) : ( )}

{t('crop.hint')}

)}
) }