import { useEffect, useRef, useState, type PointerEvent } from 'react'; import { clamp } from '../lib/curves'; import { grainSampleWindow, Renderer } from '../gl/renderer'; import type { CropState, Edits } from '../types'; type Mode = 'move' | 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'; /** * Point (frame uv) the loupe sits on when dragged to `u`,`v` inside the crop * rectangle, kept a half-box away from its edges so the patch stays inside. */ export function clampLoupe( crop: { x: number; y: number; w: number; h: number }, u: number, v: number, halfU: number, halfV: number, ) { const cx = Math.min(1 - halfU, Math.max(halfU, Math.min(1, Math.max(0, u)))); const cy = Math.min(1 - halfV, Math.max(halfV, Math.min(1, Math.max(0, v)))); return { x: crop.x + cx * crop.w, y: crop.y + cy * crop.h }; } interface Props { crop: CropState; frame: { w: number; h: number }; ratio: number | null; bitmap: ImageBitmap | null; edits: Edits; onChange: (rect: Partial) => void; /** lets the preview hold the grain still while a handle is moving */ onDragChange?: (busy: boolean) => void; } const MIN = 0.04; function clampRect(r: CropState): CropState { let w = clamp(r.w, MIN, 1); let h = clamp(r.h, MIN, 1); const x = clamp(r.x, 0, 1 - w); const y = clamp(r.y, 0, 1 - h); return { ...r, x, y, w, h }; } function applyDrag( start: CropState, mode: Mode, dx: number, dy: number, ratio: number | null, frame: { w: number; h: number }, ): Partial { let { x, y, w, h } = start; if (mode === 'move') { x = clamp(x + dx, 0, 1 - w); y = clamp(y + dy, 0, 1 - h); return { x, y }; } if (mode.includes('e')) w = clamp(w + dx, MIN, 1 - x); if (mode.includes('s')) h = clamp(h + dy, MIN, 1 - y); if (mode.includes('w')) { const nx = clamp(x + dx, 0, x + w - MIN); w += x - nx; x = nx; } if (mode.includes('n')) { const ny = clamp(y + dy, 0, y + h - MIN); h += y - ny; y = ny; } if (ratio) { const frameRatio = frame.w / frame.h; const dragsWidth = mode.includes('e') || mode.includes('w'); if (dragsWidth) { const targetH = (w * frameRatio) / ratio; if (mode.includes('n')) y = y + h - targetH; h = targetH; } else if (mode.includes('n') || mode.includes('s')) { const targetW = (h * ratio) / frameRatio; x += (w - targetW) / 2; w = targetW; } if (w > 1) { const k = 1 / w; w *= k; h *= k; } if (h > 1) { const k = 1 / h; w *= k; h *= k; } if (mode.includes('w')) x = start.x + start.w - w; if (mode.includes('n')) y = start.y + start.h - h; x = clamp(x, 0, 1 - w); y = clamp(y, 0, 1 - h); } return clampRect({ ...start, x, y, w, h }); } export default function CropOverlay({ crop, frame, ratio, bitmap, edits, onChange, onDragChange }: Props) { const ref = useRef(null); const start = useRef<{ mode: Mode; x: number; y: number; rect: CropState } | null>(null); const [dragging, setDragging] = useState(false); const loupe = useRef(null); const loupeRenderer = useRef(null); /** where the patch is sampling, in frame uv; null = centre of the rectangle */ const [loupePoint, setLoupePoint] = useState<{ x: number; y: number } | null>(null); /** pointer offset from the patch centre while it is being dragged */ const grab = useRef<{ x: number; y: number } | null>(null); useEffect( () => () => { loupeRenderer.current?.dispose(); loupeRenderer.current = null; }, [], ); // A live 1:1 grain patch inside the crop rectangle: it samples whatever area the // rectangle frames, so the rectangle can be judged as it is dragged. useEffect(() => { const canvas = loupe.current; if (!canvas || !bitmap) return; const dpr = Math.min(window.devicePixelRatio || 1, 2); const cssW = 120; const cropPxW = Math.max(1, frame.w * crop.w); const cropPxH = Math.max(1, frame.h * crop.h); const cssH = Math.round(Math.min(96, Math.max(48, cssW * (cropPxH / cropPxW)))); const W = Math.max(1, Math.round(cssW * dpr)); const H = Math.max(1, Math.round(cssH * dpr)); canvas.style.width = `${cssW}px`; canvas.style.height = `${cssH}px`; if (canvas.width !== W) canvas.width = W; if (canvas.height !== H) canvas.height = H; try { if (!loupeRenderer.current) loupeRenderer.current = new Renderer(canvas); const r = loupeRenderer.current; r.setImage(bitmap); const view = grainSampleWindow(frame, crop, W, H, loupePoint); r.render({ ...edits, crop }, { width: W, height: H, view }); } catch { // The overlay still works if the engine cannot start a second context. } }, [bitmap, crop, edits, frame, loupePoint]); const dpr = Math.min(typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1, 2); const loupeCssW = 120; const cropPxW = Math.max(1, frame.w * crop.w); const cropPxH = Math.max(1, frame.h * crop.h); const loupeCssH = Math.round(Math.min(96, Math.max(48, loupeCssW * (cropPxH / cropPxW)))); const loupeW = Math.max(1, Math.round(loupeCssW * dpr)); const loupeH = Math.max(1, Math.round(loupeCssH * dpr)); const view = grainSampleWindow(frame, crop, loupeW, loupeH, loupePoint); const fits = crop.w > 0.16 && crop.h > 0.16; const loupeAt = { left: `${((view.x + view.w / 2 - crop.x) / crop.w) * 100}%`, top: `${((view.y + view.h / 2 - crop.y) / crop.h) * 100}%`, width: `${loupeCssW}px`, height: `${loupeCssH}px`, transform: 'translate(-50%, -50%)', display: fits && bitmap ? 'block' : 'none', }; const startLoupe = (e: PointerEvent) => { e.preventDefault(); e.stopPropagation(); e.currentTarget.setPointerCapture(e.pointerId); const box = e.currentTarget.parentElement?.getBoundingClientRect(); if (!box || !box.width || !box.height) return; const cx = box.left + ((view.x + view.w / 2 - crop.x) / crop.w) * box.width; const cy = box.top + ((view.y + view.h / 2 - crop.y) / crop.h) * box.height; grab.current = { x: e.clientX - cx, y: e.clientY - cy }; }; const moveLoupe = (e: PointerEvent) => { const g = grab.current; if (!g) return; const box = e.currentTarget.parentElement?.getBoundingClientRect(); if (!box || !box.width || !box.height) return; const halfU = Math.min(0.5, loupeCssW / 2 / box.width); const halfV = Math.min(0.5, loupeCssH / 2 / box.height); setLoupePoint( clampLoupe( crop, (e.clientX - g.x - box.left) / box.width, (e.clientY - g.y - box.top) / box.height, halfU, halfV, ), ); }; const endLoupe = () => { grab.current = null; }; const onPointerDown = (e: React.PointerEvent) => { const el = e.target as HTMLElement; const mode = (el.dataset.mode ?? 'move') as Mode; e.preventDefault(); e.stopPropagation(); ref.current?.setPointerCapture(e.pointerId); start.current = { mode, x: e.clientX, y: e.clientY, rect: { ...crop } }; setDragging(true); onDragChange?.(true); }; const onPointerMove = (e: React.PointerEvent) => { const s = start.current; const el = ref.current; if (!s || !el) return; const rect = el.getBoundingClientRect(); if (!rect.width || !rect.height) return; const dx = (e.clientX - s.x) / rect.width; const dy = (e.clientY - s.y) / rect.height; onChange(applyDrag(s.rect, s.mode, dx, dy, ratio, frame)); }; const end = (e: React.PointerEvent) => { if (ref.current?.hasPointerCapture(e.pointerId)) ref.current.releasePointerCapture(e.pointerId); start.current = null; setDragging(false); onDragChange?.(false); }; const style = { left: `${crop.x * 100}%`, top: `${crop.y * 100}%`, width: `${crop.w * 100}%`, height: `${crop.h * 100}%`, }; return (
{(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as Mode[]).map((m) => ( ))} {Math.round(crop.w * 100)}% × {Math.round(crop.h * 100)}%
); }