import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits'; import { getBitmap, thumbSrc } from '../lib/images'; import { rotatedBounds, Renderer } from '../gl/renderer'; import type { Edits, EventRecord, PhotoRecord, Preset } from '../types'; import ContextMenu, { type MenuEntry } from './ContextMenu'; import CropOverlay from './CropOverlay'; import Histogram from './Histogram'; import { BasicPanel, ColorGradingPanel, CropPanel, CurvePanel, DetailPanel, EffectsPanel, HistoryPanel, HslPanel, MetadataPanel, NavigatorPanel, PresetsPanel, } from './Panels'; import Stars, { ColorSwatches, FlagButtons } from './Stars'; /** Zoom is expressed as a percentage of actual pixels, like Lightroom's readout. */ const MAX_ZOOM = 400; const clampNum = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); interface Rect { x: number; y: number; w: number; h: number; } interface Geometry { fitScale: number; fitPct: number; frameW: number; frameH: number; zoomFactor: number; availW: number; availH: number; content: Rect; view: Rect; } const EMPTY_GEO: Geometry = { fitScale: 0, fitPct: 100, frameW: 1, frameH: 1, zoomFactor: 1, availW: 0, availH: 0, content: { x: 0, y: 0, w: 1, h: 1 }, view: { x: 0, y: 0, w: 1, h: 1 }, }; interface Props { photo: PhotoRecord; photos: PhotoRecord[]; events: EventRecord[]; onSelect: (id: string) => void; onExit: () => void; onUpdate: (id: string, patch: Partial, historyLabel?: string) => void; onNavigate: (dir: -1 | 1) => void; clipboard: Edits | null; onCopy: () => void; onPaste: () => void; onExport: () => void; presets: Preset[]; onSavePreset: (name: string, edits: Edits) => void; onDelete: () => void; } export default function Develop({ photo, photos, events, onSelect, onExit, onUpdate, onNavigate, clipboard, onCopy, onPaste, onExport, presets, onSavePreset, onDelete, }: Props) { const canvasRef = useRef(null); const stageRef = useRef(null); const stripRef = useRef(null); const rendererRef = useRef(null); const histRef = useRef(null); const geoRef = useRef(EMPTY_GEO); const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null); const [bitmap, setBitmap] = useState(null); const [stage, setStage] = useState({ w: 0, h: 0 }); const [cropMode, setCropMode] = useState(false); const [cropDrag, setCropDrag] = useState(false); const [showOriginal, setShowOriginal] = useState(false); const [histVersion, setHistVersion] = useState(0); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const [zoom, setZoom] = useState<{ pct: number | 'fit'; cx: number; cy: number }>({ pct: 'fit', cx: 0.5, cy: 0.5, }); const [panning, setPanning] = useState(false); const [readout, setReadout] = useState({ shown: 100, fit: 100 }); const [menu, setMenu] = useState<{ x: number; y: number; kind: 'canvas' | 'film' } | null>(null); const edits = photo.edits; const zoomed = zoom.pct !== 'fit'; const setEdits = useCallback( (patch: Partial, label: string) => { onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label); }, [onUpdate, photo.id, photo.edits], ); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; try { rendererRef.current = new Renderer(canvas); } catch (err) { setError(err instanceof Error ? err.message : 'The image engine could not start'); } return () => { rendererRef.current?.dispose(); rendererRef.current = null; }; }, []); useEffect(() => { const el = stageRef.current; if (!el) return; setStage({ w: el.clientWidth, h: el.clientHeight }); const ro = new ResizeObserver((entries) => { const rect = entries[0].contentRect; setStage({ w: Math.round(rect.width), h: Math.round(rect.height) }); }); ro.observe(el); return () => ro.disconnect(); }, [cropMode]); useEffect(() => { let alive = true; setLoading(true); getBitmap(photo) .then((bmp) => { if (!alive) return; setBitmap(bmp); setLoading(false); }) .catch((err) => { if (!alive) return; setError(err instanceof Error ? err.message : 'Could not load the original image'); setLoading(false); }); return () => { alive = false; }; }, [photo.id, photo.raw, photo.previewUrl]); // A new photo, a crop change or entering crop mode all invalidate the current view. useEffect(() => { setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 }); }, [photo.id, cropMode, edits.crop]); // Leaving crop mode mid-drag must not leave the grain frozen. useEffect(() => { if (!cropMode) setCropDrag(false); }, [cropMode]); const drawPreview = useCallback(() => { const renderer = rendererRef.current; const canvas = canvasRef.current; if (!renderer || !canvas || !bitmap) return; if (stage.w < 40 || stage.h < 40) return; const activeEdits = showOriginal ? { ...defaultEdits(), crop: edits.crop } : edits; const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter); const content: Rect = cropMode ? { x: 0, y: 0, w: 1, h: 1 } : { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h }; const contentW = Math.max(1, frame.w * content.w); const contentH = Math.max(1, frame.h * content.h); const availW = Math.max(60, stage.w - 48); const availH = Math.max(60, stage.h - 48); const fitScale = Math.min(availW / contentW, availH / contentH); const fitPct = Math.min(100, fitScale * 100); const zoomFactor = zoom.pct === 'fit' ? 1 : Math.max(1, zoom.pct / 100 / fitScale); let view: Rect = content; let cssW = Math.max(40, Math.round(contentW * fitScale)); let cssH = Math.max(40, Math.round(contentH * fitScale)); if (zoomFactor > 1.0001) { // The visible window keeps the stage's aspect, so the canvas is stage sized // and the shader maps it onto a sub-rect of the frame. Cost stays constant // no matter how far you zoom, and detail comes from the source bitmap. const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w); const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h); const cx = vw >= content.w ? content.x + content.w / 2 : clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2); const cy = vh >= content.h ? content.y + content.h / 2 : clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2); view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh }; cssW = Math.round(availW); cssH = Math.round(availH); } const dpr = Math.min(window.devicePixelRatio || 1, 2); const cap = Math.min(1, 3200 / Math.max(1, Math.max(cssW * dpr, cssH * dpr))); const pxW = Math.max(1, Math.round(cssW * dpr * cap)); const pxH = Math.max(1, Math.round(cssH * dpr * cap)); canvas.style.width = `${cssW}px`; canvas.style.height = `${cssH}px`; geoRef.current = { fitScale, fitPct, frameW: frame.w, frameH: frame.h, zoomFactor, availW, availH, content, view, }; const shown = Math.round(fitScale * zoomFactor * 100); const fit = Math.round(fitPct); setReadout((prev) => (prev.shown === shown && prev.fit === fit ? prev : { shown, fit })); try { renderer.setImage(bitmap); renderer.render(activeEdits, { width: pxW, height: pxH, cropPreview: cropMode, // The histogram describes the whole photo, so it is only refreshed at fit. histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001, view: zoomFactor <= 1.0001 ? undefined : view, // Holding the grain still keeps the noise from crawling while a crop // handle moves; the new crop-relative scale applies on release. freezeGrain: cropDrag, // One source pixel per device pixel is the crossover: below it mipmaps // resample cleanly, above it bicubic keeps magnified detail from squaring off. upscale: dpr * cap * fitScale * zoomFactor > 1.1, }); histRef.current = renderer.histogram; setHistVersion((v) => v + 1); } catch (err) { setError(err instanceof Error ? err.message : 'Rendering failed'); } }, [bitmap, edits, cropMode, showOriginal, stage, zoom, cropDrag]); useEffect(() => { if (!bitmap) return; const raf = requestAnimationFrame(drawPreview); return () => cancelAnimationFrame(raf); }, [bitmap, drawPreview]); /* ------------------------------------------------------------ zoom & pan */ const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => { const geo = geoRef.current; if (!geo.fitScale) return; const fitPct = geo.fitPct; if (rawPct === 'fit' || rawPct <= fitPct * 1.015 || fitPct >= 99.5) { setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 }); return; } const next = clampNum(rawPct, fitPct * 1.02, MAX_ZOOM); const zNow = Math.max(1, geo.zoomFactor); const zNext = Math.max(1, next / fitPct); const centerX = geo.view.x + geo.view.w / 2; const centerY = geo.view.y + geo.view.h / 2; let cx = centerX; let cy = centerY; if (point) { // Keep the frame point under the cursor fixed while the scale changes. const rect = canvasRef.current?.getBoundingClientRect(); if (rect) { const dx = point.x - (rect.left + rect.width / 2); const dy = point.y - (rect.top + rect.height / 2); const pointX = centerX + dx / (geo.fitScale * zNow) / geo.frameW; const pointY = centerY + dy / (geo.fitScale * zNow) / geo.frameH; cx = pointX - dx / (geo.fitScale * zNext) / geo.frameW; cy = pointY - dy / (geo.fitScale * zNext) / geo.frameH; } } const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW; const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH; const c = geo.content; cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2); cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2); setZoom({ pct: next, cx, cy }); }, []); // Filmstrip: the wheel browses photos sideways, and the current one is kept // in view as you move through the shoot. useEffect(() => { const el = stripRef.current; if (!el) return; const onWheel = (e: WheelEvent) => { if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return; e.preventDefault(); el.scrollLeft += e.deltaY; }; el.addEventListener('wheel', onWheel, { passive: false }); return () => el.removeEventListener('wheel', onWheel); }, []); useEffect(() => { stripRef.current?.querySelector('.film.active')?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); }, [photo.id]); useEffect(() => { const el = stageRef.current; if (!el) return; const onWheel = (e: WheelEvent) => { if (cropMode) return; const geo = geoRef.current; if (!geo.fitScale) return; if (!e.ctrlKey && Math.abs(e.deltaX) > Math.abs(e.deltaY)) return; e.preventDefault(); const base = geo.fitPct * Math.max(1, geo.zoomFactor); applyZoom(base * Math.exp(-e.deltaY * 0.0022), { x: e.clientX, y: e.clientY }); }; el.addEventListener('wheel', onWheel, { passive: false }); return () => el.removeEventListener('wheel', onWheel); }, [cropMode, applyZoom]); const beginPan = (e: React.PointerEvent) => { if (cropMode || !zoomed || e.button !== 0) return; const geo = geoRef.current; panRef.current = { x: e.clientX, y: e.clientY, cx: geo.view.x + geo.view.w / 2, cy: geo.view.y + geo.view.h / 2, }; e.currentTarget.setPointerCapture(e.pointerId); setPanning(true); }; const movePan = (e: React.PointerEvent) => { const start = panRef.current; if (!start) return; const geo = geoRef.current; const z = Math.max(1, geo.zoomFactor); const dx = (e.clientX - start.x) / (geo.fitScale * z * geo.frameW); const dy = (e.clientY - start.y) / (geo.fitScale * z * geo.frameH); const c = geo.content; const cx = geo.view.w >= c.w ? c.x + c.w / 2 : clampNum(start.cx - dx, c.x + geo.view.w / 2, c.x + c.w - geo.view.w / 2); const cy = geo.view.h >= c.h ? c.y + c.h / 2 : clampNum(start.cy - dy, c.y + geo.view.h / 2, c.y + c.h - geo.view.h / 2); setZoom((prev) => ({ pct: prev.pct, cx, cy })); }; const endPan = (e: React.PointerEvent) => { if (!panRef.current) return; panRef.current = null; setPanning(false); if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId); }; const toggleZoom = (x?: number, y?: number) => { if (cropMode) return; if (zoomed) applyZoom('fit'); else applyZoom(100, x !== undefined && y !== undefined ? { x, y } : undefined); }; const undo = useCallback(() => { const hist = photo.history; if (hist.length < 2) return; const idx = hist.findIndex((h) => h.edits === photo.edits); const target = idx > 0 ? hist[idx - 1] : hist[hist.length - 2]; if (target) onUpdate(photo.id, { edits: target.edits }); }, [photo.history, photo.edits, photo.id, onUpdate]); useEffect(() => { const down = (e: KeyboardEvent) => { const target = e.target as HTMLElement | null; if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return; if (e.key === '\\') { setShowOriginal(true); return; } if (e.key === 'ArrowRight') { onNavigate(1); e.preventDefault(); } else if (e.key === 'ArrowLeft') { onNavigate(-1); e.preventDefault(); } else if (e.key.toLowerCase() === 'c' && !e.metaKey && !e.ctrlKey) { setCropMode((v) => !v); } else if (e.key.toLowerCase() === 'z' && !e.metaKey && !e.ctrlKey) { toggleZoom(); e.preventDefault(); } else if (e.key === 'Enter' && cropMode) { setCropMode(false); } else if (e.key === 'Escape') { if (cropMode) setCropMode(false); else onExit(); } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { undo(); e.preventDefault(); } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c') { onCopy(); } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') { onPaste(); } }; const up = (e: KeyboardEvent) => { if (e.key === '\\') setShowOriginal(false); }; window.addEventListener('keydown', down); window.addEventListener('keyup', up); return () => { window.removeEventListener('keydown', down); window.removeEventListener('keyup', up); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [cropMode, onExit, onNavigate, onCopy, onPaste, undo, applyZoom, zoomed]); const applyPreset = useCallback( (preset: Preset) => { const next: Edits = preset.id === 'original' ? { ...defaultEdits(), crop: photo.edits.crop } : { ...photo.edits, ...preset.edits, crop: photo.edits.crop }; onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`); }, [onUpdate, photo.id, photo.edits], ); const frame = bitmap ? rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter) : { w: 1, h: 1 }; const lockedRatio = useMemo(() => { const def = ASPECTS.find((a) => a.id === edits.crop.aspect); return def?.ratio ?? null; }, [edits.crop.aspect]); const applyAspect = useCallback( (id: string) => { const def = ASPECTS.find((a) => a.id === id); if (!def) return; const f = bitmap ? rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter) : { w: 1, h: 1 }; let w = 1; let h = 1; if (def.ratio) { const frameRatio = f.w / f.h; if (def.ratio > frameRatio) { w = 1; h = frameRatio / def.ratio; } else { h = 1; w = def.ratio / frameRatio; } } setEdits( { crop: { ...photo.edits.crop, x: (1 - w) / 2, y: (1 - h) / 2, w, h, aspect: id } }, def.ratio ? `Crop ${def.label}` : 'Crop', ); }, [bitmap, photo.edits.crop, setEdits], ); const rotate = useCallback( (dir: -1 | 1) => { const c = photo.edits.crop; const quarter = ((c.quarter + dir) % 4 + 4) % 4; const rect = dir === 1 ? { x: 1 - (c.y + c.h), y: c.x, w: c.h, h: c.w } : { x: c.y, y: 1 - (c.x + c.w), w: c.h, h: c.w }; setEdits( { crop: { ...c, quarter, ...rect } }, dir === 1 ? 'Rotate 90° right' : 'Rotate 90° left', ); }, [photo.edits.crop, setEdits], ); const resetAll = () => { if (!window.confirm('Reset all develop settings for this photo?')) return; onUpdate(photo.id, { edits: { ...defaultEdits(), crop: photo.edits.crop } }, 'Reset'); }; const canvasMenu: MenuEntry[] = [ { label: 'Zoom to Fit', shortcut: 'Z', onSelect: () => applyZoom('fit') }, { label: 'Zoom to 100%', onSelect: () => applyZoom(100) }, 'separator', { label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) }, { label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) }, 'separator', { label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy }, { label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard }, { label: 'Reset settings', onSelect: resetAll }, 'separator', { label: 'Export…', onSelect: onExport }, { label: 'Delete photo…', danger: true, onSelect: onDelete }, ]; const filmMenu: MenuEntry[] = [ { label: 'Copy settings', onSelect: onCopy }, { label: 'Paste settings', onSelect: onPaste, disabled: !clipboard }, { label: 'Reset settings', onSelect: resetAll }, 'separator', { label: 'Export…', onSelect: onExport }, { label: 'Delete photo…', danger: true, onSelect: onDelete }, ]; const index = photos.findIndex((p) => p.id === photo.id); return (
{photo.name} {index >= 0 ? `${index + 1} / ${photos.length}` : ''} · {photo.width}×{photo.height}
onUpdate(photo.id, { rating: r })} size="md" /> onUpdate(photo.id, { flag: f })} /> onUpdate(photo.id, { color: c })} />
{ e.preventDefault(); setMenu({ x: e.clientX, y: e.clientY, kind: 'canvas' }); }} > {error ? (
{error}
) : (
toggleZoom(e.clientX, e.clientY)} /> {cropMode && bitmap && ( setEdits({ crop: { ...photo.edits.crop, ...rect } }, 'Crop')} onDragChange={setCropDrag} /> )}
)} {loading &&
Loading original…
} {cropMode &&
Drag the edges to crop · Enter to apply · Esc to cancel
} {!cropMode && !error && (
{readout.shown}%
)} {zoomed && !cropMode &&
Drag to pan · scroll to zoom · double-click to fit
} {showOriginal &&
Before
}
{photos.map((p) => ( ))}
{menu && ( setMenu(null)} header={ menu.kind === 'film' ? (
onUpdate(photo.id, { rating: r })} size="md" /> onUpdate(photo.id, { flag: f })} /> onUpdate(photo.id, { color: c })} />
) : undefined } entries={menu.kind === 'canvas' ? canvasMenu : filmMenu} /> )}
); }