Files
luminary/src/components/Panels.tsx
T
bhursey 5c2903eeef Apply the lens vignetting gain in linear light.
Lensfun's vignetting coefficients describe linear transmission, so
multiplying them into the sRGB-encoded proxy brightened the corners far
more than the lens had lost and over-exposed the edges. The gain now runs
after the decode, in both the grade and the eyedropper.

Existing records that stored the old auto-enabled flag are cleared once,
on the server catalogue at boot and in the browser cache on its next
IndexedDB upgrade, and the Optics panel says when the correction is off.
2026-11-28 16:34:31 +00:00

2782 lines
94 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, 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,
LocalComponent,
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 (
<section className={`panel ${open ? 'open' : ''}`}>
<div className="panel-head">
<button className="panel-toggle" onClick={() => setOpen((o) => !o)}>
<span className="chev">{open ? '▾' : '▸'}</span>
{title}
</button>
{right}
</div>
{open && <div className="panel-body">{children}</div>}
</section>
);
}
export interface PanelSetProps {
edits: Edits;
photo: PhotoRecord;
set: (patch: Partial<Edits>, 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);
// Raws carry their pixels as a URL, with `thumb` empty; handing the empty
// string to the analysis made the decode fail and both Auto buttons quietly
// come back with neutral values, so Auto WB matched As shot exactly.
const thumbSrc = photo.thumbUrl ?? photo.thumb;
const auto = async () => {
setAutoBusy(true);
try {
const partial = await computeAutoEdits(thumbSrc);
set(partial, 'Auto tone');
} finally {
setAutoBusy(false);
}
};
const autoWb = async () => {
setWbBusy(true);
try {
set(await computeAutoWhiteBalance(thumbSrc), 'Auto white balance');
} finally {
setWbBusy(false);
}
};
return (
<Panel title="Light">
<div className="subhead">
<span>White balance</span>
<div className="subhead-actions">
<button
className={`link-btn ${picker ? 'on' : ''}`}
onClick={() => onPicker?.(!picker)}
title="Eyedropper: click something neutral in the photo"
aria-pressed={picker}
>
{picker ? 'Picking…' : 'Eyedropper'}
</button>
<button className="link-btn" onClick={() => void autoWb()} disabled={wbBusy}>
{wbBusy ? 'Reading…' : 'Auto WB'}
</button>
<button className="link-btn" onClick={() => set({ temp: 0, tint: 0, kelvin: null }, 'As shot')}>
As shot
</button>
</div>
</div>
<label className="check-row">
<input
type="checkbox"
checked={edits.kelvin != null}
onChange={(e) => set({ kelvin: e.target.checked ? 5500 : null }, 'Kelvin white balance')}
/>
Absolute Kelvin (5500 K reference)
</label>
{edits.kelvin == null ? (
<Slider
label="Temp"
value={edits.temp}
onChange={(v) => set({ temp: v }, 'Temperature')}
track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)"
/>
) : (
<Slider
label="Temperature"
min={1500}
max={12000}
step={50}
value={edits.kelvin}
onChange={(v) => set({ kelvin: v }, 'Kelvin temperature')}
format={(v) => `${Math.round(v)} K`}
track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)"
/>
)}
<Slider
label="Tint"
value={edits.tint}
onChange={(v) => set({ tint: v }, 'Tint')}
track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)"
/>
<div className="subhead">
<span>Tone</span>
<button className="link-btn" onClick={() => void auto()} disabled={autoBusy}>
{autoBusy ? 'Analyzing…' : 'Auto'}
</button>
</div>
<Slider
label="Exposure"
min={-5}
max={5}
step={0.01}
value={edits.exposure}
onChange={(v) => set({ exposure: v }, 'Exposure')}
format={(v) => v.toFixed(2)}
previewClipping
/>
<Slider
label="Recovery"
min={0}
max={100}
value={edits.recovery}
onChange={(v) => set({ recovery: v }, 'Recovery')}
previewClipping
/>
<Slider label="Contrast" value={edits.contrast} onChange={(v) => set({ contrast: v }, 'Contrast')} />
<Slider label="Highlights" value={edits.highlights} onChange={(v) => set({ highlights: v }, 'Highlights')} />
<Slider label="Shadows" value={edits.shadows} onChange={(v) => set({ shadows: v }, 'Shadows')} />
<Slider label="Whites" value={edits.whites} onChange={(v) => set({ whites: v }, 'Whites')} />
<Slider label="Blacks" value={edits.blacks} onChange={(v) => set({ blacks: v }, 'Blacks')} />
<div className="subhead">
<span>Presence</span>
</div>
<Slider label="Texture" value={edits.texture} onChange={(v) => set({ texture: v }, 'Texture')} />
<Slider label="Clarity" value={edits.clarity} onChange={(v) => set({ clarity: v }, 'Clarity')} />
<Slider label="Dehaze" value={edits.dehaze} onChange={(v) => set({ dehaze: v }, 'Dehaze')} />
<Slider label="Vibrance" value={edits.vibrance} onChange={(v) => set({ vibrance: v }, 'Vibrance')} />
<Slider label="Saturation" value={edits.saturation} onChange={(v) => set({ saturation: v }, 'Saturation')} />
<Slider
label="Redscale"
min={0}
max={100}
value={edits.redscale}
onChange={(v) => set({ redscale: v }, 'Redscale')}
track="linear-gradient(90deg,#a8b6c6,#d96b34,#8f1d12)"
/>
<label className="toggle">
<input type="checkbox" checked={edits.bw} onChange={(e) => set({ bw: e.target.checked }, 'Black & white')} />
<span>Black &amp; white mix</span>
</label>
{edits.bw && (
<>
<div className="subhead">
<span>B&amp;W filter</span>
</div>
<div className="bw-filters">
{BW_FILTERS.map((f) => (
<button
key={f.id}
className={`bw-filter ${edits.bwFilter === f.id ? 'on' : ''}`}
title={`${f.label} filter`}
onClick={() => set({ bwFilter: f.id }, `B&W filter · ${f.label}`)}
>
{f.label}
</button>
))}
</div>
{edits.bwFilter !== 'none' && (
<Slider
label="Filter strength"
value={edits.bwFilterAmount}
onChange={(v) => set({ bwFilterAmount: v }, 'B&W filter strength')}
/>
)}
<div className="muted small">
A filter darkens the colors it absorbs: red drops blue skies, green lifts foliage. The color mixer
below tunes individual hues on top.
</div>
</>
)}
</Panel>
);
}
const CURVE_COLORS: Record<CurveChannel, string> = {
rgb: '#e9e9ec',
red: '#e06a6a',
green: '#6ecf7d',
blue: '#6f9de8',
};
export function CurvePanel({ edits, set }: PanelSetProps) {
const [channel, setChannel] = useState<CurveChannel>('rgb');
const points = edits.curve[channel];
const update = (next: typeof points) => set({ curve: { ...edits.curve, [channel]: next } }, `Curve ${channel.toUpperCase()}`);
return (
<Panel
title="Tone curve"
defaultOpen={false}
right={
<button
className="link-btn"
onClick={() =>
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
</button>
}
>
<div className="subhead">
<span>Input levels</span>
</div>
<Slider
label="Black point"
min={0}
max={45}
value={edits.levels.black}
onChange={(v) =>
set({ levels: { ...edits.levels, black: Math.min(v, edits.levels.white - 5) } }, 'Black point')
}
format={(v) => `${Math.round(v)}`}
/>
<Slider
label="White point"
min={55}
max={100}
value={edits.levels.white}
onChange={(v) =>
set({ levels: { ...edits.levels, white: Math.max(v, edits.levels.black + 5) } }, 'White point')
}
format={(v) => `${Math.round(v)}`}
/>
<Slider
label="Gamma"
min={0.3}
max={3}
step={0.05}
value={edits.levels.gamma}
onChange={(v) => set({ levels: { ...edits.levels, gamma: v } }, 'Midtone gamma')}
format={(v) => v.toFixed(2)}
def={1}
/>
<div className="tabs">
{(['rgb', 'red', 'green', 'blue'] as CurveChannel[]).map((c) => (
<button key={c} className={`tab ${channel === c ? 'on' : ''}`} onClick={() => setChannel(c)}>
{c === 'rgb' ? 'RGB' : c === 'red' ? 'R' : c === 'green' ? 'G' : 'B'}
</button>
))}
</div>
<CurveEditor
points={points}
onChange={update}
color={CURVE_COLORS[channel]}
parametric={edits.parametric}
onParametric={(key, value) =>
set(
{ parametric: { ...edits.parametric, [key]: value } },
`Parametric ${key}`,
)
}
/>
<div className="subhead">
<span>Parametric</span>
</div>
<Slider
label="Highlights"
value={edits.parametric.highlights}
onChange={(v) => set({ parametric: { ...edits.parametric, highlights: v } }, 'Parametric highlights')}
/>
<Slider
label="Lights"
value={edits.parametric.lights}
onChange={(v) => set({ parametric: { ...edits.parametric, lights: v } }, 'Parametric lights')}
/>
<Slider
label="Darks"
value={edits.parametric.darks}
onChange={(v) => set({ parametric: { ...edits.parametric, darks: v } }, 'Parametric darks')}
/>
<Slider
label="Blacks"
value={edits.parametric.blacks}
onChange={(v) => set({ parametric: { ...edits.parametric, blacks: v } }, 'Parametric blacks')}
/>
</Panel>
);
}
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 (
<Panel
title="Color mixer"
defaultOpen={false}
right={
<button
className="link-btn"
onClick={() =>
set(
{ hsl: { hue: HUE_BANDS.map(() => 0), sat: HUE_BANDS.map(() => 0), lum: HUE_BANDS.map(() => 0) } },
'Reset color mixer',
)
}
>
Reset
</button>
}
>
<div className="band-row">
{HUE_BANDS.map((b, i) => (
<button
key={b.key}
className={`band-swatch ${band === i ? 'on' : ''}`}
style={{ background: b.swatch }}
title={b.name}
onClick={() => setBand(i)}
/>
))}
</div>
<div className="band-title">{active.name}</div>
<Slider label="Hue" value={edits.hsl.hue[band]} onChange={(v) => setBandValue('hue', v)} track={HUE_TRACK} />
<Slider label="Saturation" value={edits.hsl.sat[band]} onChange={(v) => setBandValue('sat', v)} />
<Slider label="Luminance" value={edits.hsl.lum[band]} onChange={(v) => setBandValue('lum', v)} />
<div className="muted small">Shift, saturate or brighten one color range without touching the rest.</div>
</Panel>
);
}
export function ColorGradingPanel({ edits, set }: PanelSetProps) {
return (
<Panel title="Color grading" defaultOpen={false}>
<div className="subhead">
<span>Shadows</span>
<span className="swatch-mini" style={{ background: `hsl(${edits.grading.shadows.h} 80% 55%)` }} />
</div>
<Slider
label="Hue"
min={0}
max={360}
value={edits.grading.shadows.h}
onChange={(v) => set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, h: v } } }, 'Grading shadows hue')}
track={HUE_TRACK}
/>
<Slider
label="Amount"
min={0}
max={100}
value={edits.grading.shadows.s}
onChange={(v) => set({ grading: { ...edits.grading, shadows: { ...edits.grading.shadows, s: v } } }, 'Grading shadows')}
/>
<div className="subhead">
<span>Highlights</span>
<span className="swatch-mini" style={{ background: `hsl(${edits.grading.highlights.h} 80% 55%)` }} />
</div>
<Slider
label="Hue"
min={0}
max={360}
value={edits.grading.highlights.h}
onChange={(v) =>
set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, h: v } } }, 'Grading highlights hue')
}
track={HUE_TRACK}
/>
<Slider
label="Amount"
min={0}
max={100}
value={edits.grading.highlights.s}
onChange={(v) => set({ grading: { ...edits.grading, highlights: { ...edits.grading.highlights, s: v } } }, 'Grading highlights')}
/>
<Slider
label="Balance"
value={edits.grading.balance}
onChange={(v) => set({ grading: { ...edits.grading, balance: v } }, 'Grading balance')}
/>
</Panel>
);
}
/**
* 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<HTMLCanvasElement>(null);
const renderer = useRef<Renderer | null>(null);
const bitmap = useRef<ImageBitmap | null>(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 (
<figure className="grain-patch">
<canvas ref={ref} />
<span>Grain at 100% · inside the crop</span>
</figure>
);
}
export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps & { grainFreeze?: boolean }) {
return (
<Panel title="Effects" defaultOpen={false}>
<div className="subhead">
<span>Vignette</span>
</div>
<Slider
label="Amount"
value={edits.vignette.amount}
onChange={(v) => set({ vignette: { ...edits.vignette, amount: v } }, 'Vignette amount')}
/>
<Slider
label="Midpoint"
min={0}
max={100}
value={edits.vignette.midpoint}
onChange={(v) => set({ vignette: { ...edits.vignette, midpoint: v } }, 'Vignette midpoint')}
/>
<Slider
label="Feather"
min={0}
max={100}
value={edits.vignette.feather}
onChange={(v) => set({ vignette: { ...edits.vignette, feather: v } }, 'Vignette feather')}
/>
<div className="subhead">
<span>Grain</span>
</div>
<Slider
label="Amount"
min={0}
max={100}
value={edits.grain.amount}
onChange={(v) => set({ grain: { ...edits.grain, amount: v } }, 'Grain amount')}
/>
<Slider
label="Size"
min={10}
max={100}
value={edits.grain.size}
onChange={(v) => set({ grain: { ...edits.grain, size: v } }, 'Grain size')}
/>
<Slider
label="Roughness"
min={0}
max={100}
value={edits.grain.roughness}
onChange={(v) => set({ grain: { ...edits.grain, roughness: v } }, 'Grain roughness')}
/>
<GrainPatch photo={photo} edits={edits} freezeGrain={grainFreeze} />
</Panel>
);
}
export function DetailPanel({ edits, photo, set }: PanelSetProps) {
const [aiBusy, setAiBusy] = useState(false);
const [aiNote, setAiNote] = useState<string | null>(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 (
<Panel title="Detail" defaultOpen={false}>
<div className="subhead">
<span>Sharpening</span>
</div>
<Slider
label="Amount"
min={0}
max={150}
value={edits.sharpen.amount}
onChange={(v) => set({ sharpen: { ...edits.sharpen, amount: v } }, 'Sharpen amount')}
/>
<Slider
label="Radius"
min={0.5}
max={3}
step={0.1}
value={edits.sharpen.radius}
onChange={(v) => set({ sharpen: { ...edits.sharpen, radius: v } }, 'Sharpen radius')}
format={(v) => v.toFixed(1)}
def={1}
/>
<Slider
label="Detail"
min={0}
max={100}
value={edits.sharpen.detail}
def={25}
onChange={(v) => set({ sharpen: { ...edits.sharpen, detail: v } }, 'Sharpen detail')}
/>
<Slider
label="Masking"
min={0}
max={100}
value={edits.sharpen.mask}
onChange={(v) => set({ sharpen: { ...edits.sharpen, mask: v } }, 'Sharpen masking')}
/>
<Slider
label="Lens softness"
min={0}
max={100}
value={edits.sharpen.lensSoftness}
onChange={(v) => set({ sharpen: { ...edits.sharpen, lensSoftness: v } }, 'Lens softness')}
format={(v) => `${Math.round(v)}`}
/>
<p className="muted small panel-hint">
Edge-aware sharpening for lenses that soften towards the corners.
</p>
<div className="subhead">
<span>Noise reduction</span>
<button
className="chip tiny"
onClick={() => set({ noise: autoNoiseFor(photo.meta) }, 'Auto noise profile')}
title="Set a starting point from camera and ISO"
>
Auto · ISO {photo.meta.iso ?? '—'}
</button>
</div>
<Slider
label="Luminance"
min={0}
max={100}
value={edits.noise.luminance}
onChange={(v) => set({ noise: { ...edits.noise, luminance: v } }, 'Noise reduction')}
/>
<Slider
label="Detail"
min={0}
max={100}
value={edits.noise.detail}
def={50}
onChange={(v) => set({ noise: { ...edits.noise, detail: v } }, 'Noise detail')}
/>
<Slider
label="Color"
min={0}
max={100}
value={edits.noise.chroma}
onChange={(v) => set({ noise: { ...edits.noise, chroma: v } }, 'Color noise reduction')}
/>
<Slider
label="Color detail"
min={0}
max={100}
value={edits.noise.chromaDetail}
def={50}
onChange={(v) => set({ noise: { ...edits.noise, chromaDetail: v } }, 'Color detail')}
/>
<div className="subhead">
<span>AI denoise</span>
<button
className="chip tiny"
disabled={aiBusy}
onClick={generateAi}
title="Clean up noise while keeping edges and fine texture"
>
{aiBusy ? 'Working…' : aiActive ? 'Regenerate' : 'Generate'}
</button>
</div>
{aiActive ? (
<Slider
label="Amount"
min={0}
max={100}
value={edits.aiDenoise.amount}
onChange={(v) => set({ aiDenoise: { ...edits.aiDenoise, amount: v } }, 'AI denoise amount')}
/>
) : null}
<p className="muted small panel-hint">
{aiNote ??
(aiActive
? 'Detail-preserving denoise, rendered from the full proxy.'
: 'Removes noise only where there is no structure to keep.')}
</p>
{aiActive ? (
<button
className="chip tiny"
onClick={() => {
// Drop the rendered files too: an unreferenced 4 MB JPEG per photo is
// not worth keeping, and the next Generate re-renders from scratch.
void clearDenoised(photo.id).catch(() => {});
set({ aiDenoise: { ...edits.aiDenoise, key: null } }, 'Remove AI denoise');
}}
title="Stop using the generated version"
>
Remove
</button>
) : null}
<div className="subhead">
<span>Defringe</span>
</div>
<Slider
label="Purple"
min={0}
max={100}
value={edits.defringe.purple}
onChange={(v) => set({ defringe: { ...edits.defringe, purple: v } }, 'Purple fringe')}
/>
<Slider
label="Green"
min={0}
max={100}
value={edits.defringe.green}
onChange={(v) => set({ defringe: { ...edits.defringe, green: v } }, 'Green fringe')}
/>
</Panel>
);
}
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 <select>: the browser popup tears down when the panel repaints while
* the preset thumbnails stream in, so it would close before you could pick.
*/
function PresetFilterMenu({
value,
onChange,
filmCats,
lookCats,
counts,
}: {
value: string;
onChange: (id: string) => void;
filmCats: { id: string; label: string; hint: string }[];
lookCats: { id: string; label: string; hint: string }[];
counts: Map<string, number>;
}) {
const [open, setOpen] = useState(false);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onPointerDown = (event: PointerEvent) => {
if (root.current && event.target instanceof Node && root.current.contains(event.target)) return;
setOpen(false);
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') setOpen(false);
};
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('keydown', onKeyDown, true);
return () => {
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('keydown', onKeyDown, true);
};
}, [open]);
const labelOf = (id: string) => {
if (id === ALL) return 'All';
if (id === FAVOURITES) return 'Favourites';
if (id === MY_PRESETS) return 'My presets';
return PRESET_CATEGORIES.find((category) => category.id === id)?.label ?? id;
};
const pick = (id: string) => {
onChange(id);
setOpen(false);
};
const item = (id: string, text: string, hint?: string) => (
<button
key={id}
type="button"
role="option"
aria-selected={id === value}
className={`preset-menu-item ${id === value ? 'on' : ''}`}
title={hint}
onClick={() => pick(id)}
>
<span className="preset-menu-label">{text}</span>
<span className="preset-menu-count">{counts.get(id) ?? 0}</span>
</button>
);
return (
<div className="preset-filter" ref={root}>
<button
type="button"
className="preset-select"
aria-label="Preset category"
aria-haspopup="listbox"
aria-expanded={open}
onClick={() => setOpen((prev) => !prev)}
>
<span className="preset-select-text">{labelOf(value)}</span>
<span className="preset-select-chev" aria-hidden="true">
▾
</span>
</button>
{open && (
<div className="preset-menu" role="listbox" aria-label="Preset category">
{item(ALL, 'All')}
{item(FAVOURITES, '★ Favourites')}
{(counts.get(MY_PRESETS) ?? 0) > 0 && item(MY_PRESETS, 'My presets')}
<div className="preset-menu-head">Film stocks</div>
{filmCats.map((category) => item(category.id, category.label, category.hint))}
{lookCats.length > 0 && <div className="preset-menu-head">Creative looks</div>}
{lookCats.map((category) => item(category.id, category.label, category.hint))}
</div>
)}
</div>
);
}
export function PresetsPanel({
presets,
photo,
onApply,
onSave,
onDelete,
}: {
presets: Preset[];
photo: PhotoRecord;
onApply: (preset: Preset) => void;
onSave: (name: string) => void;
onDelete?: (id: string) => void;
}) {
const [query, setQuery] = useState('');
const [filter, setFilter] = usePersistentState<string>('presets.filter', ALL);
const [favourites, setFavourites] = usePersistentState<string[]>('presets.favourites', []);
const [collapsed, setCollapsed] = useState<string[]>([]);
const [variant, setVariant] = useState<FilmVariant>('base');
const [focusedId, setFocusedId] = useState<string | null>(null);
const all = useMemo(
() => presets.map((preset) => ({ ...preset, category: presetCategory(preset) })),
[presets],
);
const counts = useMemo(() => {
const map = new Map<string, number>([[ALL, all.length]]);
for (const preset of all) {
map.set(preset.category!, (map.get(preset.category!) ?? 0) + 1);
} map.set(FAVOURITES, all.reduce((n, preset) => n + (favourites.includes(preset.id) ? 1 : 0), 0));
map.set(MY_PRESETS, all.reduce((n, preset) => n + (preset.category === MY_PRESETS ? 1 : 0), 0));
return map;
}, [all, favourites]);
// One compact picker instead of a wall of pills: film stocks and creative
// looks are separated, and empty categories stay out of the list.
const filmCats = useMemo(
() => PRESET_CATEGORIES.filter((category) => FILM_CATEGORIES.includes(category.id) && (counts.get(category.id) ?? 0) > 0),
[counts],
);
const lookCats = useMemo(
() => PRESET_CATEGORIES.filter((category) => !FILM_CATEGORIES.includes(category.id) && (counts.get(category.id) ?? 0) > 0),
[counts],
);
const validFilter =
filter === ALL || filter === FAVOURITES || filter === MY_PRESETS || (counts.get(filter) ?? 0) > 0 ? filter : ALL;
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
return all.filter((preset) => {
if (validFilter === FAVOURITES) {
if (!favourites.includes(preset.id)) return false;
} else if (validFilter !== ALL && preset.category !== validFilter) {
return false;
}
if (!q) return true;
return [preset.name, preset.group, preset.category, preset.description ?? '', ...(preset.tags ?? [])]
.join(' ')
.toLowerCase()
.includes(q);
});
}, [all, favourites, validFilter, query]);
// Variants are derived on the fly so every stock ships push/pull and split
// grade versions without multiplying the catalogue.
const shown = useMemo(() => filtered.map((preset) => applyFilmVariant(preset, variant)), [filtered, variant]);
const hasFilm = shown.some((preset) => preset.film);
const thumbs = usePresetThumbs(photo, shown);
const groups = useMemo(() => {
const map = new Map<string, Preset[]>();
for (const preset of shown) {
const arr = map.get(preset.group) ?? [];
arr.push(preset);
map.set(preset.group, arr);
}
return [...map.entries()];
}, [shown]);
const focused = shown.find((preset) => preset.id === focusedId) ?? null;
const starId = (preset: Preset) => (preset.film ? preset.id.split('::')[0] : preset.id);
const toggleFavourite = (id: string) =>
setFavourites((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]));
const toggleGroup = (group: string) =>
setCollapsed((prev) => (prev.includes(group) ? prev.filter((item) => item !== group) : [...prev, group]));
return (
<div className="panel-stack preset-browser">
<div className="dev-panel-head">
<span>Presets</span>
<span className="muted small">{shown.length}</span>
<button
className="icon-btn"
title="Save current settings as a preset"
onClick={() => {
const name = window.prompt('Preset name');
if (name && name.trim()) onSave(name.trim());
}}
>
+
</button>
</div>
<div className="preset-toolbar">
<div className="preset-search">
<input
value={query}
placeholder="Search film, brand or tag…"
aria-label="Search presets"
onChange={(event) => setQuery(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Escape') setQuery('');
}}
/>
{query && (
<button className="preset-search-clear" aria-label="Clear search" onClick={() => setQuery('')}>
×
</button>
)}
</div>
<PresetFilterMenu
value={validFilter}
onChange={setFilter}
filmCats={filmCats}
lookCats={lookCats}
counts={counts}
/>
</div>
{hasFilm && (
<div className="variant-row">
{FILM_VARIANTS.map((v) => (
<button
key={v.id}
className={`variant-btn ${variant === v.id ? 'on' : ''}`}
title={v.hint}
onClick={() => setVariant(v.id)}
>
{v.label}
</button>
))}
</div>
)}
<div className="preset-list">
{!shown.length && (
<div className="preset-empty">
{validFilter === FAVOURITES
? 'No favourites yet — hover a preset and click the star.'
: 'No presets match this search.'}
</div>
)}
{groups.map(([group, items]) => {
const isCollapsed = collapsed.includes(group);
return (
<div key={group} className="preset-group">
<button
className="preset-group-head"
aria-expanded={!isCollapsed}
onClick={() => toggleGroup(group)}
>
<span>{group}</span>
<span className="preset-group-count">{items.length}</span>
<span className="preset-group-chev">{isCollapsed ? '▸' : '▾'}</span>
</button>
{!isCollapsed && (
<div className="preset-grid">
{items.map((preset) => {
const src = thumbs[preset.id];
const favourite = favourites.includes(starId(preset));
return (
<div key={preset.id} className="preset-tile-wrap">
<button
className="preset-tile"
onClick={() => onApply(preset)}
onMouseEnter={() => setFocusedId(preset.id)}
onFocus={() => setFocusedId(preset.id)}
title={`${preset.name}${src ? '' : ' — rendering preview…'}`}
>
{src ? (
<img src={src} alt={preset.name} loading="lazy" draggable={false} />
) : (
<span className="preset-tile-blank" />
)}
<span className="preset-tile-name">{shortName(preset)}</span>
</button>
<button
className={`preset-star ${favourite ? 'on' : ''}`}
aria-label={favourite ? `Unstar ${preset.name}` : `Star ${preset.name}`}
aria-pressed={favourite}
onClick={() => toggleFavourite(starId(preset))}
>
★
</button>
{onDelete && presetCategory(preset) === MY_PRESETS && (
<button
className="preset-del"
aria-label={`Delete ${preset.name}`}
title="Delete preset"
onClick={() => {
if (window.confirm(`Delete preset “${preset.name}”?`)) onDelete(preset.id);
}}
>
×
</button>
)}
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
{focused && (
<div className="preset-detail">
<strong>{focused.name}</strong>
{focused.description && <span>{focused.description}</span>}
<span className="preset-detail-meta">
{[focused.film?.process, focused.film?.speed ? `ISO ${focused.film.speed}` : null, focused.group]
.filter(Boolean)
.join(' · ')}
</span>
</div>
)}
</div>
);
}
export function HistoryPanel({ history, onRestore }: { history: HistoryEntry[]; onRestore: (edits: Edits) => void }) {
return (
<div className="panel-stack history">
<div className="dev-panel-head">
<span>History</span>
<span className="muted small">{history.length}</span>
</div>
<div className="history-list">
{[...history].reverse().map((entry, i) => (
<button key={`${entry.ts}-${i}`} className="history-item" onClick={() => onRestore(entry.edits)}>
<span className="history-label">{entry.label}</span>
<span className="muted small">{new Date(entry.ts).toLocaleTimeString()}</span>
</button>
))}
</div>
</div>
);
}
export function SnapshotsPanel({
snapshots,
onSave,
onRestore,
onDelete,
}: {
snapshots: Snapshot[];
onSave: (name: string) => void;
onRestore: (snapshot: Snapshot) => void;
onDelete: (snapshot: Snapshot) => void;
}) {
return (
<div className="panel-stack snapshots">
<div className="dev-panel-head">
<span>Snapshots</span>
<button
className="icon-btn"
title="Save the current look as a named snapshot"
onClick={() => {
const name = window.prompt('Snapshot name', `Look ${snapshots.length + 1}`);
if (name?.trim()) onSave(name.trim());
}}
>
+
</button>
</div>
{snapshots.length ? (
<div className="snapshot-list">
{[...snapshots].reverse().map((snapshot) => (
<div key={snapshot.id} className="snapshot-row">
<button className="snapshot-restore" onClick={() => onRestore(snapshot)} title="Restore this snapshot">
<span>{snapshot.name}</span>
<small>{new Date(snapshot.ts).toLocaleTimeString()}</small>
</button>
<button
className="icon-btn danger"
title="Delete snapshot"
onClick={() => onDelete(snapshot)}
>
✕
</button>
</div>
))}
</div>
) : (
<p className="muted small snapshot-hint">
Save a named look before trying another treatment. Snapshots stay with this photo and its virtual copies.
</p>
)}
</div>
);
}
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 (
<Panel title="Crop & straighten">
<div className="btn-row rotate-row">
<button className="btn ghost small" onClick={() => onRotate(-1)} title="Rotate 90° left">
⟲ 90°
</button>
<button className="btn ghost small" onClick={() => onRotate(1)} title="Rotate 90° right">
⟳ 90°
</button>
{onFlipPreview && (
<button
className={`btn ghost small ${mirrored ? 'on' : ''}`}
onClick={onFlipPreview}
title="Mirror the crop preview without changing the export"
>
{mirrored ? 'Mirror on' : 'Mirror view'}
</button>
)}
</div>
<div className="aspect-grid">
{ASPECTS.map((a) => (
<button key={a.id} className={`chip small ${crop.aspect === a.id ? 'on' : ''}`} onClick={() => onAspect(a.id)}>
{a.label}
</button>
))}
</div>
<Slider
label="Angle"
min={-45}
max={45}
step={0.1}
value={crop.angle}
onChange={(v) => set({ crop: { ...crop, angle: v } }, 'Straighten')}
format={(v) => `${v.toFixed(1)}°`}
/>
<div className="btn-row">
<button className="btn ghost small" onClick={() => set({ crop: { ...crop, flipH: !crop.flipH } }, 'Flip horizontal')}>
Flip H
</button>
<button className="btn ghost small" onClick={() => set({ crop: { ...crop, flipV: !crop.flipV } }, 'Flip vertical')}>
Flip V
</button>
<button
className="btn ghost small"
onClick={() =>
set(
{ crop: { ...crop, x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original' } },
'Reset crop',
)
}
>
Reset crop
</button>
</div>
</Panel>
);
}
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<HTMLCanvasElement>(null);
const frameRef = useRef<NavigatorRect | null>(null);
const dragRef = useRef(false);
const thumbSrc = photo.thumbUrl ?? photo.thumb;
const [thumb, setThumb] = useState<HTMLImageElement | null>(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<HTMLCanvasElement>) => {
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<HTMLCanvasElement>) => {
dragRef.current = false;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
};
return (
<div className="panel-stack navigator">
<div className="dev-panel-head">
<span>Navigator</span>
<span className="muted small">{zoomLabel}</span>
</div>
<div className="navigator-thumb">
<canvas
ref={canvasRef}
className={zoomed ? 'zoomed' : ''}
role="button"
tabIndex={0}
aria-label={`Navigator — ${zoomed ? 'drag to move the zoomed view' : 'click to zoom to 100%'}`}
title={zoomed ? 'Drag to move the zoomed view' : 'Click to zoom to 100% here'}
onPointerDown={(event) => {
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}
/>
</div>
<div className="navigator-name" title={photo.name}>
{photo.name}
</div>
<div className="muted small navigator-meta">
{photo.raw ? (photo.decode === 'embedded' ? 'Raw · camera preview' : 'Raw · demosaiced') : 'JPEG/PNG'}{' '}
· {photo.width}×{photo.height}
</div>
</div>
);
}
const LOCAL_ICON: Record<LocalMaskKind, string> = { brush: '✎', linear: '▤', radial: '◉', raster: '✦' };
export function LocalPanel({
edits,
set,
activeId,
onSelect,
componentId,
onSelectComponent,
onAddComponent,
onDeleteComponent,
onAdd,
onDelete,
onDuplicate,
onEditMask,
maskMode,
brushSize,
onBrushSize,
onCopyLayer,
onPasteLayer,
canPaste,
onAutoMask,
onSampleRange,
autoBusy,
}: PanelSetProps & {
activeId: string | null;
onSelect: (id: string) => void;
/** Shape inside the active layer that the mask controls edit. */
componentId: string | null;
onSelectComponent: (id: string) => void;
onAddComponent: (kind: LocalMaskKind) => void;
onDeleteComponent: (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 shapes = active?.components ?? [];
const shape = shapes.find((component) => component.id === componentId) ?? shapes[0] ?? null;
const patch = (next: Partial<LocalLayer>, label: string) => {
if (!active) return;
set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label);
};
const patchShape = (next: Partial<LocalComponent>, label: string) => {
if (!active || !shape) return;
set(
{
local: layers.map((layer) =>
layer.id === active.id
? {
...layer,
components: layer.components.map((component) =>
component.id === shape.id ? { ...component, ...next } : component,
),
}
: 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 (
<Panel title="Local adjustments" right={<span className="muted small">{layers.length}/{MAX_LOCAL_LAYERS}</span>}>
<div className="btn-row local-add">
<button className="btn ghost small" onClick={() => onAdd('brush')} disabled={layers.length >= MAX_LOCAL_LAYERS}>
{LOCAL_ICON.brush} Brush
</button>
<button className="btn ghost small" onClick={() => onAdd('linear')} disabled={layers.length >= MAX_LOCAL_LAYERS}>
{LOCAL_ICON.linear} Linear
</button>
<button className="btn ghost small" onClick={() => onAdd('radial')} disabled={layers.length >= MAX_LOCAL_LAYERS}>
{LOCAL_ICON.radial} Radial
</button>
</div>
<div className="btn-row local-add auto-mask-row">
<button className="btn ghost small" onClick={() => onAutoMask('subject')} disabled={layers.length >= MAX_LOCAL_LAYERS || autoBusy}>
{autoBusy ? '…' : '✦'} Subject
</button>
<button className="btn ghost small" onClick={() => onAutoMask('sky')} disabled={layers.length >= MAX_LOCAL_LAYERS || autoBusy}>
{autoBusy ? '…' : '✦'} Sky
</button>
<button className="btn ghost small" onClick={() => onAutoMask('background')} disabled={layers.length >= MAX_LOCAL_LAYERS || autoBusy}>
{autoBusy ? '…' : '✦'} Background
</button>
</div>
<div className="btn-row local-transfer">
<button
className="btn ghost small"
onClick={onCopyLayer}
disabled={!active}
title="Copy this mask and its adjustments"
>
Copy mask
</button>
<button
className="btn ghost small"
onClick={onPasteLayer}
disabled={!canPaste || layers.length >= MAX_LOCAL_LAYERS}
title="Paste the copied mask into this photo"
>
Paste mask
</button>
</div>
{layers.length === 0 ? (
<p className="muted small local-hint">
Add a layer to dodge, burn or colour part of the frame. Masks follow the photo through crops
and lens correction.
</p>
) : (
<>
<div className="local-list">
{layers.map((layer) => (
<button
key={layer.id}
className={`local-item ${layer.id === activeId ? 'on' : ''}`}
onClick={() => onSelect(layer.id)}
>
<span className="local-icon">{LOCAL_ICON[layer.components[0]?.kind ?? 'brush']}</span>
<span className="local-name">{layer.name}</span>
<span className="local-kind">
{layer.components.length > 1
? `${layer.components.length} shapes`
: (layer.components[0]?.kind ?? 'mask')}
</span>
</button>
))}
</div>
<div className="local-subhead">Mask shapes</div>
<div className="local-list shapes">
{shapes.map((component, index) => (
<button
key={component.id}
className={`local-item ${component.id === shape?.id ? 'on' : ''}`}
onClick={() => onSelectComponent(component.id)}
>
<span className="local-icon">{LOCAL_ICON[component.kind]}</span>
<span className="local-name">Shape {index + 1}</span>
<span className="local-kind">
{component.mode === 'add' ? component.kind : `${component.kind} · ${component.mode}`}
</span>
</button>
))}
</div>
<div className="btn-row local-add">
{(['brush', 'linear', 'radial'] as const).map((kind) => (
<button
key={kind}
className="btn ghost small"
onClick={() => onAddComponent(kind)}
disabled={shapes.length >= MAX_LOCAL_COMPONENTS}
title="Add a shape to this mask group"
>
+ {LOCAL_ICON[kind]} {kind}
</button>
))}
</div>
{active && shape && (
<>
<div className="btn-row local-actions">
<button
className={`btn ghost small ${maskMode ? 'on' : ''}`}
onClick={onEditMask}
disabled={shape.kind === 'raster'}
title={shape.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined}
>
{maskMode ? 'Done mask' : 'Edit mask'}
</button>
<button className="btn ghost small" onClick={() => onDuplicate(active.id)} disabled={layers.length >= MAX_LOCAL_LAYERS}>
Duplicate
</button>
<button className="btn ghost small danger" onClick={() => onDelete(active.id)}>
Delete
</button>
</div>
{shape.kind === 'raster' && (
<p className="muted small panel-hint">
Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above.
</p>
)}
{shape.kind === 'brush' && (
<Slider
label="Brush size"
min={8}
max={320}
value={brushSize}
def={56}
onChange={onBrushSize}
format={(v) => `${Math.round(v)}px`}
/>
)}
{shape.kind !== 'linear' && (
<Slider
label="Feather"
min={0}
max={100}
value={shape.feather}
def={50}
onChange={(v) => patchShape({ feather: v }, 'Local feather')}
format={(v) => `${Math.round(v)}%`}
/>
)}
<div className="local-subhead">Shape blend</div>
<div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button
key={mode}
className={`chip tiny ${shape.mode === mode ? 'on' : ''}`}
disabled={shapes[0]?.id === shape.id && mode !== 'add'}
title={
shapes[0]?.id === shape.id
? 'The first shape starts the group, so it always adds'
: mode === 'add'
? 'Union this shape into the group'
: mode === 'subtract'
? 'Cut this shape out of the shapes before it'
: 'Keep only where this shape overlaps the shapes before it'
}
onClick={() => patchShape({ mode }, `Shape ${mode}`)}
>
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button>
))}
</div>
<div className="btn-row">
<button
className="btn ghost small danger"
onClick={() => onDeleteComponent(shape.id)}
disabled={shapes.length <= 1}
title={
shapes.length <= 1
? 'A layer needs one shape; delete the layer instead'
: 'Remove this shape from the group'
}
>
Delete shape
</button>
</div>
<div className="local-subhead">Layer blend</div>
<div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button
key={mode}
className={`chip tiny ${active.mode === mode ? 'on' : ''}`}
title={
mode === 'add'
? 'Apply this layer inside its mask'
: mode === 'subtract'
? 'Apply it outside its mask, within the layer above'
: 'Apply it only where the mask overlaps the layer above'
}
onClick={() => patch({ mode }, `Layer ${mode}`)}
>
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button>
))}
</div>
<div className="local-subhead">Mask curve</div>
<CurveEditor
points={active.curve}
onChange={(points) => patch({ curve: points }, 'Mask curve')}
color="#f2f4f8"
/>
<div className="local-subhead">Light</div>
<Slider
label="Exposure"
min={-4}
max={4}
step={0.05}
value={active.adjust.exposure}
onChange={(v) => adjust('exposure', v)}
format={(v) => `${v > 0 ? '+' : ''}${v.toFixed(2)}`}
/>
<Slider
label="Contrast"
value={active.adjust.contrast}
onChange={(v) => adjust('contrast', v)}
/>
<Slider
label="Highlights"
value={active.adjust.highlights}
onChange={(v) => adjust('highlights', v)}
/>
<Slider
label="Shadows"
value={active.adjust.shadows}
onChange={(v) => adjust('shadows', v)}
/>
<Slider
label="Whites"
value={active.adjust.whites}
onChange={(v) => adjust('whites', v)}
/>
<Slider
label="Blacks"
value={active.adjust.blacks}
onChange={(v) => adjust('blacks', v)}
/>
<div className="local-subhead">Detail</div>
<Slider
label="Texture"
value={active.adjust.texture}
onChange={(v) => adjust('texture', v)}
/>
<Slider
label="Clarity"
value={active.adjust.clarity}
onChange={(v) => adjust('clarity', v)}
/>
<Slider
label="Dehaze"
value={active.adjust.dehaze}
onChange={(v) => adjust('dehaze', v)}
/>
<Slider
label="Sharpen"
value={active.adjust.sharpen}
onChange={(v) => adjust('sharpen', v)}
/>
<div className="local-subhead">Colour</div>
<Slider
label="Temperature"
value={active.adjust.temp}
onChange={(v) => adjust('temp', v)}
format={(v) => (v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`)}
/>
<Slider label="Tint" value={active.adjust.tint} onChange={(v) => adjust('tint', v)} />
<Slider
label="Saturation"
value={active.adjust.saturation}
onChange={(v) => adjust('saturation', v)}
/>
<Slider
label="Vibrance"
value={active.adjust.vibrance}
onChange={(v) => adjust('vibrance', v)}
/>
<Slider
label="Hue shift"
min={-180}
max={180}
value={active.adjust.hue}
onChange={(v) => adjust('hue', v)}
format={(v) => `${v > 0 ? '+' : ''}${Math.round(v)}°`}
track={HUE_TRACK}
/>
<div className="local-subhead">
Range
<button
className="chip tiny"
onClick={onSampleRange}
title="Click a colour in the photo to limit this mask to similar hues"
>
Sample
</button>
<button
className={`chip tiny ${active.range.enabled ? 'on' : ''}`}
onClick={() => range('enabled', !active.range.enabled)}
>
{active.range.enabled ? 'On' : 'Off'}
</button>
</div>
{active.range.enabled && (
<>
<Slider
label="Luma min"
min={0}
max={100}
value={active.range.lumaMin}
onChange={(v) => range('lumaMin', Math.min(v, active.range.lumaMax))}
/>
<Slider
label="Luma max"
min={0}
max={100}
value={active.range.lumaMax}
onChange={(v) => range('lumaMax', Math.max(v, active.range.lumaMin))}
/>
<Slider
label="Hue"
min={0}
max={360}
value={active.range.hue}
onChange={(v) => range('hue', v)}
track={HUE_TRACK}
/>
<Slider
label="Hue range"
min={0}
max={180}
value={active.range.hueRange}
def={180}
onChange={(v) => range('hueRange', v)}
/>
<Slider
label="Min saturation"
min={0}
max={100}
value={active.range.satMin}
onChange={(v) => range('satMin', v)}
/>
</>
)}
<div className="btn-row">
<button
className={`btn ghost small ${shape.inverted ? 'on' : ''}`}
onClick={() => patchShape({ inverted: !shape.inverted }, 'Invert mask')}
>
Invert mask
</button>
<button
className="btn ghost small"
onClick={() =>
patch(
{
adjust: {
exposure: 0,
contrast: 0,
highlights: 0,
shadows: 0,
whites: 0,
blacks: 0,
temp: 0,
tint: 0,
saturation: 0,
vibrance: 0,
hue: 0,
texture: 0,
clarity: 0,
dehaze: 0,
sharpen: 0,
},
range: { ...active.range, enabled: false },
},
'Reset local adjustments',
)
}
>
Reset layer
</button>
</div>
</>
)}
</>
)}
</Panel>
);
}
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<LensSearchResult[]>([]);
const [searching, setSearching] = useState(false);
const [searchMsg, setSearchMsg] = useState<string | null>(null);
const [available, setAvailable] = useState<number | null>(null);
const [defaultProfile, setDefaultProfile] = useState<CameraLensDefault | null>(null);
const [defaultsOpen, setDefaultsOpen] = useState(false);
const [calibrationOpen, setCalibrationOpen] = useState(false);
const patch = (next: Partial<Edits['geometry']>, 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<LensSearchResult, 'id' | 'maker' | 'model' | 'crop'>) => {
const next: LensProfile = {
id: result.id,
maker: result.maker,
model: result.model,
crop: result.crop,
cameraModel: photo.meta.camera ?? undefined,
// Geometry and CA are safe to correct on their own; the vignetting gain
// lifts the corners above the frame centre, so it is left for the user to
// enable on the profile they applied.
corrections: { distortion: true, tca: true, vignetting: false },
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 (
<>
<Panel title="Optics & perspective" defaultOpen={false}>
<p className="muted small optics-lens">{photo.meta.lens || 'No lens in EXIF'}</p>
<div className="lens-profile">
<div className="lens-profile-head">
<span>Lens profile</span>
{profile && (
<button
className="btn ghost tiny"
onClick={() => {
set({ lens: undefined }, 'Clear lens profile');
setResults([]);
setSearchMsg(null);
}}
>
Clear
</button>
)}
</div>
{profile ? (
<p className="lens-current" title={`${profile.maker} ${profile.model}`}>
{profile.maker} {profile.model}
<span className="muted small"> · crop {profile.crop}×</span>
</p>
) : (
<p className="muted small">Search the Lensfun database or pick a match.</p>
)}
<div className="lens-search-row">
<input
className="text-input lens-search"
value={query}
placeholder="Lens maker or model"
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void runSearch();
}}
/>
<button className="btn ghost small" disabled={searching} onClick={() => void runSearch()}>
{searching ? '…' : 'Search'}
</button>
</div>
<div className="btn-row">
<button className="btn ghost small" disabled={searching} onClick={() => void autoMatch()}>
Match EXIF lens
</button>
</div>
{searchMsg && <p className="muted small lens-msg">{searchMsg}</p>}
{results.length > 0 && (
<div className="lens-results">
{results.map((result) => (
<button
key={`${result.maker}|${result.model}`}
className="lens-result"
onClick={() => applyProfile(result)}
>
<span>{result.model}</span>
<span className="muted small">
{result.maker} · {result.crop}×{result.team ? ' · Team' : ''}
</span>
</button>
))}
</div>
)}
{profile && (
<div className="lens-default-row">
<button
className="btn ghost small"
onClick={() => void saveDefault()}
disabled={!photo.meta.camera || !photo.meta.lens}
title={
photo.meta.camera && photo.meta.lens
? 'Apply this profile automatically when the same camera and lens are imported'
: 'A camera and EXIF lens name are required'
}
>
{hasDefault ? 'Update camera default' : 'Set as camera default'}
</button>
{defaultProfile && (
<button className="btn ghost tiny" onClick={() => void forgetDefault()}>
Forget
</button>
)}
</div>
)}
<div className="lens-default-manage">
<button className="btn ghost tiny" onClick={() => setCalibrationOpen(true)}>
Team calibrations
</button>
<button className="btn ghost tiny" onClick={() => setDefaultsOpen(true)}>
Manage saved defaults
</button>
</div>
{profile && (
<div className="lens-corrections">
{(['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 (
<label key={key} className={`check ${supported ? '' : 'disabled'}`}>
<input
type="checkbox"
checked={profile.corrections[key]}
disabled={!supported}
onChange={(e) => setCorrection(key, e.target.checked)}
/>
{labels[key]}
</label>
);
})}
{!profile.corrections.vignetting && (
<p className="muted small lens-msg">
Vignetting correction is off, so the corners keep the lens's own falloff.
Tick Vignetting to lift them back to the centre.
</p>
)}
{lensState?.loading && <p className="muted small lens-msg">Building correction maps…</p>}
{lensState?.error && <p className="small lens-error">{lensState.error}</p>}
{onLensSplit && (
<button
className={`btn ghost small ${lensSplit ? 'on' : ''}`}
onClick={() => onLensSplit(!lensSplit)}
disabled={lensState?.loading || Boolean(lensState?.error)}
>
{lensSplit ? 'Hide lens split' : 'Lens before / after'}
</button>
)}
</div>
)}
</div>
<Slider
label="Distortion"
min={-100}
max={100}
value={geometry.distortion}
onChange={(v) => patch({ distortion: v }, 'Lens distortion')}
/>
<Slider
label="Vertical"
min={-100}
max={100}
value={geometry.vertical}
onChange={(v) => patch({ vertical: v }, 'Vertical perspective')}
/>
<Slider
label="Horizontal"
min={-100}
max={100}
value={geometry.horizontal}
onChange={(v) => patch({ horizontal: v }, 'Horizontal perspective')}
/>
<Slider
label="Rotate"
min={-15}
max={15}
step={0.1}
value={geometry.rotate}
onChange={(v) => patch({ rotate: v }, 'Optics rotation')}
format={(v) => `${v.toFixed(1)}°`}
/>
<Slider
label="Scale"
min={50}
max={200}
value={geometry.scale}
def={100}
onChange={(v) => patch({ scale: v }, 'Optics scale')}
format={(v) => `${Math.round(v)}%`}
/>
<div className="btn-row">
<button
className="btn ghost small"
onClick={() =>
patch({ distortion: 0, vertical: 0, horizontal: 0, rotate: 0, scale: 100 }, 'Reset optics')
}
>
Reset optics
</button>
</div>
</Panel>
{defaultsOpen && (
<LensDefaultsModal
onClose={() => setDefaultsOpen(false)}
onChanged={refreshDefault}
/>
)}
{calibrationOpen && (
<LensCalibrationModal
photo={photo}
profile={profile}
onClose={() => 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,
cameraPhotoCount = 0,
onApplyToCamera,
}: PanelSetProps & {
cameraNative?: boolean;
/** Camera-native raws from this body, including the photo on screen. */
cameraPhotoCount?: number;
/** Apply the current profile to every photo from this camera body. */
onApplyToCamera?: (profile: { name: string; matrix: number[] }) => boolean | void;
}) {
const [error, setError] = useState<string | null>(null);
const [appliedAll, setAppliedAll] = useState<number | null>(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<SavedCameraProfile[]>(() => 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 (
<Panel title="Camera profile" defaultOpen={false}>
{cameraNative && (
<div className="btn-row">
<label className="btn ghost small">
{profile ? 'Replace DCP profile' : 'Load DCP profile'}
<input
type="file"
accept=".dcp"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void load(file);
e.target.value = '';
}}
/>
</label>
{profile && (
<button
className="btn ghost small"
onClick={() => {
setError(null);
set({ cameraProfile: null }, 'Body camera matrix');
}}
>
Use body matrix
</button>
)}
</div>
)}
{matching.length > 0 && (
<label className="field">
<span>Saved for this camera</span>
<select
value=""
onChange={(e) => {
const entry = matching.find((item) => item.id === e.target.value);
if (!entry) return;
setError(null);
set({ cameraProfile: { name: entry.name, matrix: entry.matrix } }, 'Camera profile');
}}
>
<option value="">Choose a saved profile…</option>
{matching.map((entry) => (
<option key={entry.id} value={entry.id}>
{entry.name}
</option>
))}
</select>
</label>
)}
{profile && onApplyToCamera && cameraPhotoCount > 1 && (
<button
className="btn ghost small"
onClick={() => {
const done = onApplyToCamera({ name: profile.name, matrix: profile.matrix });
if (done !== false) setAppliedAll(cameraPhotoCount);
}}
>
Apply “{profile.name}” to {cameraPhotoCount} photos
</button>
)}
{appliedAll !== null && (
<p className="muted small panel-hint">
Applied to {appliedAll} photos from this camera.
</p>
)}
{applied && (
<button
className="btn ghost small"
onClick={() => {
setSaved(removeCameraProfile(applied.id));
setError(null);
}}
>
Forget saved {applied.name}
</button>
)}
<p className="muted small panel-hint">
{!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.'}
</p>
{error && <p className="muted small panel-hint">{error}</p>}
</Panel>
);
}
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<string | null>(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 (
<Panel title="Soft proofing" defaultOpen={false}>
<div className="btn-row">
<button
className={`btn ghost small ${proof.enabled ? 'on' : ''}`}
onClick={() => set({ proof: { ...proof, enabled: !proof.enabled } }, 'Soft proofing')}
>
{proof.enabled ? 'Proof on' : 'Proof off'}
</button>
<button
className={`btn ghost small ${proof.gamut ? 'on' : ''}`}
onClick={() => set({ proof: { ...proof, gamut: !proof.gamut } }, 'Gamut warning')}
disabled={!proof.enabled}
>
Gamut warning
</button>
</div>
<label className="field">
<span>Paper</span>
<select
value={proof.paper}
onChange={(e) =>
set({ proof: { ...proof, paper: e.target.value as typeof proof.paper } }, 'Proof paper')
}
disabled={!proof.enabled}
>
<option value="matte">Matte paper</option>
<option value="gloss">Gloss paper</option>
<option value="newsprint">Newsprint</option>
</select>
</label>
<label className="field">
<span>Rendering intent</span>
<select
value={proof.intent}
onChange={(e) =>
set(
{ proof: { ...proof, intent: e.target.value as typeof proof.intent } },
'Rendering intent',
)
}
disabled={!proof.enabled}
title="Which printer table pair the proof uses. Relative colorimetric is what most print shops expect; saturation is often absent from paper profiles and falls back to perceptual."
>
<option value="perceptual">Perceptual</option>
<option value="relative">Relative colorimetric</option>
<option value="saturation">Saturation</option>
</select>
</label>
<Slider
label="Paper black"
min={0}
max={20}
value={proof.blackPoint}
onChange={(v) => set({ proof: { ...proof, blackPoint: v } }, 'Proof black point')}
format={(v) => `${Math.round(v)}%`}
def={2}
/>
<div className="subhead">
<span>Printer profile</span>
</div>
<div className="btn-row">
<label className="btn ghost small">
{proofProfile ? 'Replace ICC profile' : 'Load ICC profile'}
<input
type="file"
accept=".icc,.icm,application/vnd.iccprofile"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void loadProfile(file);
e.target.value = '';
}}
/>
</label>
{proofProfile && (
<button
className="btn ghost small"
onClick={() => {
setActiveProofCube(null);
void clearPersistedProofProfile();
setProfileError(null);
onProofProfile?.(null);
}}
>
Use paper simulation
</button>
)}
</div>
<p className="muted small panel-hint">
{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.'}
</p>
{profileError && <p className="muted small panel-hint">{profileError}</p>}
<p className="muted small panel-hint">
Turn proofing off before delivering screen files.
</p>
</Panel>
);
}
export function MetadataPanel({
photo,
events,
onUpdate,
presets = [],
keywordLibrary = [],
onSavePreset,
onDeletePreset,
}: {
photo: PhotoRecord;
events: EventRecord[];
onUpdate?: (patch: Partial<PhotoRecord>) => void;
presets?: MetadataPreset[];
keywordLibrary?: string[];
onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => 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<PhotoRecord>) => 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 (
<Panel title="Metadata" defaultOpen={false}>
<div className="metadata-fields">
<label className="field">
<span>Title</span>
<input
value={photo.title ?? ''}
placeholder="Untitled"
onChange={(e) => patch({ title: e.target.value })}
disabled={!onUpdate}
/>
</label>
<label className="field">
<span>Caption</span>
<textarea
rows={3}
value={photo.caption ?? ''}
placeholder="Describe this frame"
onChange={(e) => patch({ caption: e.target.value })}
disabled={!onUpdate}
/>
</label>
<div className="field-row">
<label className="field">
<span>Creator</span>
<input
value={photo.creator ?? ''}
placeholder="Photographer"
onChange={(e) => patch({ creator: e.target.value })}
disabled={!onUpdate}
/>
</label>
<label className="field">
<span>Copyright</span>
<input
value={photo.copyright ?? ''}
placeholder="© 2026"
onChange={(e) => patch({ copyright: e.target.value })}
disabled={!onUpdate}
/>
</label>
</div>
<div className="metadata-keywords-head">
<span>Keywords</span>
<span className="muted small">{photo.keywords.length}</span>
</div>
<div className="keyword-chips">
{photo.keywords.map((word) => (
<button key={word} className="keyword-chip" onClick={() => removeKeyword(word)} title="Remove keyword">
{word} <span aria-hidden="true">×</span>
</button>
))}
</div>
<div className="keyword-add">
<input
value={keyword}
list="lumen-keyword-library"
placeholder="Add keyword…"
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ',') {
e.preventDefault();
addKeyword();
}
}}
disabled={!onUpdate}
/>
<button className="btn ghost small" onClick={() => addKeyword()} disabled={!onUpdate || !keyword.trim()}>
Add
</button>
<datalist id="lumen-keyword-library">
{keywordLibrary.map((word) => (
<option key={word} value={word} />
))}
</datalist>
</div>
<div className="metadata-presets">
<select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}>
<option value="">Apply metadata preset…</option>
{presets.map((preset) => (
<option key={preset.id} value={preset.id}>
{preset.name}
</option>
))}
</select>
<button className="btn ghost small" onClick={savePreset} disabled={!onSavePreset}>
Save preset
</button>
{presetId && onDeletePreset && (
<button
className="icon-btn danger"
title="Delete metadata preset"
onClick={() => {
onDeletePreset(presetId);
setPresetId('');
}}
>
🗑
</button>
)}
</div>
</div>
<div className="meta-divider" />
<dl className="meta">
{rows.map(([key, value]) => (
<div key={key} className="meta-row">
<dt>{key}</dt>
<dd title={value}>{value}</dd>
</div>
))}
</dl>
</Panel>
);
}