import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { ASPECTS, defaultEdits, defaultLocalLayer, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS, } from '../lib/edits'; import { subscribeClipPreview } from '../lib/clipPreview'; import { getBitmap, getDenoisedBitmap } from '../lib/images'; import { useMediaQuery } from '../lib/useMediaQuery'; import { usePersistentState } from '../lib/usePersistentState'; import { solveWhiteBalance } from '../lib/whiteBalance'; import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask'; import { buildLensCorrection, correctLensPoint, uncorrectLensPoint, type LensCorrection, } from '../lib/lensfun'; import { frameToSource, rotatedBounds, Renderer, sourceToFrame, unwarpGeometryPoint, warpGeometryPoint, } from '../gl/renderer'; import type { ColorLabel, Edits, EventRecord, Flag, HealSpot, LocalLayer, LocalMaskKind, LocalStroke, MetadataPreset, PhotoRecord, Preset, Snapshot, } from '../types'; import ContextMenu, { type MenuEntry } from './ContextMenu'; import EditedImage from './EditedImage'; import CropOverlay from './CropOverlay'; import Histogram from './Histogram'; import { BasicPanel, ColorGradingPanel, CropPanel, CurvePanel, DetailPanel, EffectsPanel, HistoryPanel, HslPanel, LocalPanel, MetadataPanel, NavigatorPanel, OpticsPanel, PresetsPanel, ProofPanel, SnapshotsPanel, } 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 }, }; function cloneLocalLayer(layer: LocalLayer): LocalLayer { return { ...layer, brush: { strokes: layer.brush.strokes.map((stroke) => ({ ...stroke, points: stroke.points.map((point) => ({ ...point })), })), }, linear: { ...layer.linear }, radial: { ...layer.radial }, adjust: { ...layer.adjust }, range: { ...layer.range }, }; } interface Props { photo: PhotoRecord; photos: PhotoRecord[]; events: EventRecord[]; onSelect: (id: string) => void; onExit: () => void; onUpdate: (id: string, patch: Partial, historyLabel?: string) => void; clipboard: Edits | null; onCopy: () => void; /** Copy settings from a named filmstrip photo instead of the canvas photo. */ onCopyOf?: (id: string) => void; /** Paste the copied settings; no ids means the photo on the canvas. */ onPaste: (ids?: string[]) => void; /** Reset several photos at once, without a per-photo confirmation. */ onResetSelection?: (ids: string[]) => void; localClipboard: LocalLayer | null; onLocalClipboard: (layer: LocalLayer | null) => void; onExport: () => void; onPrint: () => void; canPushImmich?: boolean; onPushImmich?: () => void; onOpenImmich?: () => void; presets: Preset[]; onSavePreset: (name: string, edits: Edits) => void; onDelete: () => void; onVirtualCopy: () => void; metadataPresets: MetadataPreset[]; keywordLibrary: string[]; onSaveSnapshot: (name: string) => void; onRestoreSnapshot: (snapshot: Snapshot) => void; onDeleteSnapshot: (snapshot: Snapshot) => void; onSaveMetadataPreset: (preset: Omit) => void; onDeleteMetadataPreset: (id: string) => void; } export default function Develop({ photo, photos, events, onSelect, onExit, onUpdate, clipboard, onCopy, onCopyOf, onPaste, onResetSelection, localClipboard, onLocalClipboard, onExport, onPrint, canPushImmich = false, onPushImmich, onOpenImmich, presets, onSavePreset, onDelete, onVirtualCopy, metadataPresets, keywordLibrary, onSaveSnapshot, onRestoreSnapshot, onDeleteSnapshot, onSaveMetadataPreset, onDeleteMetadataPreset, }: 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 [denoisedBitmap, setDenoisedBitmap] = useState(null); const [stage, setStage] = useState({ w: 0, h: 0 }); const [cropMode, setCropMode] = useState(false); const [cropDrag, setCropDrag] = useState(false); const [clipPreview, setClipPreview] = useState(false); const [picking, setPicking] = useState(false); const [clipping, setClipping] = useState<'highlights' | 'shadows' | null>(null); const [loupe, setLoupe] = useState(false); const [adjustOpen, setAdjustOpen] = useState(false); const [leftOpen, setLeftOpen] = usePersistentState('develop.left.open', true); const [rightOpen, setRightOpen] = usePersistentState('develop.right.open', true); const [stripOpen, setStripOpen] = usePersistentState('develop.filmstrip.open', true); const [mobileStripOpen, setMobileStripOpen] = useState(false); const [mobileAdjustOpen, setMobileAdjustOpen] = useState(false); const [tipDismissed, setTipDismissed] = usePersistentState('develop.tip.dismissed', false); const mobile = useMediaQuery('(max-width: 760px)'); const shownStripOpen = mobile ? mobileStripOpen : stripOpen; const toggleStrip = () => (mobile ? setMobileStripOpen((open) => !open) : setStripOpen((open) => !open)); const [filmMinRating, setFilmMinRating] = useState(0); const [filmFlag, setFilmFlag] = useState('any'); // Filmstrip multi-select. The canvas keeps its own photo; this is the set a // paste applies to, exactly like Lightroom's filmstrip selection. const [filmSel, setFilmSel] = useState([photo.id]); const [filmAnchor, setFilmAnchor] = useState(photo.id); 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 [navigatorView, setNavigatorView] = useState(null); const [readout, setReadout] = useState({ shown: 100, fit: 100 }); const [menu, setMenu] = useState<{ x: number; y: number; kind: 'canvas' | 'film'; ids?: string[]; } | null>(null); const [healMode, setHealMode] = useState(false); const [brushPx, setBrushPx] = useState(56); const [healFeather, setHealFeather] = useState(50); const [healSelected, setHealSelected] = useState(null); const [healHover, setHealHover] = useState<{ x: number; y: number } | null>(null); const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null); const [localSelected, setLocalSelected] = useState(null); const [localMode, setLocalMode] = useState(false); const [autoMaskBusy, setAutoMaskBusy] = useState(false); const [localBrush, setLocalBrush] = useState(72); const [localHover, setLocalHover] = useState<{ x: number; y: number } | null>(null); const [localDraft, setLocalDraft] = useState(null); const [lensCorrection, setLensCorrection] = useState(null); const [lensSplit, setLensSplit] = useState(false); const [lensSplitAt, setLensSplitAt] = useState(0.5); const [lensState, setLensState] = useState<{ loading: boolean; error: string | null }>({ loading: false, error: null, }); const localDrag = useRef<{ id: string; mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end'; stroke: LocalStroke | null; } | null>(null); const edits = photo.edits; const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null; const zoomed = zoom.pct !== 'fit'; // The filmstrip has its own Lightroom-style cull filter so you can narrow the // strip without changing the grid filters or the photo open on the canvas. const filmFilterActive = filmMinRating > 0 || filmFlag !== 'any'; const filmPhotos = useMemo( () => photos.filter( (item) => item.rating >= filmMinRating && (filmFlag === 'any' || item.flag === filmFlag), ), [photos, filmMinRating, filmFlag], ); const filmPosition = filmPhotos.findIndex((item) => item.id === photo.id); const currentInFilm = filmPosition >= 0; const navigateFilm = useCallback( (dir: -1 | 1) => { if (!filmPhotos.length) return; const at = filmPhotos.findIndex((item) => item.id === photo.id); if (at < 0) { const edge = dir > 0 ? filmPhotos[0] : filmPhotos[filmPhotos.length - 1]; if (edge) onSelect(edge.id); return; } const next = filmPhotos[at + dir]; if (next) onSelect(next.id); }, [filmPhotos, onSelect, photo.id], ); // The photo on the canvas is always part of the selection, so a fresh filmstrip // starts with just that frame. Cmd/Shift clicks grow the set without moving it. useEffect(() => { setFilmSel([photo.id]); setFilmAnchor(photo.id); }, [photo.id]); // A cull filter can hide part of the selection; drop those frames rather than // pasting settings into photos that are no longer on screen. useEffect(() => { setFilmSel((prev) => { const visible = new Set(filmPhotos.map((item) => item.id)); const next = prev.filter((id) => visible.has(id)); return next.length === prev.length ? prev : next; }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [filmMinRating, filmFlag]); const clickFilm = (p: PhotoRecord, e: React.MouseEvent) => { if (e.shiftKey) { const a = filmPhotos.findIndex((item) => item.id === filmAnchor); const b = filmPhotos.findIndex((item) => item.id === p.id); if (a >= 0 && b >= 0) { const [lo, hi] = a < b ? [a, b] : [b, a]; setFilmSel(filmPhotos.slice(lo, hi + 1).map((item) => item.id)); } else { setFilmSel([p.id]); setFilmAnchor(p.id); } return; } if (e.metaKey || e.ctrlKey) { setFilmSel((prev) => prev.includes(p.id) ? prev.filter((id) => id !== p.id) : [...prev, p.id], ); setFilmAnchor(p.id); return; } setFilmSel([p.id]); setFilmAnchor(p.id); onSelect(p.id); }; const moveLensSplit = (e: React.PointerEvent) => { const rect = e.currentTarget.parentElement?.getBoundingClientRect(); if (!rect || rect.width <= 0) return; setLensSplitAt(clampNum((e.clientX - rect.left) / rect.width, 0.02, 0.98)); }; 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; }; }, []); // Ctrl held while dragging Exposure paints clipped channels on the preview. useEffect(() => subscribeClipPreview(setClipPreview), []); 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]); // The denoised proxy is a separate server asset keyed by the edit. Load it // alongside the source so the first frame after generating is not stale, and // drop it when the key is cleared. useEffect(() => { const key = edits.aiDenoise.key; if (!key) { setDenoisedBitmap(null); return; } let alive = true; getDenoisedBitmap(photo, key) .then((bmp) => { if (alive) setDenoisedBitmap(bmp); }) .catch(() => { if (alive) setDenoisedBitmap(null); }); return () => { alive = false; }; }, [photo.id, edits.aiDenoise.key]); 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]); // Warm the previous and next originals while the current frame is being // edited, so arrow-key culling does not wait on a network fetch each time. useEffect(() => { const at = filmPhotos.findIndex((item) => item.id === photo.id); if (at < 0) return; const neighbours = [filmPhotos[at - 1], filmPhotos[at + 1]].filter( (item): item is PhotoRecord => Boolean(item), ); if (!neighbours.length) return; let alive = true; const timer = setTimeout(() => { if (!alive) return; for (const next of neighbours) void getBitmap(next).catch(() => undefined); }, 450); return () => { alive = false; clearTimeout(timer); }; }, [filmPhotos, photo.id]); // Build the calibrated maps for the selected profile once per photo and // correction setting. Lensfun is loaded lazily, so photos without a profile // never pay for the database. useEffect(() => { const profile = edits.lens; if (!profile) { setLensCorrection(null); setLensState({ loading: false, error: null }); setLensSplit(false); return; } let alive = true; setLensCorrection(null); setLensState({ loading: true, error: null }); buildLensCorrection(profile, { width: bitmap?.width ?? photo.width, height: bitmap?.height ?? photo.height, meta: photo.meta, }) .then((correction) => { if (!alive) return; setLensCorrection(correction); setLensState({ loading: false, error: null }); }) .catch((err) => { if (!alive) return; console.error('Lens correction failed', err); setLensCorrection(null); setLensState({ loading: false, error: err instanceof Error ? err.message : 'Could not build the lens correction', }); }); return () => { alive = false; }; }, [edits.lens, bitmap, photo.id, photo.width, photo.height, photo.meta]); // 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 })); setNavigatorView((prev) => prev && prev.x === view.x && prev.y === view.y && prev.w === view.w && prev.h === view.h ? prev : view, ); try { renderer.setImage(bitmap); // "Show original" must show the untouched source, not the cleaned proxy. renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100); 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, clipPreview, clipping: clipping ?? undefined, lens: showOriginal ? null : lensCorrection, lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined, }); histRef.current = renderer.histogram; setHistVersion((v) => v + 1); } catch (err) { setError(err instanceof Error ? err.message : 'Rendering failed'); } }, [ bitmap, denoisedBitmap, edits, cropMode, showOriginal, stage, zoom, cropDrag, clipPreview, clipping, lensCorrection, lensSplit, lensSplitAt, ]); 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 }); }, []); /** Click or drag in the navigator thumbnail to move the zoomed viewport. */ const navigateZoom = useCallback( (fx: number, fy: number) => { const geo = geoRef.current; if (!geo.fitScale) return; // A click while fitted behaves like Lightroom: jump to actual pixels at // the chosen point. Once zoomed, dragging keeps the current scale. if (zoom.pct === 'fit' && geo.fitPct >= 99.5) return; const pct = zoom.pct === 'fit' ? 100 : zoom.pct; const z = Math.max(1, pct / geo.fitPct); const c = geo.content; const vw = Math.min(c.w, geo.availW / (geo.fitScale * z) / geo.frameW); const vh = Math.min(c.h, geo.availH / (geo.fitScale * z) / geo.frameH); const cx = vw >= c.w ? c.x + c.w / 2 : clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2); const cy = vh >= c.h ? c.y + c.h / 2 : clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2); setZoom({ pct, cx, cy }); }, [zoom.pct], ); // 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, filmMinRating, filmFlag, shownStripOpen]); useEffect(() => { const el = stageRef.current; if (!el) return; const onWheel = (e: WheelEvent) => { // The fullscreen adjustment panel scrolls independently of the photo. if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return; if (cropMode) return; // While painting a mask, the wheel sizes the brush instead of zooming. if (localMode && activeLocal?.kind === 'brush') { e.preventDefault(); setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320)); return; } // While healing, the wheel sizes the brush instead of zooming. if (healMode) { e.preventDefault(); setBrushPx((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 14, 240)); 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, healMode, localMode, activeLocal]); const beginPan = (e: React.PointerEvent) => { if (picking || cropMode || healMode || localMode || !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); }; // The eyedropper reads through the renderer so the sample follows the same // crop, straighten and zoom mapping as the pixels on screen. const pickWhiteBalance = (e: React.MouseEvent) => { if (!picking || cropMode) return; const canvas = canvasRef.current; const renderer = rendererRef.current; if (!canvas || !renderer) return; const rect = canvas.getBoundingClientRect(); if (!rect.width || !rect.height) return; const geo = geoRef.current; const sample = renderer.pickSource(edits, { nx: clampNum((e.clientX - rect.left) / rect.width, 0, 1), ny: clampNum((e.clientY - rect.top) / rect.height, 0, 1), view: geo.zoomFactor > 1.0001 ? geo.view : undefined, upscale: Math.min(window.devicePixelRatio || 1, 2) * geo.fitScale * geo.zoomFactor > 1.1, }); setPicking(false); if (!sample) return; const wb = solveWhiteBalance(sample); if (wb) setEdits({ temp: wb.temp, tint: wb.tint }, 'White balance'); }; /* --------------------------------------------------------------- healing */ /** Pointer position as normalized source-image uv, through crop and zoom. */ const sourcePointFromEvent = useCallback( (e: { clientX: number; clientY: number }): { x: number; y: number } | null => { const canvas = canvasRef.current; if (!canvas || !bitmap) return null; const rect = canvas.getBoundingClientRect(); if (!rect.width || !rect.height) return null; const geo = geoRef.current; const view = geo.zoomFactor > 1.0001 ? geo.view : edits.crop; const nx = clampNum((e.clientX - rect.left) / rect.width, 0, 1); const ny = clampNum((e.clientY - rect.top) / rect.height, 0, 1); const frame = { x: view.x + nx * view.w, y: view.y + ny * view.h }; const source = frameToSource( frame, bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter, edits.crop.flipH, edits.crop.flipV, ); // Masks and heal spots live in the warped source space the shader samples. const warped = warpGeometryPoint(source, edits.geometry, bitmap.width, bitmap.height); return correctLensPoint(lensCorrection, warped.x, warped.y); }, [bitmap, edits.crop, edits.geometry, lensCorrection], ); /** Brush size on screen converted to a fraction of the source width. */ const brushRadius = useCallback(() => { const geo = geoRef.current; if (!bitmap || !geo.fitScale) return 0.02; return Math.max(0.0015, brushPx / 2 / (geo.fitScale * geo.zoomFactor * bitmap.width)); }, [bitmap, brushPx]); const commitHeal = useCallback( (spots: HealSpot[], label = 'Healing') => { setEdits({ heal: spots.slice(-MAX_HEAL_SPOTS) }, label); }, [setEdits], ); /** Places a new spot, borrowing a clean patch from the nearest free side. */ const makeSpot = useCallback( (src: { x: number; y: number }, r: number): HealSpot => { if (!bitmap) return { x: src.x, y: src.y, r, feather: healFeather, sx: src.x, sy: src.y }; const yRoom = (r * bitmap.width) / bitmap.height; const gap = r * 2.2; const fits = (p: { x: number; y: number }) => p.x > r * 1.1 && p.x < 1 - r * 1.1 && p.y > yRoom * 1.1 && p.y < 1 - yRoom * 1.1; const options = [ { x: src.x + gap, y: src.y }, { x: src.x - gap, y: src.y }, { x: src.x, y: src.y + gap }, { x: src.x, y: src.y - gap }, ]; const source = options.find(fits) ?? { x: src.x, y: src.y - gap }; return { x: src.x, y: src.y, r, feather: healFeather, sx: clampNum(source.x, 0, 1), sy: clampNum(source.y, 0, 1), }; }, [bitmap, healFeather], ); /** Distance from a point to a spot, measured in source-width units. */ const distanceToSpot = useCallback( (p: { x: number; y: number }, spot: HealSpot) => { if (!bitmap) return Infinity; const dy = (p.y - spot.y) * (bitmap.height / bitmap.width); return Math.hypot(p.x - spot.x, dy); }, [bitmap], ); const removeHealSpot = useCallback(() => { const spots = edits.heal ?? []; if (!spots.length) return; const index = healSelected ?? spots.length - 1; commitHeal(spots.filter((_, i) => i !== index)); setHealSelected(null); }, [commitHeal, edits.heal, healSelected]); const startHeal = (e: React.PointerEvent) => { if (!bitmap || e.button !== 0) return; const src = sourcePointFromEvent(e); if (!src) return; e.preventDefault(); const spots = edits.heal ?? []; let hit = -1; for (let i = spots.length - 1; i >= 0; i--) { if (distanceToSpot(src, spots[i]) <= spots[i].r * 1.15) { hit = i; break; } } e.currentTarget.setPointerCapture(e.pointerId); if (hit >= 0) { healDrag.current = { index: hit, mode: e.altKey ? 'source' : 'target', spot: { ...spots[hit] } }; setHealSelected(hit); if (e.altKey) setHealFeather(spots[hit].feather); return; } const spot = makeSpot(src, brushRadius()); let next = [...spots, spot]; let index = next.length - 1; if (next.length > MAX_HEAL_SPOTS) { next = next.slice(-MAX_HEAL_SPOTS); index = MAX_HEAL_SPOTS - 1; } commitHeal(next, 'Heal spot'); setHealSelected(index); healDrag.current = { index, mode: 'target', spot }; }; const moveHeal = (e: React.PointerEvent) => { if (!healMode) return; const src = sourcePointFromEvent(e); if (!src) return; setHealHover(src); const drag = healDrag.current; if (!drag) return; const spots = photo.edits.heal ?? []; const current = spots[drag.index]; if (!current) return; // Dragging the spot moves it with its sample; Alt-drag moves the sample. const patch: HealSpot = drag.mode === 'source' ? { ...current, sx: src.x, sy: src.y } : { ...current, x: clampNum(drag.spot.x + (src.x - drag.spot.x), 0, 1), y: clampNum(drag.spot.y + (src.y - drag.spot.y), 0, 1), sx: clampNum(drag.spot.sx + (src.x - drag.spot.x), 0, 1), sy: clampNum(drag.spot.sy + (src.y - drag.spot.y), 0, 1), }; const next = [...spots]; next[drag.index] = patch; commitHeal(next); }; const endHeal = (e: React.PointerEvent) => { healDrag.current = null; if (e.currentTarget.hasPointerCapture(e.pointerId)) { e.currentTarget.releasePointerCapture(e.pointerId); } }; const toggleHeal = useCallback(() => { setHealMode((v) => !v); setCropMode(false); setPicking(false); setLocalMode(false); setHealSelected(null); }, []); /* ------------------------------------------------------- local adjustments */ const localRadius = useCallback(() => { const geo = geoRef.current; if (!bitmap || !geo.fitScale) return 0.03; return Math.max(0.0015, localBrush / 2 / (geo.fitScale * geo.zoomFactor * bitmap.width)); }, [bitmap, localBrush]); const commitLocal = useCallback( (layers: LocalLayer[], label = 'Local adjustment') => { setEdits({ local: layers.slice(0, MAX_LOCAL_LAYERS) }, label); }, [setEdits], ); const patchLocal = useCallback( (id: string, patch: Partial, label = 'Local adjustment') => { commitLocal( (photo.edits.local ?? []).map((layer) => (layer.id === id ? { ...layer, ...patch } : layer)), label, ); }, [commitLocal, photo.edits.local], ); const addLocalLayer = useCallback( (kind: LocalMaskKind) => { const layers = edits.local ?? []; if (layers.length >= MAX_LOCAL_LAYERS) return; const layer = defaultLocalLayer(kind, layers.length); commitLocal([...layers, layer], 'Add local adjustment'); setLocalSelected(layer.id); setLocalMode(true); setCropMode(false); setHealMode(false); }, [commitLocal, edits.local], ); const addAutoMask = useCallback( async (kind: AutoMaskKind) => { const layers = edits.local ?? []; if (layers.length >= MAX_LOCAL_LAYERS || autoMaskBusy) return; setAutoMaskBusy(true); try { const source = bitmap ?? (await getBitmap(photo)); const raster = await buildAutoMask(source, kind); const layer = defaultLocalLayer('raster', layers.length); layer.name = `Auto ${kind}`; layer.raster = raster; layer.feather = 30; commitLocal([...layers, layer], `Auto ${kind} mask`); setLocalSelected(layer.id); setLocalMode(false); setCropMode(false); setHealMode(false); } catch (err) { setError(err instanceof Error ? err.message : 'Could not build the auto mask'); } finally { setAutoMaskBusy(false); } }, [autoMaskBusy, bitmap, commitLocal, edits.local, photo], ); const deleteLocalLayer = useCallback( (id: string) => { commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment'); setLocalSelected(null); setLocalMode(false); }, [commitLocal, edits.local], ); const duplicateLocalLayer = useCallback( (id: string) => { const layers = edits.local ?? []; if (layers.length >= MAX_LOCAL_LAYERS) return; const source = layers.find((layer) => layer.id === id); if (!source) return; const copy: LocalLayer = { ...cloneLocalLayer(source), id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, name: `${source.name} copy`, }; commitLocal([...layers, copy], 'Duplicate local adjustment'); setLocalSelected(copy.id); }, [commitLocal, edits.local], ); const copyLocalLayer = useCallback(() => { if (activeLocal) onLocalClipboard(cloneLocalLayer(activeLocal)); }, [activeLocal, onLocalClipboard]); const pasteLocalLayer = useCallback(() => { if (!localClipboard) return; const layers = edits.local ?? []; if (layers.length >= MAX_LOCAL_LAYERS) return; const copy: LocalLayer = { ...cloneLocalLayer(localClipboard), id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, name: `Local ${layers.length + 1}`, }; commitLocal([...layers, copy], 'Paste local adjustment'); setLocalSelected(copy.id); setLocalMode(true); setCropMode(false); setHealMode(false); }, [commitLocal, edits.local, localClipboard]); const toggleLocalMode = useCallback(() => { if (!activeLocal) return; setLocalMode((v) => !v); setCropMode(false); setHealMode(false); setPicking(false); }, [activeLocal]); const startLocalMask = (e: React.PointerEvent) => { if (!localMode || !activeLocal || !bitmap) return; const p = sourcePointFromEvent(e); if (!p) return; e.preventDefault(); e.currentTarget.setPointerCapture(e.pointerId); if (activeLocal.kind === 'brush') { const stroke: LocalStroke = { points: [p], size: localRadius(), erase: e.altKey }; localDrag.current = { id: activeLocal.id, mode: 'brush', stroke }; setLocalDraft(stroke); return; } if (activeLocal.kind === 'radial') { const aspect = bitmap.height / bitmap.width; const nx = (p.x - activeLocal.radial.cx) / Math.max(0.001, activeLocal.radial.rx); const ny = ((p.y - activeLocal.radial.cy) * aspect) / Math.max(0.001, activeLocal.radial.ry); const mode = Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65 ? 'edgeX' : Math.abs(ny) > 0.82 && Math.abs(nx) < 0.65 ? 'edgeY' : Math.hypot(nx, ny) > 0.82 ? 'edge' : 'center'; localDrag.current = { id: activeLocal.id, mode, stroke: null }; return; } const ds = Math.hypot(p.x - activeLocal.linear.x1, (p.y - activeLocal.linear.y1) * (bitmap.height / bitmap.width)); const de = Math.hypot(p.x - activeLocal.linear.x2, (p.y - activeLocal.linear.y2) * (bitmap.height / bitmap.width)); localDrag.current = { id: activeLocal.id, mode: ds <= de ? 'start' : 'end', stroke: null }; }; const moveLocalMask = (e: React.PointerEvent) => { if (!localMode || !bitmap) return; const p = sourcePointFromEvent(e); if (!p) return; setLocalHover(p); const drag = localDrag.current; if (!drag) return; const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id); if (!layer) return; if (drag.mode === 'brush' && drag.stroke) { const last = drag.stroke.points[drag.stroke.points.length - 1]; if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return; const stroke = { ...drag.stroke, points: [...drag.stroke.points, p].slice(-4000) }; drag.stroke = stroke; setLocalDraft(stroke); return; } if (drag.mode === 'center') { patchLocal(layer.id, { radial: { ...layer.radial, cx: p.x, cy: p.y } }, 'Move local mask'); } else if (drag.mode === 'edgeX') { patchLocal( layer.id, { radial: { ...layer.radial, rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5) } }, 'Resize local mask', ); } else if (drag.mode === 'edgeY') { patchLocal( layer.id, { radial: { ...layer.radial, ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5) } }, 'Resize local mask', ); } else if (drag.mode === 'edge') { patchLocal( layer.id, { radial: { ...layer.radial, rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5), ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5), }, }, 'Resize local mask', ); } else if (drag.mode === 'start') { patchLocal(layer.id, { linear: { ...layer.linear, x1: p.x, y1: p.y } }, 'Move local gradient'); } else if (drag.mode === 'end') { patchLocal(layer.id, { linear: { ...layer.linear, x2: p.x, y2: p.y } }, 'Move local gradient'); } }; const endLocalMask = (e: React.PointerEvent) => { const drag = localDrag.current; if (drag?.mode === 'brush' && drag.stroke?.points.length) { const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id); if (layer) { patchLocal( layer.id, { brush: { strokes: [...layer.brush.strokes, drag.stroke].slice(-300) } }, drag.stroke.erase ? 'Erase local mask' : 'Paint local mask', ); } } localDrag.current = null; setLocalDraft(null); if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId); }; // The feather slider edits the selected spot, and new spots inherit it. const setFeather = (value: number) => { setHealFeather(value); const spots = edits.heal ?? []; if (healSelected === null || !spots[healSelected]) return; const next = [...spots]; next[healSelected] = { ...next[healSelected], feather: value }; commitHeal(next); }; useEffect(() => { if (cropMode) setHealMode(false); }, [cropMode]); useEffect(() => { if (!healMode) { setHealHover(null); healDrag.current = null; } }, [healMode]); useEffect(() => { setLocalSelected(null); setLocalMode(false); setLocalDraft(null); localDrag.current = null; }, [photo.id]); useEffect(() => { if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) { setLocalSelected(null); setLocalMode(false); } }, [edits.local, localSelected]); // Escape cancels the picker without touching the edit. useEffect(() => { if (!picking) return; const onKey = (e: KeyboardEvent) => { if (e.key !== 'Escape') return; e.preventDefault(); e.stopPropagation(); setPicking(false); }; window.addEventListener('keydown', onKey, true); return () => window.removeEventListener('keydown', onKey, true); }, [picking]); useEffect(() => { if (cropMode) setPicking(false); }, [cropMode]); // Full-screen loupe: the stage itself goes fullscreen, so the browser hides // every panel and the canvas simply gets the whole screen. useEffect(() => { const onFs = () => { const on = !!document.fullscreenElement; setLoupe(on); if (!on) setAdjustOpen(false); }; document.addEventListener('fullscreenchange', onFs); return () => document.removeEventListener('fullscreenchange', onFs); }, []); const toggleLoupe = useCallback(() => { const el = stageRef.current; if (document.fullscreenElement) { setAdjustOpen(false); void document.exitFullscreen().catch(() => undefined); return; } setAdjustOpen(false); if (el?.requestFullscreen) void el.requestFullscreen().catch(() => undefined); }, []); const toggleZoom = (x?: number, y?: number) => { if (cropMode) return; if (zoomed) applyZoom('fit'); else applyZoom(100, x !== undefined && y !== undefined ? { x, y } : undefined); }; const historyPosition = photo.history.findIndex((entry) => entry.edits === photo.edits); const canUndo = historyPosition > 0 || (historyPosition < 0 && photo.history.length > 1); const canRedo = historyPosition >= 0 && historyPosition < photo.history.length - 1; 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]); const redo = useCallback(() => { const hist = photo.history; const idx = hist.findIndex((h) => h.edits === photo.edits); const target = idx >= 0 ? hist[idx + 1] : undefined; 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; } // Ratings, labels and flags work here exactly as they do in the grid, so a // shoot can be culled without leaving Develop. if (/^[0-5]$/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) { onUpdate(photo.id, { rating: Number(e.key) }); e.preventDefault(); return; } if (/^[6-9]$/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) { const labels: ColorLabel[] = ['red', 'yellow', 'green', 'blue']; onUpdate(photo.id, { color: labels[Number(e.key) - 6] }); e.preventDefault(); return; } if (e.key.toLowerCase() === 'j' && !e.metaKey && !e.ctrlKey && !e.altKey) { e.preventDefault(); setClipping((cur) => e.shiftKey ? cur === 'shadows' ? null : 'shadows' : cur === 'highlights' ? null : 'highlights', ); return; } if (!e.metaKey && !e.ctrlKey && !e.altKey) { const flagKey = e.key.toLowerCase(); if (flagKey === 'p' || flagKey === 'x' || flagKey === 'u') { onUpdate(photo.id, { flag: flagKey === 'p' ? 'pick' : flagKey === 'x' ? 'reject' : 'none' }); e.preventDefault(); return; } } if (e.key === 'ArrowRight') { navigateFilm(1); e.preventDefault(); } else if (e.key === 'ArrowLeft') { navigateFilm(-1); e.preventDefault(); } else if (e.key.toLowerCase() === 'q' && !e.metaKey && !e.ctrlKey && !e.altKey) { toggleHeal(); 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.toLowerCase() === 'f' && !e.metaKey && !e.ctrlKey) { toggleLoupe(); e.preventDefault(); } else if (e.key.toLowerCase() === 'm' && !e.metaKey && !e.ctrlKey && !e.altKey) { if (activeLocal) { toggleLocalMode(); e.preventDefault(); } } else if (e.key === 'Enter' && cropMode) { setCropMode(false); } else if (e.key === 'Escape') { // In fullscreen the browser handles Escape; don't also leave Develop. if (document.fullscreenElement) return; if (localMode) setLocalMode(false); else if (healMode) setHealMode(false); else if (cropMode) setCropMode(false); else onExit(); } else if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'z') { redo(); e.preventDefault(); } 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(filmSel); } }; 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, localMode, activeLocal, toggleLocalMode, healMode, onExit, navigateFilm, onCopy, onPaste, filmSel, undo, redo, applyZoom, zoomed, onUpdate, photo.id, toggleLoupe, toggleHeal, ]); 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]); // The same panel stack is used by the regular right rail and the fullscreen // loupe overlay. Metadata stays in the rail so the overlay is purely tonal. const adjustmentPanels = (includeMetadata: boolean) => ( <> {cropMode && ( setEdits({ crop: { ...edits.crop, flipH: !edits.crop.flipH } }, 'Flip horizontal') } mirrored={edits.crop.flipH} /> )} setLocalSelected(id)} onAdd={addLocalLayer} onDelete={deleteLocalLayer} onDuplicate={duplicateLocalLayer} onEditMask={toggleLocalMode} maskMode={localMode} brushSize={localBrush} onBrushSize={setLocalBrush} onCopyLayer={copyLocalLayer} onPasteLayer={pasteLocalLayer} canPaste={Boolean(localClipboard)} onAutoMask={(kind) => void addAutoMask(kind)} autoBusy={autoMaskBusy} /> {includeMetadata && ( onUpdate(photo.id, patch)} presets={metadataPresets} keywordLibrary={keywordLibrary} onSavePreset={onSaveMetadataPreset} onDeletePreset={onDeleteMetadataPreset} /> )} ); 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([photo.id]), disabled: !clipboard }, { label: 'Reset settings', onSelect: resetAll }, 'separator', ...(canPushImmich && onPushImmich ? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[]) : []), ...(onOpenImmich ? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[]) : []), { label: 'Export…', onSelect: onExport }, { label: 'Delete photo…', danger: true, onSelect: onDelete }, ]; // Right-clicking one of several selected frames acts on the whole selection; // right-clicking outside it acts on that frame alone. const filmMenuIds = menu?.kind === 'film' && menu.ids?.length ? menu.ids : [photo.id]; const filmMenu: MenuEntry[] = [ { label: 'Open in Develop', disabled: filmMenuIds.includes(photo.id), onSelect: () => onSelect(filmMenuIds[0]), }, 'separator', { label: 'Copy settings', onSelect: () => (onCopyOf ? onCopyOf(filmMenuIds[0]) : onCopy()), }, { label: filmMenuIds.length > 1 ? `Paste settings to ${filmMenuIds.length} photos…` : 'Paste settings', onSelect: () => onPaste(filmMenuIds), disabled: !clipboard, }, { label: filmMenuIds.length > 1 ? `Reset adjustments on ${filmMenuIds.length} photos` : 'Reset settings', onSelect: () => filmMenuIds.length > 1 && onResetSelection ? onResetSelection(filmMenuIds) : resetAll(), }, 'separator', ...(canPushImmich && onPushImmich ? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[]) : []), ...(onOpenImmich ? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[]) : []), { 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 })} />
{!mobile && !tipDismissed && (
Hover a panel seam to collapse it · ⌘K searches everything · ? shows shortcuts
)} {mobile && ( <>
{photo.name} {filmPosition >= 0 ? filmPosition + 1 : '–'} / {filmPhotos.length}
onUpdate(photo.id, { rating })} size="md" /> onUpdate(photo.id, { flag })} /> {photo.meta.camera ?? 'Camera'} {photo.meta.focal ? `· ${photo.meta.focal}mm` : ''}
)}
{ e.preventDefault(); setMenu({ x: e.clientX, y: e.clientY, kind: 'canvas' }); }} > {error ? (
{error}
) : (
{ if (localMode) startLocalMask(e); else if (healMode) startHeal(e); else beginPan(e); }} onPointerMove={(e) => { if (localMode) moveLocalMask(e); else if (healMode) moveHeal(e); else movePan(e); }} onPointerUp={(e) => { if (localMode) endLocalMask(e); else if (healMode) endHeal(e); else endPan(e); }} onPointerCancel={(e) => { if (localMode) endLocalMask(e); else if (healMode) endHeal(e); else endPan(e); }} onPointerLeave={() => { setHealHover(null); setLocalHover(null); }} onDoubleClick={(e) => { if (healMode || localMode) return; toggleZoom(e.clientX, e.clientY); }} /> {lensSplit && lensCorrection && !showOriginal && (
Before After
)} {healMode && bitmap && (() => { const geo = geoRef.current; const view = geo.view; const marker = (p: { x: number; y: number }) => { const f = sourceToFrame( unwarpGeometryPoint( uncorrectLensPoint(lensCorrection, p.x, p.y), edits.geometry, bitmap.width, bitmap.height, ), bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter, edits.crop.flipH, edits.crop.flipV, ); return { x: ((f.x - view.x) / view.w) * 100, y: ((f.y - view.y) / view.h) * 100, }; }; const rx = (r: number) => ((r * bitmap.width) / (frame.w * view.w)) * 100; const ry = (r: number) => ((r * bitmap.width) / (frame.h * view.h)) * 100; const spots = edits.heal ?? []; const hoverR = brushRadius(); return ( {spots.map((spot, i) => { const t = marker(spot); const s = marker({ x: spot.sx, y: spot.sy }); const on = i === healSelected; // Matches the shader: feather acts on the outer half at most. const inner = Math.max(0, 1 - (spot.feather / 100) * 0.5); return ( {on && } {on && ( )} {inner > 0.02 && ( )} ); })} {healHover && !healDrag.current && ( )} ); })()} {localMode && bitmap && activeLocal && (() => { const geo = geoRef.current; const view = geo.view; const marker = (p: { x: number; y: number }) => { const source = unwarpGeometryPoint( uncorrectLensPoint(lensCorrection, p.x, p.y), edits.geometry, bitmap.width, bitmap.height, ); const f = sourceToFrame( source, bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter, edits.crop.flipH, edits.crop.flipV, ); return { x: ((f.x - view.x) / view.w) * 100, y: ((f.y - view.y) / view.h) * 100, }; }; const xScale = bitmap.width / (frame.w * view.w); const canvasEl = canvasRef.current; const canvasW = canvasEl?.clientWidth || 1; const canvasH = canvasEl?.clientHeight || 1; const strokes = localDraft ? [...activeLocal.brush.strokes, localDraft] : activeLocal.brush.strokes; return ( {activeLocal.kind === 'brush' && strokes.map((stroke, i) => { if (!stroke.points.length) return null; const points = stroke.points.map(marker).map((p) => `${p.x},${p.y}`).join(' '); const width = Math.max(1, stroke.size * 2 * canvasW); return ( ); })} {activeLocal.kind === 'radial' && (() => { const c = marker({ x: activeLocal.radial.cx, y: activeLocal.radial.cy }); const edge = marker({ x: activeLocal.radial.cx + activeLocal.radial.rx, y: activeLocal.radial.cy, }); const edgeY = marker({ x: activeLocal.radial.cx, y: activeLocal.radial.cy + activeLocal.radial.ry, }); // Sample the perimeter so the guide follows the same warp // as the picture instead of staying a screen-space ellipse. const ring = Array.from({ length: 72 }, (_, i) => { const angle = (i / 72) * Math.PI * 2; const p = marker({ x: activeLocal.radial.cx + Math.cos(angle) * activeLocal.radial.rx, y: activeLocal.radial.cy + Math.sin(angle) * activeLocal.radial.ry, }); return `${p.x},${p.y}`; }).join(' '); return ( ); })()} {activeLocal.kind === 'linear' && (() => { const a = marker({ x: activeLocal.linear.x1, y: activeLocal.linear.y1 }); const b = marker({ x: activeLocal.linear.x2, y: activeLocal.linear.y2 }); return ( ); })()} {activeLocal.kind === 'brush' && localHover && !localDrag.current && ( )} ); })()} {cropMode && bitmap && ( setEdits({ crop: { ...photo.edits.crop, ...rect } }, 'Crop')} onDragChange={setCropDrag} /> )}
)} {localMode && activeLocal && !error && (
Local · {activeLocal.kind} {activeLocal.kind === 'brush' && ( <> {Math.round(localBrush)}px )} {activeLocal.kind !== 'linear' && ( <> {Math.round(activeLocal.feather)}% )} {activeLocal.kind === 'brush' ? 'Paint the mask · Alt paints an erase stroke · wheel sizes the brush' : activeLocal.kind === 'radial' ? 'Drag the centre or the edge handle · wheel zooms' : 'Drag either end of the gradient'}
)} {healMode && !error && (
Healing {brushPx}px {healFeather}% {(edits.heal ?? []).length} spot{(edits.heal ?? []).length === 1 ? '' : 's'} Click a blemish · Alt-drag moves the sample · wheel sizes the brush
)} {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
} {loupe && !cropMode && (
{filmPosition >= 0 ? filmPosition + 1 : '–'} / {filmPhotos.length} {filmFilterActive && filtered}
onUpdate(photo.id, { rating })} size="md" /> onUpdate(photo.id, { flag })} />
)} {clipPreview && (
red green blue two channels all three
)} {loupe && !adjustOpen && ( )} {loupe && adjustOpen && ( )}
Rating {[0, 1, 2, 3, 4, 5].map((n) => ( ))}
Flag {(['any', 'pick', 'none', 'reject'] as const).map((value) => ( ))}
{filmFilterActive && ( )} {filmFilterActive && !currentInFilm && ( <> Current photo is hidden by this filter )}
{filmSel.length > 1 && ( {filmSel.length} selected )} {filmPhotos.length} / {photos.length}
{shownStripOpen && (
{filmPhotos.map((p) => ( ))} {!filmPhotos.length && (
No photos match this filter.
)}
)}
{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} /> )}
); }