Files
bobinoo/src/components/social/ImageCropper.tsx
T
2026-12-02 10:22:07 +00:00

241 lines
9.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<HTMLDivElement>(null)
const [img, setImg] = useState<HTMLImageElement>()
const [error, setError] = useState<string>()
const [frame, setFrame] = useState({ w: 0, h: 0 })
const [view, setView] = useState<View>({ z: 1, cx: 0, cy: 0 })
const [busy, setBusy] = useState(false)
const pointers = useRef(new Map<number, { x: number; y: number }>())
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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
pointers.current.delete(e.pointerId)
if (pointers.current.size < 2) pinch.current = null
}
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const step = e.shiftKey ? 40 : 10
const moves: Record<string, [number, number]> = { 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 (
<Sheet
elevated
label={t(format.title)}
title={t(format.title)}
onClose={onCancel}
right={
<button onClick={apply} disabled={!img || busy} className="btn btn-light px-3 py-1.5 text-sm">
{busy ? <Loader2 size={15} className="animate-spin" /> : t('crop.apply')}
</button>
}
>
<div className="px-4 pt-6">
{error ? (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm">
{error}
</p>
) : !img ? (
<div className="grid h-48 place-items-center text-ink-3">
<Loader2 size={22} className="animate-spin" />
</div>
) : (
<>
<div
ref={frameRef}
tabIndex={0}
role="img"
aria-label={t('crop.hint')}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onKeyDown={onKeyDown}
className={cx(
'relative mx-auto cursor-grab touch-none select-none overflow-hidden bg-surface-2 outline-none focus-visible:ring-2 focus-visible:ring-accent active:cursor-grabbing',
kind === 'avatar' ? 'aspect-square w-full max-w-sm' : 'aspect-[3/1] w-full max-w-2xl',
)}
>
<img
src={src}
alt=""
draggable={false}
className="pointer-events-none absolute max-w-none"
style={{ left: 0, top: 0, width: iw * s, height: ih * s, transform: `translate(${frame.w / 2 - view.cx * s}px, ${frame.h / 2 - view.cy * s}px)` }}
/>
{/* Photo de profil : ce qui sort du rond est assombri ; bannière : le cadre est la bannière */}
{kind === 'avatar' ? (
<span className="pointer-events-none absolute inset-0 rounded-full border border-line-strong shadow-[0_0_0_9999px_var(--color-scrim)]" />
) : (
<span className="pointer-events-none absolute inset-0 border border-line-strong" />
)}
</div>
<label className="mx-auto mt-6 flex max-w-sm items-center gap-3">
<span className="text-xs text-ink-3">{t('crop.zoom')}</span>
<input
type="range"
min={1}
max={MAX_ZOOM}
step={0.01}
value={view.z}
onChange={(e) => zoomAt(frame.w / 2, frame.h / 2, Number(e.target.value))}
className="flex-1 accent-accent"
/>
</label>
<p className="mx-auto mt-4 max-w-sm text-center text-xs leading-relaxed text-ink-3">{t('crop.hint')}</p>
</>
)}
</div>
</Sheet>
)
}