import { useEffect, useMemo, useRef, useState } from 'react'; import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_LAYERS } from '../lib/edits'; import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto'; import { autoNoiseFor } from '../lib/noiseProfile'; import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api'; import { clamp } from '../lib/curves'; import type { CurveChannel, Edits, EventRecord, HistoryEntry, LocalLayer, LocalMaskKind, MetadataPreset, PhotoRecord, Preset, Snapshot, } from '../types'; import CurveEditor from './CurveEditor'; import { getBitmap } from '../lib/images'; import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer'; import { applyFilmVariant, FILM_VARIANTS, PRESET_CATEGORIES, type FilmVariant } from '../lib/presets'; import { usePersistentState } from '../lib/usePersistentState'; import { clearPersistedProofProfile, loadProofProfile, persistProofProfile, setActiveProofCube, type SoftProofCube, } from '../lib/softProof'; import { dcpRgbCam, parseDcp } from '../lib/dcp'; import { loadSavedCameraProfiles, removeCameraProfile, saveCameraProfile, savedProfilesForCamera, type SavedCameraProfile, } from '../lib/dcpLibrary'; import { usePresetThumbs } from './PresetThumbs'; import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensDb'; import { getCameraLensDefault, removeCameraLensDefault, saveCameraLensDefault, type CameraLensDefault, } from '../lib/lensDefaults'; import type { LensProfile } from '../types'; import LensDefaultsModal from './LensDefaultsModal'; import LensCalibrationModal from './LensCalibrationModal'; import { TEAM_PREFIX } from '../lib/lensProfiles'; import Slider from './Slider'; export function Panel({ title, children, defaultOpen = true, right, }: { title: string; children: React.ReactNode; defaultOpen?: boolean; right?: React.ReactNode; }) { const [open, setOpen] = useState(defaultOpen); return (
{right}
{open &&
{children}
}
); } export interface PanelSetProps { edits: Edits; photo: PhotoRecord; set: (patch: Partial, label: string) => void; } const HUE_TRACK = 'linear-gradient(90deg,#ff4d4d,#ffd24d,#6dff6d,#4dfff0,#4d8bff,#c44dff,#ff4dd2,#ff4d4d)'; export function BasicPanel({ edits, photo, set, picker = false, onPicker, }: PanelSetProps & { picker?: boolean; onPicker?: (active: boolean) => void }) { const [autoBusy, setAutoBusy] = useState(false); const [wbBusy, setWbBusy] = useState(false); const auto = async () => { setAutoBusy(true); try { const partial = await computeAutoEdits(photo.thumb); set(partial, 'Auto tone'); } finally { setAutoBusy(false); } }; const autoWb = async () => { setWbBusy(true); try { set(await computeAutoWhiteBalance(photo.thumb), 'Auto white balance'); } finally { setWbBusy(false); } }; return (
White balance
{edits.kelvin == null ? ( set({ temp: v }, 'Temperature')} track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)" /> ) : ( set({ kelvin: v }, 'Kelvin temperature')} format={(v) => `${Math.round(v)} K`} track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)" /> )} set({ tint: v }, 'Tint')} track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)" />
Tone
set({ exposure: v }, 'Exposure')} format={(v) => v.toFixed(2)} previewClipping /> set({ recovery: v }, 'Recovery')} previewClipping /> set({ contrast: v }, 'Contrast')} /> set({ highlights: v }, 'Highlights')} /> set({ shadows: v }, 'Shadows')} /> set({ whites: v }, 'Whites')} /> set({ blacks: v }, 'Blacks')} />
Presence
set({ texture: v }, 'Texture')} /> set({ clarity: v }, 'Clarity')} /> set({ dehaze: v }, 'Dehaze')} /> set({ vibrance: v }, 'Vibrance')} /> set({ saturation: v }, 'Saturation')} /> set({ redscale: v }, 'Redscale')} track="linear-gradient(90deg,#a8b6c6,#d96b34,#8f1d12)" /> {edits.bw && ( <>
B&W filter
{BW_FILTERS.map((f) => ( ))}
{edits.bwFilter !== 'none' && ( set({ bwFilterAmount: v }, 'B&W filter strength')} /> )}
A filter darkens the colors it absorbs: red drops blue skies, green lifts foliage. The color mixer below tunes individual hues on top.
)}
); } const CURVE_COLORS: Record = { rgb: '#e9e9ec', red: '#e06a6a', green: '#6ecf7d', blue: '#6f9de8', }; export function CurvePanel({ edits, set }: PanelSetProps) { const [channel, setChannel] = useState('rgb'); const points = edits.curve[channel]; const update = (next: typeof points) => set({ curve: { ...edits.curve, [channel]: next } }, `Curve ${channel.toUpperCase()}`); return ( set( { curve: { ...edits.curve, [channel]: identityCurve() }, levels: { black: 0, white: 100, gamma: 1 }, parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 }, }, 'Reset tone curve', ) } > Reset } >
Input levels
set({ levels: { ...edits.levels, black: Math.min(v, edits.levels.white - 5) } }, 'Black point') } format={(v) => `${Math.round(v)}`} /> set({ levels: { ...edits.levels, white: Math.max(v, edits.levels.black + 5) } }, 'White point') } format={(v) => `${Math.round(v)}`} /> set({ levels: { ...edits.levels, gamma: v } }, 'Midtone gamma')} format={(v) => v.toFixed(2)} def={1} />
{(['rgb', 'red', 'green', 'blue'] as CurveChannel[]).map((c) => ( ))}
set( { parametric: { ...edits.parametric, [key]: value } }, `Parametric ${key}`, ) } />
Parametric
set({ parametric: { ...edits.parametric, highlights: v } }, 'Parametric highlights')} /> set({ parametric: { ...edits.parametric, lights: v } }, 'Parametric lights')} /> set({ parametric: { ...edits.parametric, darks: v } }, 'Parametric darks')} /> set({ parametric: { ...edits.parametric, blacks: v } }, 'Parametric blacks')} />
); } export function HslPanel({ edits, set }: PanelSetProps) { const [band, setBand] = useState(0); const active = HUE_BANDS[band]; const setBandValue = (kind: 'hue' | 'sat' | 'lum', value: number) => { const arr = [...edits.hsl[kind]]; arr[band] = value; const label = kind === 'hue' ? 'Hue' : kind === 'sat' ? 'Saturation' : 'Luminance'; set({ hsl: { ...edits.hsl, [kind]: arr } }, `${label} · ${active.name}`); }; return ( set( { hsl: { hue: HUE_BANDS.map(() => 0), sat: HUE_BANDS.map(() => 0), lum: HUE_BANDS.map(() => 0) } }, 'Reset color mixer', ) } > Reset } >
{HUE_BANDS.map((b, i) => (
{active.name}
setBandValue('hue', v)} track={HUE_TRACK} /> setBandValue('sat', v)} /> setBandValue('lum', v)} />
Shift, saturate or brighten one color range without touching the rest.
); } export function ColorGradingPanel({ edits, set }: PanelSetProps) { return (
Shadows
set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, h: v } } }, 'Grading shadows hue')} track={HUE_TRACK} /> set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, s: v } } }, 'Grading shadows')} />
Highlights
set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, h: v } } }, 'Grading highlights hue') } track={HUE_TRACK} /> set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, s: v } } }, 'Grading highlights')} /> set({ grading: { ...edits.grading, balance: v } }, 'Grading balance')} />
); } /** * 1:1 loupe of the grain. A small window of the real crop is rendered at actual * pixels, which is the only way to judge a resolution independent grain size * without exporting: this is what the file looks like at 100%. */ function GrainPatch({ photo, edits, freezeGrain, }: { photo: PhotoRecord; edits: Edits; freezeGrain?: boolean; }) { const ref = useRef(null); const renderer = useRef(null); const bitmap = useRef(null); const [ready, setReady] = useState(false); useEffect(() => { let alive = true; getBitmap(photo) .then((bmp) => { if (!alive) return; bitmap.current = bmp; setReady(true); }) .catch(() => undefined); return () => { alive = false; }; }, [photo.id]); useEffect( () => () => { renderer.current?.dispose(); renderer.current = null; }, [], ); useEffect(() => { const canvas = ref.current; const bmp = bitmap.current; if (!canvas || !bmp) return; const dpr = Math.min(window.devicePixelRatio || 1, 2); const frame = rotatedBounds(bmp.width, bmp.height, edits.crop.angle, edits.crop.quarter); // The patch takes the shape of the framed area, so it reads as a window onto // the crop rather than a generic swatch. const cropPxW = Math.max(1, frame.w * edits.crop.w); const cropPxH = Math.max(1, frame.h * edits.crop.h); const cssW = 148; const cssH = Math.round(Math.min(148, Math.max(64, 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 (!renderer.current) renderer.current = new Renderer(canvas); const r = renderer.current; r.setImage(bmp); // One source pixel per device pixel, centred on whatever the crop frames: // drag the crop rectangle and the patch samples that part of the photo. const view = grainSampleWindow(frame, edits.crop, W, H); r.render(edits, { width: W, height: H, view, freezeGrain }); } catch { // Keep the last good frame rather than blanking the patch. } }, [photo.id, ready, edits, freezeGrain]); return (
Grain at 100% · inside the crop
); } export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps & { grainFreeze?: boolean }) { return (
Vignette
set({ vignette: { ...edits.vignette, amount: v } }, 'Vignette amount')} /> set({ vignette: { ...edits.vignette, midpoint: v } }, 'Vignette midpoint')} /> set({ vignette: { ...edits.vignette, feather: v } }, 'Vignette feather')} />
Grain
set({ grain: { ...edits.grain, amount: v } }, 'Grain amount')} /> set({ grain: { ...edits.grain, size: v } }, 'Grain size')} /> set({ grain: { ...edits.grain, roughness: v } }, 'Grain roughness')} />
); } export function DetailPanel({ edits, photo, set }: PanelSetProps) { const [aiBusy, setAiBusy] = useState(false); const [aiNote, setAiNote] = useState(null); const aiActive = Boolean(edits.aiDenoise.key); // Poll rather than stream: the job is seconds long, and a failed poll just // leaves the previous note on screen instead of breaking the panel. const generateAi = async () => { if (aiBusy) return; setAiBusy(true); setAiNote('Rendering the denoised version on the server…'); try { const { jobId } = await startDenoise(photo.id); for (let attempt = 0; attempt < 180; attempt++) { await new Promise((resolve) => setTimeout(resolve, 1000)); const job = await getDenoiseJob(jobId); if (job.state === 'done') { set({ aiDenoise: { ...edits.aiDenoise, key: job.key } }, 'AI denoise'); // The pipeline tapers itself down on frames it measures as clean. That // taper is in the rendered file now, so report it -- the Amount slider // multiplies it rather than replacing it. const applied = job.stats?.autoGate ?? 1; const base = job.cached ? 'Using the cached version' : job.ms != null ? `Cleaned in ${(job.ms / 1000).toFixed(1)}s` : 'Denoise ready'; setAiNote( applied < 0.95 ? `${base} · clean frame, correction reduced to ${Math.round(applied * 100)}%` : base, ); return; } if (job.state === 'error') { setAiNote(job.error ?? 'Denoise failed'); return; } } setAiNote('Denoise is still running — try again in a moment'); } catch (err) { setAiNote(err instanceof Error ? err.message : 'Denoise failed'); } finally { setAiBusy(false); } }; return (
Sharpening
set({ sharpen: { ...edits.sharpen, amount: v } }, 'Sharpen amount')} /> set({ sharpen: { ...edits.sharpen, radius: v } }, 'Sharpen radius')} format={(v) => v.toFixed(1)} def={1} /> set({ sharpen: { ...edits.sharpen, detail: v } }, 'Sharpen detail')} /> set({ sharpen: { ...edits.sharpen, mask: v } }, 'Sharpen masking')} /> set({ sharpen: { ...edits.sharpen, lensSoftness: v } }, 'Lens softness')} format={(v) => `${Math.round(v)}`} />

Edge-aware sharpening for lenses that soften towards the corners.

Noise reduction
set({ noise: { ...edits.noise, luminance: v } }, 'Noise reduction')} /> set({ noise: { ...edits.noise, detail: v } }, 'Noise detail')} /> set({ noise: { ...edits.noise, chroma: v } }, 'Color noise reduction')} /> set({ noise: { ...edits.noise, chromaDetail: v } }, 'Color detail')} />
AI denoise
{aiActive ? ( set({ aiDenoise: { ...edits.aiDenoise, amount: v } }, 'AI denoise amount')} /> ) : null}

{aiNote ?? (aiActive ? 'Detail-preserving denoise, rendered from the full proxy.' : 'Removes noise only where there is no structure to keep.')}

{aiActive ? ( ) : null}
Defringe
set({ defringe: { ...edits.defringe, purple: v } }, 'Purple fringe')} /> set({ defringe: { ...edits.defringe, green: v } }, 'Green fringe')} />
); } const ALL = 'All'; const FAVOURITES = 'Favourites'; const MY_PRESETS = 'My presets'; function presetCategory(preset: Preset): string { if (preset.custom || preset.group === 'User presets') return MY_PRESETS; return preset.category ?? 'Essentials'; } /** Film tiles drop the brand, since the group header already names it. */ function shortName(preset: Preset): string { if (!preset.film) return preset.name; const prefix = `${preset.group} `; return preset.name.startsWith(prefix) ? preset.name.slice(prefix.length) : preset.name; } const FILM_CATEGORIES = ['Colour Negative', 'Colour Slide', 'Black & White', 'Cinema', 'Instant', 'Redscale', 'Experimental']; /** * Category picker for the preset browser. This is a plain menu rather than a * native setQuery(event.target.value)} onKeyDown={(event) => { if (event.key === 'Escape') setQuery(''); }} /> {query && ( )} {hasFilm && (
{FILM_VARIANTS.map((v) => ( ))}
)}
{!shown.length && (
{validFilter === FAVOURITES ? 'No favourites yet — hover a preset and click the star.' : 'No presets match this search.'}
)} {groups.map(([group, items]) => { const isCollapsed = collapsed.includes(group); return (
{!isCollapsed && (
{items.map((preset) => { const src = thumbs[preset.id]; const favourite = favourites.includes(starId(preset)); return (
{onDelete && presetCategory(preset) === MY_PRESETS && ( )}
); })}
)}
); })}
{focused && (
{focused.name} {focused.description && {focused.description}} {[focused.film?.process, focused.film?.speed ? `ISO ${focused.film.speed}` : null, focused.group] .filter(Boolean) .join(' · ')}
)} ); } export function HistoryPanel({ history, onRestore }: { history: HistoryEntry[]; onRestore: (edits: Edits) => void }) { return (
History {history.length}
{[...history].reverse().map((entry, i) => ( ))}
); } export function SnapshotsPanel({ snapshots, onSave, onRestore, onDelete, }: { snapshots: Snapshot[]; onSave: (name: string) => void; onRestore: (snapshot: Snapshot) => void; onDelete: (snapshot: Snapshot) => void; }) { return (
Snapshots
{snapshots.length ? (
{[...snapshots].reverse().map((snapshot) => (
))}
) : (

Save a named look before trying another treatment. Snapshots stay with this photo and its virtual copies.

)}
); } export function CropPanel({ edits, set, onAspect, onRotate, onFlipPreview, mirrored, }: { edits: Edits; set: PanelSetProps['set']; frame: { w: number; h: number }; onAspect: (id: string) => void; onRotate: (dir: -1 | 1) => void; onFlipPreview?: () => void; mirrored?: boolean; }) { const crop = edits.crop; return (
{onFlipPreview && ( )}
{ASPECTS.map((a) => ( ))}
set({ crop: { ...crop, angle: v } }, 'Straighten')} format={(v) => `${v.toFixed(1)}°`} />
); } interface NavigatorRect { x: number; y: number; w: number; h: number; } export function NavigatorPanel({ photo, content, view, zoomed, zoomLabel, onNavigate, }: { photo: PhotoRecord; content: NavigatorRect; view: NavigatorRect | null; zoomed: boolean; zoomLabel: string; onNavigate: (x: number, y: number) => void; }) { const canvasRef = useRef(null); const frameRef = useRef(null); const dragRef = useRef(false); const thumbSrc = photo.thumbUrl ?? photo.thumb; const [thumb, setThumb] = useState(null); const [boxWidth, setBoxWidth] = useState(0); useEffect(() => { let alive = true; const image = new Image(); image.decoding = 'async'; image.onload = () => { if (alive) setThumb(image); }; image.src = thumbSrc; return () => { alive = false; image.onload = null; }; }, [thumbSrc]); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const measure = () => setBoxWidth(canvas.clientWidth); measure(); const observer = new ResizeObserver(measure); observer.observe(canvas); return () => observer.disconnect(); }, []); useEffect(() => { const canvas = canvasRef.current; if (!canvas || !boxWidth || !thumb) return; const dpr = Math.min(window.devicePixelRatio || 1, 2); const cssW = boxWidth; const cssH = (boxWidth * 3) / 4; const pixelsW = Math.max(1, Math.round(cssW * dpr)); const pixelsH = Math.max(1, Math.round(cssH * dpr)); if (canvas.width !== pixelsW || canvas.height !== pixelsH) { canvas.width = pixelsW; canvas.height = pixelsH; } const ctx = canvas.getContext('2d'); if (!ctx) return; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, cssW, cssH); ctx.fillStyle = '#0d0d10'; ctx.fillRect(0, 0, cssW, cssH); const crop = photo.edits.crop; const frame = rotatedBounds(photo.width || 1, photo.height || 1, crop.angle, crop.quarter); const inset = 7; const scale = Math.min((cssW - inset * 2) / frame.w, (cssH - inset * 2) / frame.h); const frameW = frame.w * scale; const frameH = frame.h * scale; const left = (cssW - frameW) / 2; const top = (cssH - frameH) / 2; frameRef.current = { x: left, y: top, w: frameW, h: frameH }; // The canvas miniature follows the same orientation order as the main // renderer: flips on the photo, then the quarter turns and straighten. ctx.save(); ctx.translate(left + frameW / 2, top + frameH / 2); ctx.rotate(((crop.quarter * 90 + crop.angle) * Math.PI) / 180); ctx.scale(crop.flipH ? -1 : 1, crop.flipV ? -1 : 1); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; ctx.drawImage( thumb, (-(photo.width || 1) * scale) / 2, (-(photo.height || 1) * scale) / 2, (photo.width || 1) * scale, (photo.height || 1) * scale, ); ctx.restore(); const cropX = left + content.x * frameW; const cropY = top + content.y * frameH; const cropW = content.w * frameW; const cropH = content.h * frameH; // Dim the part of the photo outside the crop so the navigator reads like // an overview, while the white box marks the pixels currently on screen. ctx.fillStyle = 'rgba(5, 5, 8, 0.58)'; if (cropY > top) ctx.fillRect(left, top, frameW, cropY - top); if (cropY + cropH < top + frameH) { ctx.fillRect(left, cropY + cropH, frameW, top + frameH - cropY - cropH); } if (cropX > left) ctx.fillRect(left, cropY, cropX - left, cropH); if (cropX + cropW < left + frameW) { ctx.fillRect(cropX + cropW, cropY, left + frameW - cropX - cropW, cropH); } const shown = view ?? content; const viewX = left + shown.x * frameW; const viewY = top + shown.y * frameH; const viewW = shown.w * frameW; const viewH = shown.h * frameH; ctx.fillStyle = 'rgba(255, 255, 255, 0.07)'; ctx.fillRect(viewX, viewY, viewW, viewH); ctx.strokeStyle = 'rgba(255, 255, 255, 0.35)'; ctx.lineWidth = 1; ctx.strokeRect(cropX + 0.5, cropY + 0.5, Math.max(0, cropW - 1), Math.max(0, cropH - 1)); ctx.strokeStyle = zoomed ? '#f4f4f7' : 'rgba(244, 244, 247, 0.78)'; ctx.lineWidth = zoomed ? 2 : 1.25; ctx.setLineDash(zoomed ? [] : [4, 3]); ctx.strokeRect(viewX + 1, viewY + 1, Math.max(0, viewW - 2), Math.max(0, viewH - 2)); ctx.setLineDash([]); }, [boxWidth, thumb, photo.width, photo.height, photo.edits.crop, content, view, zoomed]); const locate = (event: React.PointerEvent) => { const canvas = canvasRef.current; const frame = frameRef.current; if (!canvas || !frame) return null; const rect = canvas.getBoundingClientRect(); if (!rect.width || !rect.height) return null; return { x: Math.min(1, Math.max(0, (event.clientX - rect.left - frame.x) / frame.w)), y: Math.min(1, Math.max(0, (event.clientY - rect.top - frame.y) / frame.h)), }; }; const endDrag = (event: React.PointerEvent) => { dragRef.current = false; if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } }; return (
Navigator {zoomLabel}
{ if (event.button !== 0) return; const point = locate(event); if (!point) return; dragRef.current = true; event.currentTarget.setPointerCapture(event.pointerId); onNavigate(point.x, point.y); }} onPointerMove={(event) => { if (!dragRef.current) return; const point = locate(event); if (point) onNavigate(point.x, point.y); }} onPointerUp={endDrag} onPointerCancel={endDrag} />
{photo.name}
{photo.raw ? (photo.decode === 'embedded' ? 'Raw · camera preview' : 'Raw · demosaiced') : 'JPEG/PNG'}{' '} · {photo.width}×{photo.height}
); } const LOCAL_ICON: Record = { brush: '✎', linear: '▤', radial: '◉', raster: '✦' }; export function LocalPanel({ edits, set, activeId, onSelect, onAdd, onDelete, onDuplicate, onEditMask, maskMode, brushSize, onBrushSize, onCopyLayer, onPasteLayer, canPaste, onAutoMask, onSampleRange, autoBusy, }: PanelSetProps & { activeId: string | null; onSelect: (id: string) => void; onAdd: (kind: LocalMaskKind) => void; onDelete: (id: string) => void; onDuplicate: (id: string) => void; onEditMask: () => void; maskMode: boolean; brushSize: number; onBrushSize: (value: number) => void; onCopyLayer: () => void; onPasteLayer: () => void; canPaste: boolean; onAutoMask: (kind: 'subject' | 'sky' | 'background') => void; /** Arms the canvas click that samples a colour range for the active layer. */ onSampleRange: () => void; autoBusy?: boolean; }) { const layers = edits.local ?? []; const active = layers.find((layer) => layer.id === activeId) ?? null; const patch = (next: Partial, label: string) => { if (!active) return; set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label); }; const adjust = (key: keyof LocalLayer['adjust'], value: number) => active && patch({ adjust: { ...active.adjust, [key]: value } }, `Local ${key}`); const range = (key: keyof LocalLayer['range'], value: number | boolean) => active && patch({ range: { ...active.range, [key]: value } }, 'Local range'); return ( {layers.length}/{MAX_LOCAL_LAYERS}}>
{layers.length === 0 ? (

Add a layer to dodge, burn or colour part of the frame. Masks follow the photo through crops and lens correction.

) : ( <>
{layers.map((layer) => ( ))}
{active && ( <>
{active.kind === 'raster' && (

Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above.

)} {active.kind === 'brush' && ( `${Math.round(v)}px`} /> )} {active.kind !== 'linear' && ( patch({ feather: v }, 'Local feather')} format={(v) => `${Math.round(v)}%`} /> )}
Combine
{(['add', 'subtract', 'intersect'] as const).map((mode) => ( ))}
Light
adjust('exposure', v)} format={(v) => `${v > 0 ? '+' : ''}${v.toFixed(2)}`} /> adjust('contrast', v)} /> adjust('highlights', v)} /> adjust('shadows', v)} /> adjust('whites', v)} /> adjust('blacks', v)} />
Detail
adjust('texture', v)} /> adjust('clarity', v)} /> adjust('dehaze', v)} /> adjust('sharpen', v)} />
Colour
adjust('temp', v)} format={(v) => (v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`)} /> adjust('tint', v)} /> adjust('saturation', v)} /> adjust('vibrance', v)} /> adjust('hue', v)} format={(v) => `${v > 0 ? '+' : ''}${Math.round(v)}°`} track={HUE_TRACK} />
Range
{active.range.enabled && ( <> range('lumaMin', Math.min(v, active.range.lumaMax))} /> range('lumaMax', Math.max(v, active.range.lumaMin))} /> range('hue', v)} track={HUE_TRACK} /> range('hueRange', v)} /> range('satMin', v)} /> )}
)} )}
); } export function OpticsPanel({ edits, photo, set, lensState, lensSplit, onLensSplit, }: PanelSetProps & { lensState?: { loading: boolean; error: string | null }; lensSplit?: boolean; onLensSplit?: (next: boolean) => void; }) { const geometry = edits.geometry; const profile = edits.lens; const [query, setQuery] = useState(profile?.model ?? ''); const [results, setResults] = useState([]); const [searching, setSearching] = useState(false); const [searchMsg, setSearchMsg] = useState(null); const [available, setAvailable] = useState(null); const [defaultProfile, setDefaultProfile] = useState(null); const [defaultsOpen, setDefaultsOpen] = useState(false); const [calibrationOpen, setCalibrationOpen] = useState(false); const patch = (next: Partial, label: string) => set({ geometry: { ...geometry, ...next } }, label); useEffect(() => { setQuery(profile?.model ?? ''); }, [profile?.maker, profile?.model]); useEffect(() => { let alive = true; getCameraLensDefault(photo.meta) .then((entry) => alive && setDefaultProfile(entry)) .catch(() => alive && setDefaultProfile(null)); return () => { alive = false; }; }, [photo.meta.camera, photo.meta.lens]); useEffect(() => { let alive = true; if (!profile) { setAvailable(null); return; } availableFor(profile) .then((flags) => alive && setAvailable(flags)) .catch(() => alive && setAvailable(0)); return () => { alive = false; }; }, [profile]); const applyProfile = (result: Pick) => { const next: LensProfile = { id: result.id, maker: result.maker, model: result.model, crop: result.crop, cameraModel: photo.meta.camera ?? undefined, corrections: { distortion: true, tca: true, vignetting: true }, distance: 1000, }; set({ lens: next }, 'Lens profile'); setResults([]); setSearchMsg(null); }; const runSearch = async () => { const text = query.trim(); if (text.length < 2) return; setSearching(true); setSearchMsg(null); try { const found = await searchLens(text, photo.meta); setResults(found); if (!found.length) setSearchMsg('No matching lens in the database'); } catch (err) { setSearchMsg(err instanceof Error ? err.message : 'Lens search failed'); } finally { setSearching(false); } }; const autoMatch = async () => { setSearching(true); setSearchMsg(null); try { const match = await findLensForMeta(photo.meta); if (!match) { setSearchMsg(photo.meta.lens ? 'No confident match for this lens' : 'This photo has no lens in its EXIF data'); } else { applyProfile(match); } } catch (err) { setSearchMsg(err instanceof Error ? err.message : 'Lens search failed'); } finally { setSearching(false); } }; const setCorrection = (key: keyof LensProfile['corrections'], value: boolean) => { if (!profile) return; set( { lens: { ...profile, corrections: { ...profile.corrections, [key]: value } } }, `Lens ${key}`, ); }; const saveDefault = async () => { if (!profile) return; try { const entry = await saveCameraLensDefault(photo.meta, profile); setDefaultProfile(entry); setSearchMsg(entry ? 'Saved for this camera and lens' : 'A camera and EXIF lens name are required'); } catch (err) { setSearchMsg(err instanceof Error ? err.message : 'Could not save the camera default'); } }; const forgetDefault = async () => { try { await removeCameraLensDefault(photo.meta); setDefaultProfile(null); setSearchMsg('Camera default removed'); } catch (err) { setSearchMsg(err instanceof Error ? err.message : 'Could not remove the camera default'); } }; const refreshDefault = () => { getCameraLensDefault(photo.meta) .then(setDefaultProfile) .catch(() => setDefaultProfile(null)); }; const hasDefault = Boolean( defaultProfile && profile && defaultProfile.profile.maker === profile.maker && defaultProfile.profile.model === profile.model, ); return ( <>

{photo.meta.lens || 'No lens in EXIF'}

Lens profile {profile && ( )}
{profile ? (

{profile.maker} {profile.model} · crop {profile.crop}×

) : (

Search the Lensfun database or pick a match.

)}
setQuery(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') void runSearch(); }} />
{searchMsg &&

{searchMsg}

} {results.length > 0 && (
{results.map((result) => ( ))}
)} {profile && (
{defaultProfile && ( )}
)}
{profile && (
{(['distortion', 'tca', 'vignetting'] as const).map((key) => { const labels = { distortion: 'Distortion', tca: 'Chromatic aberration', vignetting: 'Vignetting' }; const bit = key === 'distortion' ? 8 : key === 'tca' ? 1 : 2; const supported = available === null || (available & bit) !== 0; return ( ); })} {lensState?.loading &&

Building correction maps…

} {lensState?.error &&

{lensState.error}

} {onLensSplit && ( )}
)}
patch({ distortion: v }, 'Lens distortion')} /> patch({ vertical: v }, 'Vertical perspective')} /> patch({ horizontal: v }, 'Horizontal perspective')} /> patch({ rotate: v }, 'Optics rotation')} format={(v) => `${v.toFixed(1)}°`} /> patch({ scale: v }, 'Optics scale')} format={(v) => `${Math.round(v)}%`} />
{defaultsOpen && ( setDefaultsOpen(false)} onChanged={refreshDefault} /> )} {calibrationOpen && ( setCalibrationOpen(false)} onUse={(saved) => { applyProfile({ id: `${TEAM_PREFIX}${saved.id}`, maker: saved.maker, model: saved.model, crop: saved.crop, }); setCalibrationOpen(false); }} /> )} ); } /** * A DCP profile supplies the same XYZ-to-camera matrix the body writes into a * raw. Only the derived camera-to-sRGB matrix is stored in the edit: the profile * file itself is not kept, so a photo stays self-contained and the choice * round-trips through presets and XMP like any other setting. */ export function CameraProfilePanel({ edits, photo, set, cameraNative = false, }: PanelSetProps & { cameraNative?: boolean }) { const [error, setError] = useState(null); const profile = edits.cameraProfile; const camera = photo.meta?.camera ?? ''; // Saved per camera body: the matrix describes the sensor, so every frame from // the same body can reuse it without opening the .dcp file again. const [saved, setSaved] = useState(() => loadSavedCameraProfiles()); const matching = useMemo(() => savedProfilesForCamera(saved, camera), [saved, camera]); const applied = matching.find((entry) => entry.name === profile?.name); const load = async (file: File) => { if (!cameraNative) return; try { const parsed = parseDcp(new Uint8Array(await file.arrayBuffer())); if (!parsed) throw new Error('That file is not a DCP camera profile'); const matrix = dcpRgbCam(parsed); if (!matrix) throw new Error('This profile has no usable colour matrix'); setError(null); set({ cameraProfile: { name: parsed.name, matrix } }, 'Camera profile'); setSaved(saveCameraProfile({ name: parsed.name, camera: camera || parsed.camera, matrix })); } catch (err) { setError(err instanceof Error ? err.message : 'Could not read that profile'); } }; // Camera profiles describe raw sensor data; a JPEG has already been through // the body's converter, so the panel would have nothing to act on. if (!photo.raw) return null; return ( {cameraNative && (
{profile && ( )}
)} {matching.length > 0 && ( )} {applied && ( )}

{!cameraNative ? 'This proxy was decoded straight to sRGB, so there are no camera samples to profile. Reprocess the RAW to enable camera profiles.' : profile ? `Rendering through ${profile.name}.` : 'Rendering with the matrix stored in the raw. Load a .dcp to render through a different camera profile.'}

{error &&

{error}

}
); } export function ProofPanel({ edits, set, proofProfile, onProofProfile, }: PanelSetProps & { /** Name of the printer profile loaded for this session, if any. */ proofProfile?: string | null; onProofProfile?: (cube: SoftProofCube | null) => void; }) { const proof = edits.proof; const [profileError, setProfileError] = useState(null); const loadProfile = async (file: File) => { try { const bytes = new Uint8Array(await file.arrayBuffer()); const cube = loadProofProfile(bytes, 33, proof.intent); // Persisting is best-effort: the cube is live even when IndexedDB is not. void persistProofProfile(); setProfileError(null); onProofProfile?.(cube); } catch (err) { setProfileError(err instanceof Error ? err.message : 'Could not read that profile'); } }; return (
set({ proof: { ...proof, blackPoint: v } }, 'Proof black point')} format={(v) => `${Math.round(v)}%`} def={2} />
Printer profile
{proofProfile && ( )}

{proofProfile ? `Proofing through ${proofProfile}: the canvas and exports show what this printer can reproduce.` : 'Load a printer .icc/.icm to prove through its real A2B/B2A tables. Without one, the paper controls are an approximation.'}

{profileError &&

{profileError}

}

Turn proofing off before delivering screen files.

); } export function MetadataPanel({ photo, events, onUpdate, presets = [], keywordLibrary = [], onSavePreset, onDeletePreset, }: { photo: PhotoRecord; events: EventRecord[]; onUpdate?: (patch: Partial) => void; presets?: MetadataPreset[]; keywordLibrary?: string[]; onSavePreset?: (preset: Omit) => void; onDeletePreset?: (id: string) => void; }) { const event = events.find((e) => e.id === photo.eventId); const [keyword, setKeyword] = useState(''); const [presetId, setPresetId] = useState(''); const rows: [string, string][] = [ ['File', photo.name], ['Dimensions', `${photo.width} × ${photo.height}`], ['Size', `${(photo.size / (1024 * 1024)).toFixed(2)} MB`], ['Camera', photo.meta.camera ?? '—'], ['Lens', photo.meta.lens ?? '—'], ['ISO', photo.meta.iso ? String(photo.meta.iso) : '—'], ['Aperture', photo.meta.aperture ? `f/${photo.meta.aperture}` : '—'], ['Shutter', photo.meta.shutter ?? '—'], ['Focal', photo.meta.focal ? `${photo.meta.focal} mm` : '—'], ['Captured', photo.takenAt ? new Date(photo.takenAt).toLocaleString() : '—'], ['Imported', new Date(photo.addedAt).toLocaleDateString()], ['Event', event?.name ?? 'Unsorted'], ]; const patch = (next: Partial) => onUpdate?.(next); const addKeyword = (raw?: string) => { const value = (raw ?? keyword).trim().replace(/,$/, ''); if (!value) return; const exists = photo.keywords.some((word) => word.toLowerCase() === value.toLowerCase()); if (!exists) patch({ keywords: [...photo.keywords, value.slice(0, 48)] }); setKeyword(''); }; const removeKeyword = (word: string) => { patch({ keywords: photo.keywords.filter((item) => item !== word) }); }; const applyPreset = (id: string) => { setPresetId(id); const preset = presets.find((item) => item.id === id); if (!preset) return; const words = new Set([...photo.keywords, ...preset.keywords]); patch({ creator: preset.creator, copyright: preset.copyright, keywords: [...words], }); }; const savePreset = () => { if (!onSavePreset) return; const name = window.prompt('Metadata preset name', 'My metadata'); if (!name?.trim()) return; onSavePreset({ name: name.trim(), creator: photo.creator, copyright: photo.copyright, keywords: photo.keywords, }); }; return (