Files
luminary/src/components/Develop.tsx
T
bhursey 6dfddffc14 Show edited renders in thumbnails and paste to a filmstrip selection
The grid and filmstrip only ever showed the import thumbnail, so edits and
virtual copies looked untouched. Edited tiles now render client-side with the
same shader as the canvas, once each, from the small cached thumbnail. The
filmstrip also gains Cmd/Shift multi-select so Paste, Copy and Reset can act on
several photos from the toolbar or the right-click menu.
2026-11-25 20:37:51 +00:00

2522 lines
92 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
ASPECTS,
defaultEdits,
defaultLocalLayer,
MAX_HEAL_SPOTS,
MAX_LOCAL_LAYERS,
} from '../lib/edits';
import { subscribeClipPreview } from '../lib/clipPreview';
import { getBitmap, getDenoisedBitmap } from '../lib/images';
import { useMediaQuery } from '../lib/useMediaQuery';
import { usePersistentState } from '../lib/usePersistentState';
import { solveWhiteBalance } from '../lib/whiteBalance';
import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask';
import {
buildLensCorrection,
correctLensPoint,
uncorrectLensPoint,
type LensCorrection,
} from '../lib/lensfun';
import {
frameToSource,
rotatedBounds,
Renderer,
sourceToFrame,
unwarpGeometryPoint,
warpGeometryPoint,
} from '../gl/renderer';
import type {
ColorLabel,
Edits,
EventRecord,
Flag,
HealSpot,
LocalLayer,
LocalMaskKind,
LocalStroke,
MetadataPreset,
PhotoRecord,
Preset,
Snapshot,
} from '../types';
import ContextMenu, { type MenuEntry } from './ContextMenu';
import EditedImage from './EditedImage';
import CropOverlay from './CropOverlay';
import Histogram from './Histogram';
import {
BasicPanel,
ColorGradingPanel,
CropPanel,
CurvePanel,
DetailPanel,
EffectsPanel,
HistoryPanel,
HslPanel,
LocalPanel,
MetadataPanel,
NavigatorPanel,
OpticsPanel,
PresetsPanel,
ProofPanel,
SnapshotsPanel,
} from './Panels';
import Stars, { ColorSwatches, FlagButtons } from './Stars';
/** Zoom is expressed as a percentage of actual pixels, like Lightroom's readout. */
const MAX_ZOOM = 400;
const clampNum = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
interface Rect {
x: number;
y: number;
w: number;
h: number;
}
interface Geometry {
fitScale: number;
fitPct: number;
frameW: number;
frameH: number;
zoomFactor: number;
availW: number;
availH: number;
content: Rect;
view: Rect;
}
const EMPTY_GEO: Geometry = {
fitScale: 0,
fitPct: 100,
frameW: 1,
frameH: 1,
zoomFactor: 1,
availW: 0,
availH: 0,
content: { x: 0, y: 0, w: 1, h: 1 },
view: { x: 0, y: 0, w: 1, h: 1 },
};
function cloneLocalLayer(layer: LocalLayer): LocalLayer {
return {
...layer,
brush: {
strokes: layer.brush.strokes.map((stroke) => ({
...stroke,
points: stroke.points.map((point) => ({ ...point })),
})),
},
linear: { ...layer.linear },
radial: { ...layer.radial },
adjust: { ...layer.adjust },
range: { ...layer.range },
};
}
interface Props {
photo: PhotoRecord;
photos: PhotoRecord[];
events: EventRecord[];
onSelect: (id: string) => void;
onExit: () => void;
onUpdate: (id: string, patch: Partial<PhotoRecord>, historyLabel?: string) => void;
clipboard: Edits | null;
onCopy: () => void;
/** Copy settings from a named filmstrip photo instead of the canvas photo. */
onCopyOf?: (id: string) => void;
/** Paste the copied settings; no ids means the photo on the canvas. */
onPaste: (ids?: string[]) => void;
/** Reset several photos at once, without a per-photo confirmation. */
onResetSelection?: (ids: string[]) => void;
localClipboard: LocalLayer | null;
onLocalClipboard: (layer: LocalLayer | null) => void;
onExport: () => void;
onPrint: () => void;
canPushImmich?: boolean;
onPushImmich?: () => void;
onOpenImmich?: () => void;
presets: Preset[];
onSavePreset: (name: string, edits: Edits) => void;
onDelete: () => void;
onVirtualCopy: () => void;
metadataPresets: MetadataPreset[];
keywordLibrary: string[];
onSaveSnapshot: (name: string) => void;
onRestoreSnapshot: (snapshot: Snapshot) => void;
onDeleteSnapshot: (snapshot: Snapshot) => void;
onSaveMetadataPreset: (preset: Omit<MetadataPreset, 'id'>) => void;
onDeleteMetadataPreset: (id: string) => void;
}
export default function Develop({
photo,
photos,
events,
onSelect,
onExit,
onUpdate,
clipboard,
onCopy,
onCopyOf,
onPaste,
onResetSelection,
localClipboard,
onLocalClipboard,
onExport,
onPrint,
canPushImmich = false,
onPushImmich,
onOpenImmich,
presets,
onSavePreset,
onDelete,
onVirtualCopy,
metadataPresets,
keywordLibrary,
onSaveSnapshot,
onRestoreSnapshot,
onDeleteSnapshot,
onSaveMetadataPreset,
onDeleteMetadataPreset,
}: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const stripRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null);
const histRef = useRef<Renderer['histogram'] | null>(null);
const geoRef = useRef<Geometry>(EMPTY_GEO);
const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [denoisedBitmap, setDenoisedBitmap] = useState<ImageBitmap | null>(null);
const [stage, setStage] = useState({ w: 0, h: 0 });
const [cropMode, setCropMode] = useState(false);
const [cropDrag, setCropDrag] = useState(false);
const [clipPreview, setClipPreview] = useState(false);
const [picking, setPicking] = useState(false);
const [clipping, setClipping] = useState<'highlights' | 'shadows' | null>(null);
const [loupe, setLoupe] = useState(false);
const [adjustOpen, setAdjustOpen] = useState(false);
const [leftOpen, setLeftOpen] = usePersistentState('develop.left.open', true);
const [rightOpen, setRightOpen] = usePersistentState('develop.right.open', true);
const [stripOpen, setStripOpen] = usePersistentState('develop.filmstrip.open', true);
const [mobileStripOpen, setMobileStripOpen] = useState(false);
const [mobileAdjustOpen, setMobileAdjustOpen] = useState(false);
const [tipDismissed, setTipDismissed] = usePersistentState('develop.tip.dismissed', false);
const mobile = useMediaQuery('(max-width: 760px)');
const shownStripOpen = mobile ? mobileStripOpen : stripOpen;
const toggleStrip = () => (mobile ? setMobileStripOpen((open) => !open) : setStripOpen((open) => !open));
const [filmMinRating, setFilmMinRating] = useState(0);
const [filmFlag, setFilmFlag] = useState<Flag | 'any'>('any');
// Filmstrip multi-select. The canvas keeps its own photo; this is the set a
// paste applies to, exactly like Lightroom's filmstrip selection.
const [filmSel, setFilmSel] = useState<string[]>([photo.id]);
const [filmAnchor, setFilmAnchor] = useState(photo.id);
const [showOriginal, setShowOriginal] = useState(false);
const [histVersion, setHistVersion] = useState(0);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [zoom, setZoom] = useState<{ pct: number | 'fit'; cx: number; cy: number }>({
pct: 'fit',
cx: 0.5,
cy: 0.5,
});
const [panning, setPanning] = useState(false);
const [navigatorView, setNavigatorView] = useState<Rect | null>(null);
const [readout, setReadout] = useState({ shown: 100, fit: 100 });
const [menu, setMenu] = useState<{
x: number;
y: number;
kind: 'canvas' | 'film';
ids?: string[];
} | null>(null);
const [healMode, setHealMode] = useState(false);
const [brushPx, setBrushPx] = useState(56);
const [healFeather, setHealFeather] = useState(50);
const [healSelected, setHealSelected] = useState<number | null>(null);
const [healHover, setHealHover] = useState<{ x: number; y: number } | null>(null);
const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null);
const [localSelected, setLocalSelected] = useState<string | null>(null);
const [localMode, setLocalMode] = useState(false);
const [autoMaskBusy, setAutoMaskBusy] = useState(false);
const [localBrush, setLocalBrush] = useState(72);
const [localHover, setLocalHover] = useState<{ x: number; y: number } | null>(null);
const [localDraft, setLocalDraft] = useState<LocalStroke | null>(null);
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [lensSplit, setLensSplit] = useState(false);
const [lensSplitAt, setLensSplitAt] = useState(0.5);
const [lensState, setLensState] = useState<{ loading: boolean; error: string | null }>({
loading: false,
error: null,
});
const localDrag = useRef<{
id: string;
mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end';
stroke: LocalStroke | null;
} | null>(null);
const edits = photo.edits;
const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null;
const zoomed = zoom.pct !== 'fit';
// The filmstrip has its own Lightroom-style cull filter so you can narrow the
// strip without changing the grid filters or the photo open on the canvas.
const filmFilterActive = filmMinRating > 0 || filmFlag !== 'any';
const filmPhotos = useMemo(
() =>
photos.filter(
(item) => item.rating >= filmMinRating && (filmFlag === 'any' || item.flag === filmFlag),
),
[photos, filmMinRating, filmFlag],
);
const filmPosition = filmPhotos.findIndex((item) => item.id === photo.id);
const currentInFilm = filmPosition >= 0;
const navigateFilm = useCallback(
(dir: -1 | 1) => {
if (!filmPhotos.length) return;
const at = filmPhotos.findIndex((item) => item.id === photo.id);
if (at < 0) {
const edge = dir > 0 ? filmPhotos[0] : filmPhotos[filmPhotos.length - 1];
if (edge) onSelect(edge.id);
return;
}
const next = filmPhotos[at + dir];
if (next) onSelect(next.id);
},
[filmPhotos, onSelect, photo.id],
);
// The photo on the canvas is always part of the selection, so a fresh filmstrip
// starts with just that frame. Cmd/Shift clicks grow the set without moving it.
useEffect(() => {
setFilmSel([photo.id]);
setFilmAnchor(photo.id);
}, [photo.id]);
// A cull filter can hide part of the selection; drop those frames rather than
// pasting settings into photos that are no longer on screen.
useEffect(() => {
setFilmSel((prev) => {
const visible = new Set(filmPhotos.map((item) => item.id));
const next = prev.filter((id) => visible.has(id));
return next.length === prev.length ? prev : next;
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filmMinRating, filmFlag]);
const clickFilm = (p: PhotoRecord, e: React.MouseEvent) => {
if (e.shiftKey) {
const a = filmPhotos.findIndex((item) => item.id === filmAnchor);
const b = filmPhotos.findIndex((item) => item.id === p.id);
if (a >= 0 && b >= 0) {
const [lo, hi] = a < b ? [a, b] : [b, a];
setFilmSel(filmPhotos.slice(lo, hi + 1).map((item) => item.id));
} else {
setFilmSel([p.id]);
setFilmAnchor(p.id);
}
return;
}
if (e.metaKey || e.ctrlKey) {
setFilmSel((prev) =>
prev.includes(p.id) ? prev.filter((id) => id !== p.id) : [...prev, p.id],
);
setFilmAnchor(p.id);
return;
}
setFilmSel([p.id]);
setFilmAnchor(p.id);
onSelect(p.id);
};
const moveLensSplit = (e: React.PointerEvent<HTMLButtonElement>) => {
const rect = e.currentTarget.parentElement?.getBoundingClientRect();
if (!rect || rect.width <= 0) return;
setLensSplitAt(clampNum((e.clientX - rect.left) / rect.width, 0.02, 0.98));
};
const setEdits = useCallback(
(patch: Partial<Edits>, label: string) => {
onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label);
},
[onUpdate, photo.id, photo.edits],
);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
try {
rendererRef.current = new Renderer(canvas);
} catch (err) {
setError(err instanceof Error ? err.message : 'The image engine could not start');
}
return () => {
rendererRef.current?.dispose();
rendererRef.current = null;
};
}, []);
// Ctrl held while dragging Exposure paints clipped channels on the preview.
useEffect(() => subscribeClipPreview(setClipPreview), []);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
setStage({ w: el.clientWidth, h: el.clientHeight });
const ro = new ResizeObserver((entries) => {
const rect = entries[0].contentRect;
setStage({ w: Math.round(rect.width), h: Math.round(rect.height) });
});
ro.observe(el);
return () => ro.disconnect();
}, [cropMode]);
// The denoised proxy is a separate server asset keyed by the edit. Load it
// alongside the source so the first frame after generating is not stale, and
// drop it when the key is cleared.
useEffect(() => {
const key = edits.aiDenoise.key;
if (!key) {
setDenoisedBitmap(null);
return;
}
let alive = true;
getDenoisedBitmap(photo, key)
.then((bmp) => {
if (alive) setDenoisedBitmap(bmp);
})
.catch(() => {
if (alive) setDenoisedBitmap(null);
});
return () => {
alive = false;
};
}, [photo.id, edits.aiDenoise.key]);
useEffect(() => {
let alive = true;
setLoading(true);
getBitmap(photo)
.then((bmp) => {
if (!alive) return;
setBitmap(bmp);
setLoading(false);
})
.catch((err) => {
if (!alive) return;
setError(err instanceof Error ? err.message : 'Could not load the original image');
setLoading(false);
});
return () => {
alive = false;
};
}, [photo.id, photo.raw, photo.previewUrl]);
// Warm the previous and next originals while the current frame is being
// edited, so arrow-key culling does not wait on a network fetch each time.
useEffect(() => {
const at = filmPhotos.findIndex((item) => item.id === photo.id);
if (at < 0) return;
const neighbours = [filmPhotos[at - 1], filmPhotos[at + 1]].filter(
(item): item is PhotoRecord => Boolean(item),
);
if (!neighbours.length) return;
let alive = true;
const timer = setTimeout(() => {
if (!alive) return;
for (const next of neighbours) void getBitmap(next).catch(() => undefined);
}, 450);
return () => {
alive = false;
clearTimeout(timer);
};
}, [filmPhotos, photo.id]);
// Build the calibrated maps for the selected profile once per photo and
// correction setting. Lensfun is loaded lazily, so photos without a profile
// never pay for the database.
useEffect(() => {
const profile = edits.lens;
if (!profile) {
setLensCorrection(null);
setLensState({ loading: false, error: null });
setLensSplit(false);
return;
}
let alive = true;
setLensCorrection(null);
setLensState({ loading: true, error: null });
buildLensCorrection(profile, {
width: bitmap?.width ?? photo.width,
height: bitmap?.height ?? photo.height,
meta: photo.meta,
})
.then((correction) => {
if (!alive) return;
setLensCorrection(correction);
setLensState({ loading: false, error: null });
})
.catch((err) => {
if (!alive) return;
console.error('Lens correction failed', err);
setLensCorrection(null);
setLensState({
loading: false,
error: err instanceof Error ? err.message : 'Could not build the lens correction',
});
});
return () => {
alive = false;
};
}, [edits.lens, bitmap, photo.id, photo.width, photo.height, photo.meta]);
// A new photo, a crop change or entering crop mode all invalidate the current view.
useEffect(() => {
setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 });
}, [photo.id, cropMode, edits.crop]);
// Leaving crop mode mid-drag must not leave the grain frozen.
useEffect(() => {
if (!cropMode) setCropDrag(false);
}, [cropMode]);
const drawPreview = useCallback(() => {
const renderer = rendererRef.current;
const canvas = canvasRef.current;
if (!renderer || !canvas || !bitmap) return;
if (stage.w < 40 || stage.h < 40) return;
const activeEdits = showOriginal ? { ...defaultEdits(), crop: edits.crop } : edits;
const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter);
const content: Rect = cropMode
? { x: 0, y: 0, w: 1, h: 1 }
: { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h };
const contentW = Math.max(1, frame.w * content.w);
const contentH = Math.max(1, frame.h * content.h);
const availW = Math.max(60, stage.w - 48);
const availH = Math.max(60, stage.h - 48);
const fitScale = Math.min(availW / contentW, availH / contentH);
const fitPct = Math.min(100, fitScale * 100);
const zoomFactor = zoom.pct === 'fit' ? 1 : Math.max(1, zoom.pct / 100 / fitScale);
let view: Rect = content;
let cssW = Math.max(40, Math.round(contentW * fitScale));
let cssH = Math.max(40, Math.round(contentH * fitScale));
if (zoomFactor > 1.0001) {
// The visible window keeps the stage's aspect, so the canvas is stage sized
// and the shader maps it onto a sub-rect of the frame. Cost stays constant
// no matter how far you zoom, and detail comes from the source bitmap.
const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w);
const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h);
const cx =
vw >= content.w
? content.x + content.w / 2
: clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
const cy =
vh >= content.h
? content.y + content.h / 2
: clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh };
cssW = Math.round(availW);
cssH = Math.round(availH);
}
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cap = Math.min(1, 3200 / Math.max(1, Math.max(cssW * dpr, cssH * dpr)));
const pxW = Math.max(1, Math.round(cssW * dpr * cap));
const pxH = Math.max(1, Math.round(cssH * dpr * cap));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
geoRef.current = {
fitScale,
fitPct,
frameW: frame.w,
frameH: frame.h,
zoomFactor,
availW,
availH,
content,
view,
};
const shown = Math.round(fitScale * zoomFactor * 100);
const fit = Math.round(fitPct);
setReadout((prev) => (prev.shown === shown && prev.fit === fit ? prev : { shown, fit }));
setNavigatorView((prev) =>
prev && prev.x === view.x && prev.y === view.y && prev.w === view.w && prev.h === view.h
? prev
: view,
);
try {
renderer.setImage(bitmap);
// "Show original" must show the untouched source, not the cleaned proxy.
renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100);
renderer.render(activeEdits, {
width: pxW,
height: pxH,
cropPreview: cropMode,
// The histogram describes the whole photo, so it is only refreshed at fit.
histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001,
view: zoomFactor <= 1.0001 ? undefined : view,
// Holding the grain still keeps the noise from crawling while a crop
// handle moves; the new crop-relative scale applies on release.
freezeGrain: cropDrag,
// One source pixel per device pixel is the crossover: below it mipmaps
// resample cleanly, above it bicubic keeps magnified detail from squaring off.
upscale: dpr * cap * fitScale * zoomFactor > 1.1,
clipPreview,
clipping: clipping ?? undefined,
lens: showOriginal ? null : lensCorrection,
lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined,
});
histRef.current = renderer.histogram;
setHistVersion((v) => v + 1);
} catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed');
}
}, [
bitmap,
denoisedBitmap,
edits,
cropMode,
showOriginal,
stage,
zoom,
cropDrag,
clipPreview,
clipping,
lensCorrection,
lensSplit,
lensSplitAt,
]);
useEffect(() => {
if (!bitmap) return;
const raf = requestAnimationFrame(drawPreview);
return () => cancelAnimationFrame(raf);
}, [bitmap, drawPreview]);
/* ------------------------------------------------------------ zoom & pan */
const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => {
const geo = geoRef.current;
if (!geo.fitScale) return;
const fitPct = geo.fitPct;
if (rawPct === 'fit' || rawPct <= fitPct * 1.015 || fitPct >= 99.5) {
setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 });
return;
}
const next = clampNum(rawPct, fitPct * 1.02, MAX_ZOOM);
const zNow = Math.max(1, geo.zoomFactor);
const zNext = Math.max(1, next / fitPct);
const centerX = geo.view.x + geo.view.w / 2;
const centerY = geo.view.y + geo.view.h / 2;
let cx = centerX;
let cy = centerY;
if (point) {
// Keep the frame point under the cursor fixed while the scale changes.
const rect = canvasRef.current?.getBoundingClientRect();
if (rect) {
const dx = point.x - (rect.left + rect.width / 2);
const dy = point.y - (rect.top + rect.height / 2);
const pointX = centerX + dx / (geo.fitScale * zNow) / geo.frameW;
const pointY = centerY + dy / (geo.fitScale * zNow) / geo.frameH;
cx = pointX - dx / (geo.fitScale * zNext) / geo.frameW;
cy = pointY - dy / (geo.fitScale * zNext) / geo.frameH;
}
}
const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW;
const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH;
const c = geo.content;
cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
setZoom({ pct: next, cx, cy });
}, []);
/** Click or drag in the navigator thumbnail to move the zoomed viewport. */
const navigateZoom = useCallback(
(fx: number, fy: number) => {
const geo = geoRef.current;
if (!geo.fitScale) return;
// A click while fitted behaves like Lightroom: jump to actual pixels at
// the chosen point. Once zoomed, dragging keeps the current scale.
if (zoom.pct === 'fit' && geo.fitPct >= 99.5) return;
const pct = zoom.pct === 'fit' ? 100 : zoom.pct;
const z = Math.max(1, pct / geo.fitPct);
const c = geo.content;
const vw = Math.min(c.w, geo.availW / (geo.fitScale * z) / geo.frameW);
const vh = Math.min(c.h, geo.availH / (geo.fitScale * z) / geo.frameH);
const cx =
vw >= c.w
? c.x + c.w / 2
: clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2);
const cy =
vh >= c.h
? c.y + c.h / 2
: clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2);
setZoom({ pct, cx, cy });
},
[zoom.pct],
);
// Filmstrip: the wheel browses photos sideways, and the current one is kept
// in view as you move through the shoot.
useEffect(() => {
const el = stripRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
e.preventDefault();
el.scrollLeft += e.deltaY;
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
useEffect(() => {
stripRef.current?.querySelector('.film.active')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}, [photo.id, filmMinRating, filmFlag, shownStripOpen]);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
// The fullscreen adjustment panel scrolls independently of the photo.
if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return;
if (cropMode) return;
// While painting a mask, the wheel sizes the brush instead of zooming.
if (localMode && activeLocal?.kind === 'brush') {
e.preventDefault();
setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320));
return;
}
// While healing, the wheel sizes the brush instead of zooming.
if (healMode) {
e.preventDefault();
setBrushPx((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 14, 240));
return;
}
const geo = geoRef.current;
if (!geo.fitScale) return;
if (!e.ctrlKey && Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
e.preventDefault();
const base = geo.fitPct * Math.max(1, geo.zoomFactor);
applyZoom(base * Math.exp(-e.deltaY * 0.0022), { x: e.clientX, y: e.clientY });
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [cropMode, applyZoom, healMode, localMode, activeLocal]);
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (picking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
const geo = geoRef.current;
panRef.current = {
x: e.clientX,
y: e.clientY,
cx: geo.view.x + geo.view.w / 2,
cy: geo.view.y + geo.view.h / 2,
};
e.currentTarget.setPointerCapture(e.pointerId);
setPanning(true);
};
const movePan = (e: React.PointerEvent<HTMLCanvasElement>) => {
const start = panRef.current;
if (!start) return;
const geo = geoRef.current;
const z = Math.max(1, geo.zoomFactor);
const dx = (e.clientX - start.x) / (geo.fitScale * z * geo.frameW);
const dy = (e.clientY - start.y) / (geo.fitScale * z * geo.frameH);
const c = geo.content;
const cx =
geo.view.w >= c.w
? c.x + c.w / 2
: clampNum(start.cx - dx, c.x + geo.view.w / 2, c.x + c.w - geo.view.w / 2);
const cy =
geo.view.h >= c.h
? c.y + c.h / 2
: clampNum(start.cy - dy, c.y + geo.view.h / 2, c.y + c.h - geo.view.h / 2);
setZoom((prev) => ({ pct: prev.pct, cx, cy }));
};
const endPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!panRef.current) return;
panRef.current = null;
setPanning(false);
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
};
// The eyedropper reads through the renderer so the sample follows the same
// crop, straighten and zoom mapping as the pixels on screen.
const pickWhiteBalance = (e: React.MouseEvent<HTMLCanvasElement>) => {
if (!picking || cropMode) return;
const canvas = canvasRef.current;
const renderer = rendererRef.current;
if (!canvas || !renderer) return;
const rect = canvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const geo = geoRef.current;
const sample = renderer.pickSource(edits, {
nx: clampNum((e.clientX - rect.left) / rect.width, 0, 1),
ny: clampNum((e.clientY - rect.top) / rect.height, 0, 1),
view: geo.zoomFactor > 1.0001 ? geo.view : undefined,
upscale: Math.min(window.devicePixelRatio || 1, 2) * geo.fitScale * geo.zoomFactor > 1.1,
});
setPicking(false);
if (!sample) return;
const wb = solveWhiteBalance(sample);
if (wb) setEdits({ temp: wb.temp, tint: wb.tint }, 'White balance');
};
/* --------------------------------------------------------------- healing */
/** Pointer position as normalized source-image uv, through crop and zoom. */
const sourcePointFromEvent = useCallback(
(e: { clientX: number; clientY: number }): { x: number; y: number } | null => {
const canvas = canvasRef.current;
if (!canvas || !bitmap) return null;
const rect = canvas.getBoundingClientRect();
if (!rect.width || !rect.height) return null;
const geo = geoRef.current;
const view = geo.zoomFactor > 1.0001 ? geo.view : edits.crop;
const nx = clampNum((e.clientX - rect.left) / rect.width, 0, 1);
const ny = clampNum((e.clientY - rect.top) / rect.height, 0, 1);
const frame = { x: view.x + nx * view.w, y: view.y + ny * view.h };
const source = frameToSource(
frame,
bitmap.width,
bitmap.height,
edits.crop.angle,
edits.crop.quarter,
edits.crop.flipH,
edits.crop.flipV,
);
// Masks and heal spots live in the warped source space the shader samples.
const warped = warpGeometryPoint(source, edits.geometry, bitmap.width, bitmap.height);
return correctLensPoint(lensCorrection, warped.x, warped.y);
},
[bitmap, edits.crop, edits.geometry, lensCorrection],
);
/** Brush size on screen converted to a fraction of the source width. */
const brushRadius = useCallback(() => {
const geo = geoRef.current;
if (!bitmap || !geo.fitScale) return 0.02;
return Math.max(0.0015, brushPx / 2 / (geo.fitScale * geo.zoomFactor * bitmap.width));
}, [bitmap, brushPx]);
const commitHeal = useCallback(
(spots: HealSpot[], label = 'Healing') => {
setEdits({ heal: spots.slice(-MAX_HEAL_SPOTS) }, label);
},
[setEdits],
);
/** Places a new spot, borrowing a clean patch from the nearest free side. */
const makeSpot = useCallback(
(src: { x: number; y: number }, r: number): HealSpot => {
if (!bitmap) return { x: src.x, y: src.y, r, feather: healFeather, sx: src.x, sy: src.y };
const yRoom = (r * bitmap.width) / bitmap.height;
const gap = r * 2.2;
const fits = (p: { x: number; y: number }) =>
p.x > r * 1.1 &&
p.x < 1 - r * 1.1 &&
p.y > yRoom * 1.1 &&
p.y < 1 - yRoom * 1.1;
const options = [
{ x: src.x + gap, y: src.y },
{ x: src.x - gap, y: src.y },
{ x: src.x, y: src.y + gap },
{ x: src.x, y: src.y - gap },
];
const source = options.find(fits) ?? { x: src.x, y: src.y - gap };
return {
x: src.x,
y: src.y,
r,
feather: healFeather,
sx: clampNum(source.x, 0, 1),
sy: clampNum(source.y, 0, 1),
};
},
[bitmap, healFeather],
);
/** Distance from a point to a spot, measured in source-width units. */
const distanceToSpot = useCallback(
(p: { x: number; y: number }, spot: HealSpot) => {
if (!bitmap) return Infinity;
const dy = (p.y - spot.y) * (bitmap.height / bitmap.width);
return Math.hypot(p.x - spot.x, dy);
},
[bitmap],
);
const removeHealSpot = useCallback(() => {
const spots = edits.heal ?? [];
if (!spots.length) return;
const index = healSelected ?? spots.length - 1;
commitHeal(spots.filter((_, i) => i !== index));
setHealSelected(null);
}, [commitHeal, edits.heal, healSelected]);
const startHeal = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!bitmap || e.button !== 0) return;
const src = sourcePointFromEvent(e);
if (!src) return;
e.preventDefault();
const spots = edits.heal ?? [];
let hit = -1;
for (let i = spots.length - 1; i >= 0; i--) {
if (distanceToSpot(src, spots[i]) <= spots[i].r * 1.15) {
hit = i;
break;
}
}
e.currentTarget.setPointerCapture(e.pointerId);
if (hit >= 0) {
healDrag.current = { index: hit, mode: e.altKey ? 'source' : 'target', spot: { ...spots[hit] } };
setHealSelected(hit);
if (e.altKey) setHealFeather(spots[hit].feather);
return;
}
const spot = makeSpot(src, brushRadius());
let next = [...spots, spot];
let index = next.length - 1;
if (next.length > MAX_HEAL_SPOTS) {
next = next.slice(-MAX_HEAL_SPOTS);
index = MAX_HEAL_SPOTS - 1;
}
commitHeal(next, 'Heal spot');
setHealSelected(index);
healDrag.current = { index, mode: 'target', spot };
};
const moveHeal = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!healMode) return;
const src = sourcePointFromEvent(e);
if (!src) return;
setHealHover(src);
const drag = healDrag.current;
if (!drag) return;
const spots = photo.edits.heal ?? [];
const current = spots[drag.index];
if (!current) return;
// Dragging the spot moves it with its sample; Alt-drag moves the sample.
const patch: HealSpot =
drag.mode === 'source'
? { ...current, sx: src.x, sy: src.y }
: {
...current,
x: clampNum(drag.spot.x + (src.x - drag.spot.x), 0, 1),
y: clampNum(drag.spot.y + (src.y - drag.spot.y), 0, 1),
sx: clampNum(drag.spot.sx + (src.x - drag.spot.x), 0, 1),
sy: clampNum(drag.spot.sy + (src.y - drag.spot.y), 0, 1),
};
const next = [...spots];
next[drag.index] = patch;
commitHeal(next);
};
const endHeal = (e: React.PointerEvent<HTMLCanvasElement>) => {
healDrag.current = null;
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
};
const toggleHeal = useCallback(() => {
setHealMode((v) => !v);
setCropMode(false);
setPicking(false);
setLocalMode(false);
setHealSelected(null);
}, []);
/* ------------------------------------------------------- local adjustments */
const localRadius = useCallback(() => {
const geo = geoRef.current;
if (!bitmap || !geo.fitScale) return 0.03;
return Math.max(0.0015, localBrush / 2 / (geo.fitScale * geo.zoomFactor * bitmap.width));
}, [bitmap, localBrush]);
const commitLocal = useCallback(
(layers: LocalLayer[], label = 'Local adjustment') => {
setEdits({ local: layers.slice(0, MAX_LOCAL_LAYERS) }, label);
},
[setEdits],
);
const patchLocal = useCallback(
(id: string, patch: Partial<LocalLayer>, label = 'Local adjustment') => {
commitLocal(
(photo.edits.local ?? []).map((layer) => (layer.id === id ? { ...layer, ...patch } : layer)),
label,
);
},
[commitLocal, photo.edits.local],
);
const addLocalLayer = useCallback(
(kind: LocalMaskKind) => {
const layers = edits.local ?? [];
if (layers.length >= MAX_LOCAL_LAYERS) return;
const layer = defaultLocalLayer(kind, layers.length);
commitLocal([...layers, layer], 'Add local adjustment');
setLocalSelected(layer.id);
setLocalMode(true);
setCropMode(false);
setHealMode(false);
},
[commitLocal, edits.local],
);
const addAutoMask = useCallback(
async (kind: AutoMaskKind) => {
const layers = edits.local ?? [];
if (layers.length >= MAX_LOCAL_LAYERS || autoMaskBusy) return;
setAutoMaskBusy(true);
try {
const source = bitmap ?? (await getBitmap(photo));
const raster = await buildAutoMask(source, kind);
const layer = defaultLocalLayer('raster', layers.length);
layer.name = `Auto ${kind}`;
layer.raster = raster;
layer.feather = 30;
commitLocal([...layers, layer], `Auto ${kind} mask`);
setLocalSelected(layer.id);
setLocalMode(false);
setCropMode(false);
setHealMode(false);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not build the auto mask');
} finally {
setAutoMaskBusy(false);
}
},
[autoMaskBusy, bitmap, commitLocal, edits.local, photo],
);
const deleteLocalLayer = useCallback(
(id: string) => {
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
setLocalSelected(null);
setLocalMode(false);
},
[commitLocal, edits.local],
);
const duplicateLocalLayer = useCallback(
(id: string) => {
const layers = edits.local ?? [];
if (layers.length >= MAX_LOCAL_LAYERS) return;
const source = layers.find((layer) => layer.id === id);
if (!source) return;
const copy: LocalLayer = {
...cloneLocalLayer(source),
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `${source.name} copy`,
};
commitLocal([...layers, copy], 'Duplicate local adjustment');
setLocalSelected(copy.id);
},
[commitLocal, edits.local],
);
const copyLocalLayer = useCallback(() => {
if (activeLocal) onLocalClipboard(cloneLocalLayer(activeLocal));
}, [activeLocal, onLocalClipboard]);
const pasteLocalLayer = useCallback(() => {
if (!localClipboard) return;
const layers = edits.local ?? [];
if (layers.length >= MAX_LOCAL_LAYERS) return;
const copy: LocalLayer = {
...cloneLocalLayer(localClipboard),
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${layers.length + 1}`,
};
commitLocal([...layers, copy], 'Paste local adjustment');
setLocalSelected(copy.id);
setLocalMode(true);
setCropMode(false);
setHealMode(false);
}, [commitLocal, edits.local, localClipboard]);
const toggleLocalMode = useCallback(() => {
if (!activeLocal) return;
setLocalMode((v) => !v);
setCropMode(false);
setHealMode(false);
setPicking(false);
}, [activeLocal]);
const startLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!localMode || !activeLocal || !bitmap) return;
const p = sourcePointFromEvent(e);
if (!p) return;
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
if (activeLocal.kind === 'brush') {
const stroke: LocalStroke = { points: [p], size: localRadius(), erase: e.altKey };
localDrag.current = { id: activeLocal.id, mode: 'brush', stroke };
setLocalDraft(stroke);
return;
}
if (activeLocal.kind === 'radial') {
const aspect = bitmap.height / bitmap.width;
const nx = (p.x - activeLocal.radial.cx) / Math.max(0.001, activeLocal.radial.rx);
const ny = ((p.y - activeLocal.radial.cy) * aspect) / Math.max(0.001, activeLocal.radial.ry);
const mode =
Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65
? 'edgeX'
: Math.abs(ny) > 0.82 && Math.abs(nx) < 0.65
? 'edgeY'
: Math.hypot(nx, ny) > 0.82
? 'edge'
: 'center';
localDrag.current = { id: activeLocal.id, mode, stroke: null };
return;
}
const ds = Math.hypot(p.x - activeLocal.linear.x1, (p.y - activeLocal.linear.y1) * (bitmap.height / bitmap.width));
const de = Math.hypot(p.x - activeLocal.linear.x2, (p.y - activeLocal.linear.y2) * (bitmap.height / bitmap.width));
localDrag.current = { id: activeLocal.id, mode: ds <= de ? 'start' : 'end', stroke: null };
};
const moveLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!localMode || !bitmap) return;
const p = sourcePointFromEvent(e);
if (!p) return;
setLocalHover(p);
const drag = localDrag.current;
if (!drag) return;
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id);
if (!layer) return;
if (drag.mode === 'brush' && drag.stroke) {
const last = drag.stroke.points[drag.stroke.points.length - 1];
if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return;
const stroke = { ...drag.stroke, points: [...drag.stroke.points, p].slice(-4000) };
drag.stroke = stroke;
setLocalDraft(stroke);
return;
}
if (drag.mode === 'center') {
patchLocal(layer.id, { radial: { ...layer.radial, cx: p.x, cy: p.y } }, 'Move local mask');
} else if (drag.mode === 'edgeX') {
patchLocal(
layer.id,
{ radial: { ...layer.radial, rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5) } },
'Resize local mask',
);
} else if (drag.mode === 'edgeY') {
patchLocal(
layer.id,
{ radial: { ...layer.radial, ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5) } },
'Resize local mask',
);
} else if (drag.mode === 'edge') {
patchLocal(
layer.id,
{
radial: {
...layer.radial,
rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5),
ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5),
},
},
'Resize local mask',
);
} else if (drag.mode === 'start') {
patchLocal(layer.id, { linear: { ...layer.linear, x1: p.x, y1: p.y } }, 'Move local gradient');
} else if (drag.mode === 'end') {
patchLocal(layer.id, { linear: { ...layer.linear, x2: p.x, y2: p.y } }, 'Move local gradient');
}
};
const endLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
const drag = localDrag.current;
if (drag?.mode === 'brush' && drag.stroke?.points.length) {
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id);
if (layer) {
patchLocal(
layer.id,
{ brush: { strokes: [...layer.brush.strokes, drag.stroke].slice(-300) } },
drag.stroke.erase ? 'Erase local mask' : 'Paint local mask',
);
}
}
localDrag.current = null;
setLocalDraft(null);
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
};
// The feather slider edits the selected spot, and new spots inherit it.
const setFeather = (value: number) => {
setHealFeather(value);
const spots = edits.heal ?? [];
if (healSelected === null || !spots[healSelected]) return;
const next = [...spots];
next[healSelected] = { ...next[healSelected], feather: value };
commitHeal(next);
};
useEffect(() => {
if (cropMode) setHealMode(false);
}, [cropMode]);
useEffect(() => {
if (!healMode) {
setHealHover(null);
healDrag.current = null;
}
}, [healMode]);
useEffect(() => {
setLocalSelected(null);
setLocalMode(false);
setLocalDraft(null);
localDrag.current = null;
}, [photo.id]);
useEffect(() => {
if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) {
setLocalSelected(null);
setLocalMode(false);
}
}, [edits.local, localSelected]);
// Escape cancels the picker without touching the edit.
useEffect(() => {
if (!picking) return;
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
setPicking(false);
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [picking]);
useEffect(() => {
if (cropMode) setPicking(false);
}, [cropMode]);
// Full-screen loupe: the stage itself goes fullscreen, so the browser hides
// every panel and the canvas simply gets the whole screen.
useEffect(() => {
const onFs = () => {
const on = !!document.fullscreenElement;
setLoupe(on);
if (!on) setAdjustOpen(false);
};
document.addEventListener('fullscreenchange', onFs);
return () => document.removeEventListener('fullscreenchange', onFs);
}, []);
const toggleLoupe = useCallback(() => {
const el = stageRef.current;
if (document.fullscreenElement) {
setAdjustOpen(false);
void document.exitFullscreen().catch(() => undefined);
return;
}
setAdjustOpen(false);
if (el?.requestFullscreen) void el.requestFullscreen().catch(() => undefined);
}, []);
const toggleZoom = (x?: number, y?: number) => {
if (cropMode) return;
if (zoomed) applyZoom('fit');
else applyZoom(100, x !== undefined && y !== undefined ? { x, y } : undefined);
};
const historyPosition = photo.history.findIndex((entry) => entry.edits === photo.edits);
const canUndo = historyPosition > 0 || (historyPosition < 0 && photo.history.length > 1);
const canRedo = historyPosition >= 0 && historyPosition < photo.history.length - 1;
const undo = useCallback(() => {
const hist = photo.history;
if (hist.length < 2) return;
const idx = hist.findIndex((h) => h.edits === photo.edits);
const target = idx > 0 ? hist[idx - 1] : hist[hist.length - 2];
if (target) onUpdate(photo.id, { edits: target.edits });
}, [photo.history, photo.edits, photo.id, onUpdate]);
const redo = useCallback(() => {
const hist = photo.history;
const idx = hist.findIndex((h) => h.edits === photo.edits);
const target = idx >= 0 ? hist[idx + 1] : undefined;
if (target) onUpdate(photo.id, { edits: target.edits });
}, [photo.history, photo.edits, photo.id, onUpdate]);
useEffect(() => {
const down = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null;
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return;
if (e.key === '\\') {
setShowOriginal(true);
return;
}
// Ratings, labels and flags work here exactly as they do in the grid, so a
// shoot can be culled without leaving Develop.
if (/^[0-5]$/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) {
onUpdate(photo.id, { rating: Number(e.key) });
e.preventDefault();
return;
}
if (/^[6-9]$/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) {
const labels: ColorLabel[] = ['red', 'yellow', 'green', 'blue'];
onUpdate(photo.id, { color: labels[Number(e.key) - 6] });
e.preventDefault();
return;
}
if (e.key.toLowerCase() === 'j' && !e.metaKey && !e.ctrlKey && !e.altKey) {
e.preventDefault();
setClipping((cur) =>
e.shiftKey
? cur === 'shadows'
? null
: 'shadows'
: cur === 'highlights'
? null
: 'highlights',
);
return;
}
if (!e.metaKey && !e.ctrlKey && !e.altKey) {
const flagKey = e.key.toLowerCase();
if (flagKey === 'p' || flagKey === 'x' || flagKey === 'u') {
onUpdate(photo.id, { flag: flagKey === 'p' ? 'pick' : flagKey === 'x' ? 'reject' : 'none' });
e.preventDefault();
return;
}
}
if (e.key === 'ArrowRight') {
navigateFilm(1);
e.preventDefault();
} else if (e.key === 'ArrowLeft') {
navigateFilm(-1);
e.preventDefault();
} else if (e.key.toLowerCase() === 'q' && !e.metaKey && !e.ctrlKey && !e.altKey) {
toggleHeal();
e.preventDefault();
} else if (e.key.toLowerCase() === 'c' && !e.metaKey && !e.ctrlKey) {
setCropMode((v) => !v);
} else if (e.key.toLowerCase() === 'z' && !e.metaKey && !e.ctrlKey) {
toggleZoom();
e.preventDefault();
} else if (e.key.toLowerCase() === 'f' && !e.metaKey && !e.ctrlKey) {
toggleLoupe();
e.preventDefault();
} else if (e.key.toLowerCase() === 'm' && !e.metaKey && !e.ctrlKey && !e.altKey) {
if (activeLocal) {
toggleLocalMode();
e.preventDefault();
}
} else if (e.key === 'Enter' && cropMode) {
setCropMode(false);
} else if (e.key === 'Escape') {
// In fullscreen the browser handles Escape; don't also leave Develop.
if (document.fullscreenElement) return;
if (localMode) setLocalMode(false);
else if (healMode) setHealMode(false);
else if (cropMode) setCropMode(false);
else onExit();
} else if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'z') {
redo();
e.preventDefault();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
undo();
e.preventDefault();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c') {
onCopy();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') {
onPaste(filmSel);
}
};
const up = (e: KeyboardEvent) => {
if (e.key === '\\') setShowOriginal(false);
};
window.addEventListener('keydown', down);
window.addEventListener('keyup', up);
return () => {
window.removeEventListener('keydown', down);
window.removeEventListener('keyup', up);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
cropMode,
localMode,
activeLocal,
toggleLocalMode,
healMode,
onExit,
navigateFilm,
onCopy,
onPaste,
filmSel,
undo,
redo,
applyZoom,
zoomed,
onUpdate,
photo.id,
toggleLoupe,
toggleHeal,
]);
const applyPreset = useCallback(
(preset: Preset) => {
const next: Edits =
preset.id === 'original'
? { ...defaultEdits(), crop: photo.edits.crop }
: { ...photo.edits, ...preset.edits, crop: photo.edits.crop };
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
},
[onUpdate, photo.id, photo.edits],
);
const frame = bitmap
? rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter)
: { w: 1, h: 1 };
const lockedRatio = useMemo(() => {
const def = ASPECTS.find((a) => a.id === edits.crop.aspect);
return def?.ratio ?? null;
}, [edits.crop.aspect]);
// The same panel stack is used by the regular right rail and the fullscreen
// loupe overlay. Metadata stays in the rail so the overlay is purely tonal.
const adjustmentPanels = (includeMetadata: boolean) => (
<>
{cropMode && (
<CropPanel
edits={edits}
set={setEdits}
frame={frame}
onAspect={applyAspect}
onRotate={rotate}
onFlipPreview={() =>
setEdits({ crop: { ...edits.crop, flipH: !edits.crop.flipH } }, 'Flip horizontal')
}
mirrored={edits.crop.flipH}
/>
)}
<BasicPanel edits={edits} photo={photo} set={setEdits} picker={picking} onPicker={setPicking} />
<CurvePanel edits={edits} photo={photo} set={setEdits} />
<HslPanel edits={edits} photo={photo} set={setEdits} />
<ColorGradingPanel edits={edits} photo={photo} set={setEdits} />
<LocalPanel
edits={edits}
photo={photo}
set={setEdits}
activeId={localSelected}
onSelect={(id) => setLocalSelected(id)}
onAdd={addLocalLayer}
onDelete={deleteLocalLayer}
onDuplicate={duplicateLocalLayer}
onEditMask={toggleLocalMode}
maskMode={localMode}
brushSize={localBrush}
onBrushSize={setLocalBrush}
onCopyLayer={copyLocalLayer}
onPasteLayer={pasteLocalLayer}
canPaste={Boolean(localClipboard)}
onAutoMask={(kind) => void addAutoMask(kind)}
autoBusy={autoMaskBusy}
/>
<EffectsPanel edits={edits} photo={photo} set={setEdits} grainFreeze={cropDrag} />
<DetailPanel edits={edits} photo={photo} set={setEdits} />
<OpticsPanel
edits={edits}
photo={photo}
set={setEdits}
lensState={lensState}
lensSplit={lensSplit}
onLensSplit={setLensSplit}
/>
<ProofPanel edits={edits} photo={photo} set={setEdits} />
{includeMetadata && (
<MetadataPanel
photo={photo}
events={events}
onUpdate={(patch) => onUpdate(photo.id, patch)}
presets={metadataPresets}
keywordLibrary={keywordLibrary}
onSavePreset={onSaveMetadataPreset}
onDeletePreset={onDeleteMetadataPreset}
/>
)}
</>
);
const applyAspect = useCallback(
(id: string) => {
const def = ASPECTS.find((a) => a.id === id);
if (!def) return;
const f = bitmap
? rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter)
: { w: 1, h: 1 };
let w = 1;
let h = 1;
if (def.ratio) {
const frameRatio = f.w / f.h;
if (def.ratio > frameRatio) {
w = 1;
h = frameRatio / def.ratio;
} else {
h = 1;
w = def.ratio / frameRatio;
}
}
setEdits(
{ crop: { ...photo.edits.crop, x: (1 - w) / 2, y: (1 - h) / 2, w, h, aspect: id } },
def.ratio ? `Crop ${def.label}` : 'Crop',
);
},
[bitmap, photo.edits.crop, setEdits],
);
const rotate = useCallback(
(dir: -1 | 1) => {
const c = photo.edits.crop;
const quarter = ((c.quarter + dir) % 4 + 4) % 4;
const rect =
dir === 1
? { x: 1 - (c.y + c.h), y: c.x, w: c.h, h: c.w }
: { x: c.y, y: 1 - (c.x + c.w), w: c.h, h: c.w };
setEdits(
{ crop: { ...c, quarter, ...rect } },
dir === 1 ? 'Rotate 90° right' : 'Rotate 90° left',
);
},
[photo.edits.crop, setEdits],
);
const resetAll = () => {
if (!window.confirm('Reset all develop settings for this photo?')) return;
onUpdate(photo.id, { edits: { ...defaultEdits(), crop: photo.edits.crop } }, 'Reset');
};
const canvasMenu: MenuEntry[] = [
{ label: 'Zoom to Fit', shortcut: 'Z', onSelect: () => applyZoom('fit') },
{ label: 'Zoom to 100%', onSelect: () => applyZoom(100) },
'separator',
{ label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) },
{ label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) },
'separator',
{ label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy },
{ label: 'Paste settings', shortcut: '⌘V', onSelect: () => onPaste([photo.id]), disabled: !clipboard },
{ label: 'Reset settings', onSelect: resetAll },
'separator',
...(canPushImmich && onPushImmich
? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[])
: []),
...(onOpenImmich
? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[])
: []),
{ label: 'Export…', onSelect: onExport },
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
];
// Right-clicking one of several selected frames acts on the whole selection;
// right-clicking outside it acts on that frame alone.
const filmMenuIds = menu?.kind === 'film' && menu.ids?.length ? menu.ids : [photo.id];
const filmMenu: MenuEntry[] = [
{
label: 'Open in Develop',
disabled: filmMenuIds.includes(photo.id),
onSelect: () => onSelect(filmMenuIds[0]),
},
'separator',
{
label: 'Copy settings',
onSelect: () => (onCopyOf ? onCopyOf(filmMenuIds[0]) : onCopy()),
},
{
label:
filmMenuIds.length > 1
? `Paste settings to ${filmMenuIds.length} photos…`
: 'Paste settings',
onSelect: () => onPaste(filmMenuIds),
disabled: !clipboard,
},
{
label:
filmMenuIds.length > 1
? `Reset adjustments on ${filmMenuIds.length} photos`
: 'Reset settings',
onSelect: () =>
filmMenuIds.length > 1 && onResetSelection
? onResetSelection(filmMenuIds)
: resetAll(),
},
'separator',
...(canPushImmich && onPushImmich
? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[])
: []),
...(onOpenImmich
? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[])
: []),
{ label: 'Export…', onSelect: onExport },
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
];
const index = photos.findIndex((p) => p.id === photo.id);
return (
<div className={`develop ${cropMode ? 'cropping' : ''} ${mobile ? 'mobile' : ''} ${mobile && mobileAdjustOpen ? 'adjusting' : ''}`}>
<div className="dev-toolbar">
<button className="btn ghost small" onClick={onExit}>
← Library
</button>
<div className="dev-title">
<strong title={photo.name}>{photo.name}</strong>
<span className="muted small">
{index >= 0 ? `${index + 1} / ${photos.length}` : ''} · {photo.width}×{photo.height}
</span>
</div>
<Stars value={photo.rating} onChange={(r) => onUpdate(photo.id, { rating: r })} size="md" />
<FlagButtons value={photo.flag} onChange={(f) => onUpdate(photo.id, { flag: f })} />
<ColorSwatches value={photo.color} onChange={(c) => onUpdate(photo.id, { color: c })} />
<div className="spacer" />
<button
className={`btn ghost small ${showOriginal ? 'on' : ''}`}
onClick={() => setShowOriginal((v) => !v)}
title="Toggle before / after (hold \)"
>
Before / After
</button>
<button className={`btn ghost small ${cropMode ? 'on' : ''}`} onClick={() => setCropMode((v) => !v)} title="Crop & straighten (C)">
Crop
</button>
<button
className={`btn ghost small ${healMode ? 'on' : ''}`}
onClick={toggleHeal}
title="Spot healing (Q)"
>
Heal
</button>
<button className="btn ghost small" onClick={onCopy} title="Copy develop settings (⌘C)">
Copy
</button>
<button className="btn ghost small" onClick={onVirtualCopy} title="Create a virtual copy with its own edits">
Virtual copy
</button>
<button
className="btn ghost small"
onClick={() => onPaste(filmSel)}
disabled={!clipboard || !filmSel.length}
title={
filmSel.length > 1
? `Paste develop settings to ${filmSel.length} selected photos (⌘V)`
: 'Paste develop settings (⌘V)'
}
>
Paste{filmSel.length > 1 ? ` (${filmSel.length})` : ''}
</button>
<button className="btn ghost small" onClick={undo} disabled={!canUndo} title="Undo (⌘Z)">
Undo
</button>
<button
className="btn ghost small"
onClick={redo}
disabled={!canRedo}
title="Redo (⌘⇧Z)"
>
Redo
</button>
<button className="btn ghost small" onClick={resetAll}>
Reset
</button>
<button className="btn ghost small danger" onClick={onDelete}>
Delete
</button>
<button className="btn ghost small" onClick={onPrint} title="Print this photo">
Print
</button>
<button className="btn primary small" onClick={onExport}>
Export
</button>
</div>
{!mobile && !tipDismissed && (
<div className="dev-tip">
<span>
Hover a panel seam to collapse it · <strong>⌘K</strong> searches everything · <strong>?</strong> shows shortcuts
</span>
<button type="button" className="link-btn" onClick={() => setTipDismissed(true)}>
Got it
</button>
</div>
)}
{mobile && (
<>
<div className="dev-mobile-bar">
<button type="button" className="icon-btn" onClick={onExit} aria-label="Back to library" title="Back to library">
←
</button>
<button
type="button"
className="dev-mobile-nav"
onClick={() => navigateFilm(-1)}
aria-label="Previous photo"
title="Previous photo"
>
‹
</button>
<div className="dev-mobile-title">
<strong>{photo.name}</strong>
<span>
{filmPosition >= 0 ? filmPosition + 1 : '–'} / {filmPhotos.length}
</span>
</div>
<button
type="button"
className="dev-mobile-nav"
onClick={() => navigateFilm(1)}
aria-label="Next photo"
title="Next photo"
>
›
</button>
<button
type="button"
className={`chip ${mobileStripOpen ? 'on' : ''}`}
onClick={() => setMobileStripOpen((open) => !open)}
>
Photos
</button>
<button
type="button"
className={`btn primary small ${mobileAdjustOpen ? 'on' : ''}`}
onClick={() => setMobileAdjustOpen((open) => !open)}
>
Adjust
</button>
</div>
<div className="dev-mobile-meta">
<Stars value={photo.rating} onChange={(rating) => onUpdate(photo.id, { rating })} size="md" />
<FlagButtons value={photo.flag} onChange={(flag) => onUpdate(photo.id, { flag })} />
<span className="muted small">
{photo.meta.camera ?? 'Camera'} {photo.meta.focal ? `· ${photo.meta.focal}mm` : ''}
</span>
</div>
</>
)}
<div className="dev-body">
<aside id="dev-left-panel" className={`dev-left ${leftOpen ? '' : 'collapsed'}`}>
<NavigatorPanel
photo={photo}
content={cropMode ? { x: 0, y: 0, w: 1, h: 1 } : edits.crop}
view={navigatorView}
zoomed={zoomed}
zoomLabel={zoomed ? `${readout.shown}%` : 'Fit'}
onNavigate={navigateZoom}
/>
<PresetsPanel
presets={presets}
photo={photo}
onApply={applyPreset}
onSave={(name) => onSavePreset(name, photo.edits)}
/>
<SnapshotsPanel
snapshots={photo.snapshots ?? []}
onSave={onSaveSnapshot}
onRestore={onRestoreSnapshot}
onDelete={onDeleteSnapshot}
/>
<HistoryPanel history={photo.history} onRestore={(next) => onUpdate(photo.id, { edits: next })} />
</aside>
<button
type="button"
className={`dev-edge left ${leftOpen ? '' : 'closed'}`}
onClick={() => setLeftOpen((open) => !open)}
aria-controls="dev-left-panel"
aria-expanded={leftOpen}
aria-label={leftOpen ? 'Collapse left panels' : 'Expand left panels'}
title={leftOpen ? 'Collapse left panels' : 'Expand left panels'}
>
<span className="dev-edge-tab" aria-hidden="true">{leftOpen ? '‹' : '›'}</span>
</button>
<div
className={`canvas-stage ${zoomed ? 'zoomed' : ''} ${panning ? 'panning' : ''}`}
ref={stageRef}
onContextMenu={(e) => {
e.preventDefault();
setMenu({ x: e.clientX, y: e.clientY, kind: 'canvas' });
}}
>
{error ? (
<div className="banner error">{error}</div>
) : (
<div className="canvas-wrap">
<canvas
ref={canvasRef}
className={`preview ${zoomed ? 'zoomed' : ''} ${picking ? 'picking' : ''} ${healMode ? 'healing' : ''} ${localMode ? 'masking' : ''}`}
onClick={pickWhiteBalance}
onPointerDown={(e) => {
if (localMode) startLocalMask(e);
else if (healMode) startHeal(e);
else beginPan(e);
}}
onPointerMove={(e) => {
if (localMode) moveLocalMask(e);
else if (healMode) moveHeal(e);
else movePan(e);
}}
onPointerUp={(e) => {
if (localMode) endLocalMask(e);
else if (healMode) endHeal(e);
else endPan(e);
}}
onPointerCancel={(e) => {
if (localMode) endLocalMask(e);
else if (healMode) endHeal(e);
else endPan(e);
}}
onPointerLeave={() => {
setHealHover(null);
setLocalHover(null);
}}
onDoubleClick={(e) => {
if (healMode || localMode) return;
toggleZoom(e.clientX, e.clientY);
}}
/>
{lensSplit && lensCorrection && !showOriginal && (
<div className="lens-split">
<div className="lens-split-line" style={{ left: `${lensSplitAt * 100}%` }} />
<span className="lens-split-label before">Before</span>
<span className="lens-split-label after">After</span>
<button
type="button"
className="lens-split-handle"
style={{ left: `${lensSplitAt * 100}%` }}
aria-label="Drag to move the lens correction split"
title="Drag to compare lens correction"
onPointerDown={(e) => {
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
moveLensSplit(e);
}}
onPointerMove={(e) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) moveLensSplit(e);
}}
onPointerUp={(e) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
}}
onPointerCancel={(e) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
}}
>
↔
</button>
</div>
)}
{healMode && bitmap && (() => {
const geo = geoRef.current;
const view = geo.view;
const marker = (p: { x: number; y: number }) => {
const f = sourceToFrame(
unwarpGeometryPoint(
uncorrectLensPoint(lensCorrection, p.x, p.y),
edits.geometry,
bitmap.width,
bitmap.height,
),
bitmap.width,
bitmap.height,
edits.crop.angle,
edits.crop.quarter,
edits.crop.flipH,
edits.crop.flipV,
);
return {
x: ((f.x - view.x) / view.w) * 100,
y: ((f.y - view.y) / view.h) * 100,
};
};
const rx = (r: number) => ((r * bitmap.width) / (frame.w * view.w)) * 100;
const ry = (r: number) => ((r * bitmap.width) / (frame.h * view.h)) * 100;
const spots = edits.heal ?? [];
const hoverR = brushRadius();
return (
<svg className="heal-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
{spots.map((spot, i) => {
const t = marker(spot);
const s = marker({ x: spot.sx, y: spot.sy });
const on = i === healSelected;
// Matches the shader: feather acts on the outer half at most.
const inner = Math.max(0, 1 - (spot.feather / 100) * 0.5);
return (
<g key={i}>
{on && <line x1={t.x} y1={t.y} x2={s.x} y2={s.y} className="heal-link" />}
{on && (
<ellipse
cx={s.x}
cy={s.y}
rx={rx(spot.r)}
ry={ry(spot.r)}
className="heal-source"
vectorEffect="non-scaling-stroke"
/>
)}
<ellipse
cx={t.x}
cy={t.y}
rx={rx(spot.r)}
ry={ry(spot.r)}
className={`heal-ring ${on ? 'on' : ''}`}
vectorEffect="non-scaling-stroke"
/>
{inner > 0.02 && (
<ellipse
cx={t.x}
cy={t.y}
rx={rx(spot.r * inner)}
ry={ry(spot.r * inner)}
className="heal-feather"
vectorEffect="non-scaling-stroke"
/>
)}
</g>
);
})}
{healHover && !healDrag.current && (
<ellipse
cx={marker(healHover).x}
cy={marker(healHover).y}
rx={rx(hoverR)}
ry={ry(hoverR)}
className="heal-cursor"
vectorEffect="non-scaling-stroke"
/>
)}
</svg>
);
})()}
{localMode && bitmap && activeLocal && (() => {
const geo = geoRef.current;
const view = geo.view;
const marker = (p: { x: number; y: number }) => {
const source = unwarpGeometryPoint(
uncorrectLensPoint(lensCorrection, p.x, p.y),
edits.geometry,
bitmap.width,
bitmap.height,
);
const f = sourceToFrame(
source,
bitmap.width,
bitmap.height,
edits.crop.angle,
edits.crop.quarter,
edits.crop.flipH,
edits.crop.flipV,
);
return {
x: ((f.x - view.x) / view.w) * 100,
y: ((f.y - view.y) / view.h) * 100,
};
};
const xScale = bitmap.width / (frame.w * view.w);
const canvasEl = canvasRef.current;
const canvasW = canvasEl?.clientWidth || 1;
const canvasH = canvasEl?.clientHeight || 1;
const strokes = localDraft
? [...activeLocal.brush.strokes, localDraft]
: activeLocal.brush.strokes;
return (
<svg className="local-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
{activeLocal.kind === 'brush' &&
strokes.map((stroke, i) => {
if (!stroke.points.length) return null;
const points = stroke.points.map(marker).map((p) => `${p.x},${p.y}`).join(' ');
const width = Math.max(1, stroke.size * 2 * canvasW);
return (
<polyline
key={i}
points={points}
className={`local-brush ${stroke.erase ? 'erase' : ''}`}
strokeWidth={width}
vectorEffect="non-scaling-stroke"
/>
);
})}
{activeLocal.kind === 'radial' && (() => {
const c = marker({ x: activeLocal.radial.cx, y: activeLocal.radial.cy });
const edge = marker({
x: activeLocal.radial.cx + activeLocal.radial.rx,
y: activeLocal.radial.cy,
});
const edgeY = marker({
x: activeLocal.radial.cx,
y: activeLocal.radial.cy + activeLocal.radial.ry,
});
// Sample the perimeter so the guide follows the same warp
// as the picture instead of staying a screen-space ellipse.
const ring = Array.from({ length: 72 }, (_, i) => {
const angle = (i / 72) * Math.PI * 2;
const p = marker({
x: activeLocal.radial.cx + Math.cos(angle) * activeLocal.radial.rx,
y: activeLocal.radial.cy + Math.sin(angle) * activeLocal.radial.ry,
});
return `${p.x},${p.y}`;
}).join(' ');
return (
<g>
<polygon
points={ring}
className="local-outline"
vectorEffect="non-scaling-stroke"
/>
<circle cx={c.x} cy={c.y} r={2.2} className="local-handle" />
<circle cx={edge.x} cy={edge.y} r={1.7} className="local-handle edge" />
<circle cx={edgeY.x} cy={edgeY.y} r={1.7} className="local-handle edge" />
</g>
);
})()}
{activeLocal.kind === 'linear' && (() => {
const a = marker({ x: activeLocal.linear.x1, y: activeLocal.linear.y1 });
const b = marker({ x: activeLocal.linear.x2, y: activeLocal.linear.y2 });
return (
<g>
<line x1={a.x} y1={a.y} x2={b.x} y2={b.y} className="local-line" vectorEffect="non-scaling-stroke" />
<circle cx={a.x} cy={a.y} r={2.2} className="local-handle" />
<circle cx={b.x} cy={b.y} r={2.2} className="local-handle" />
</g>
);
})()}
{activeLocal.kind === 'brush' && localHover && !localDrag.current && (
<ellipse
cx={marker(localHover).x}
cy={marker(localHover).y}
rx={localRadius() * xScale * 100}
ry={localRadius() * 100 * (canvasW / canvasH)}
className="local-cursor"
vectorEffect="non-scaling-stroke"
/>
)}
</svg>
);
})()}
{cropMode && bitmap && (
<CropOverlay
crop={photo.edits.crop}
frame={frame}
ratio={lockedRatio}
bitmap={bitmap}
edits={edits}
onChange={(rect) => setEdits({ crop: { ...photo.edits.crop, ...rect } }, 'Crop')}
onDragChange={setCropDrag}
/>
)}
</div>
)}
{localMode && activeLocal && !error && (
<div className="heal-hud local-hud">
<span className="heal-hud-title">Local · {activeLocal.kind}</span>
{activeLocal.kind === 'brush' && (
<>
<label className="heal-field">
Size
<input
type="range"
min={8}
max={320}
step={1}
value={localBrush}
onChange={(e) => setLocalBrush(Number(e.target.value))}
/>
</label>
<span className="heal-read">{Math.round(localBrush)}px</span>
</>
)}
{activeLocal.kind !== 'linear' && (
<>
<label className="heal-field">
Feather
<input
type="range"
min={0}
max={100}
step={1}
value={activeLocal.feather}
onChange={(e) => patchLocal(activeLocal.id, { feather: Number(e.target.value) }, 'Local feather')}
/>
</label>
<span className="heal-read">{Math.round(activeLocal.feather)}%</span>
</>
)}
<button
className="heal-act"
onClick={() => {
if (activeLocal.kind === 'brush') {
patchLocal(activeLocal.id, { brush: { strokes: [] } }, 'Clear local mask');
} else if (activeLocal.kind === 'radial') {
patchLocal(
activeLocal.id,
{ radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 } },
'Reset local mask',
);
} else {
patchLocal(
activeLocal.id,
{ linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 } },
'Reset local mask',
);
}
}}
>
Clear
</button>
<button className="heal-act on" onClick={() => setLocalMode(false)}>
Done
</button>
<span className="heal-tip">
{activeLocal.kind === 'brush'
? 'Paint the mask · Alt paints an erase stroke · wheel sizes the brush'
: activeLocal.kind === 'radial'
? 'Drag the centre or the edge handle · wheel zooms'
: 'Drag either end of the gradient'}
</span>
</div>
)}
{healMode && !error && (
<div className="heal-hud">
<span className="heal-hud-title">Healing</span>
<label className="heal-field">
Size
<input
type="range"
min={14}
max={240}
step={1}
value={brushPx}
onChange={(e) => setBrushPx(Number(e.target.value))}
/>
</label>
<span className="heal-read">{brushPx}px</span>
<label className="heal-field">
Feather
<input
type="range"
min={0}
max={100}
step={1}
value={healFeather}
onChange={(e) => setFeather(Number(e.target.value))}
/>
</label>
<span className="heal-read">{healFeather}%</span>
<span className="heal-count">
{(edits.heal ?? []).length} spot{(edits.heal ?? []).length === 1 ? '' : 's'}
</span>
<button
className="heal-act"
onClick={removeHealSpot}
disabled={!(edits.heal ?? []).length}
>
Remove
</button>
<button
className="heal-act"
onClick={() => {
commitHeal([]);
setHealSelected(null);
}}
disabled={!(edits.heal ?? []).length}
>
Clear
</button>
<button className="heal-act on" onClick={() => setHealMode(false)}>
Done
</button>
<span className="heal-tip">Click a blemish · Alt-drag moves the sample · wheel sizes the brush</span>
</div>
)}
{loading && <div className="canvas-loading">Loading original…</div>}
{cropMode && <div className="crop-hint">Drag the edges to crop · Enter to apply · Esc to cancel</div>}
{!cropMode && !error && (
<div className="zoom-bar">
<button
className={`zoom-btn ${zoomed ? '' : 'on'}`}
onClick={() => applyZoom('fit')}
title="Fit to window (Z)"
>
Fit
</button>
<button
className={`zoom-btn ${zoomed && readout.shown === 100 ? 'on' : ''}`}
onClick={() => applyZoom(100)}
disabled={readout.fit >= 100}
title="Actual pixels"
>
100%
</button>
<span className="zoom-pct">{readout.shown}%</span>
<button
className={`zoom-btn ${loupe ? 'on' : ''}`}
onClick={toggleLoupe}
title="Full-screen loupe (F)"
>
{loupe ? 'Exit' : 'Loupe'}
</button>
</div>
)}
{zoomed && !cropMode && <div className="crop-hint">Drag to pan · scroll to zoom · double-click to fit</div>}
{showOriginal && <div className="before-badge">Before</div>}
{loupe && !cropMode && (
<div className="loupe-cull" aria-label="Photo culling controls">
<button
type="button"
className="loupe-cull-nav"
onClick={() => navigateFilm(-1)}
title="Previous photo (←)"
>
‹
</button>
<div className="loupe-cull-position">
<strong>{filmPosition >= 0 ? filmPosition + 1 : '–'}</strong>
<span>/ {filmPhotos.length}</span>
{filmFilterActive && <em>filtered</em>}
</div>
<div className="loupe-cull-rating">
<Stars
value={photo.rating}
onChange={(rating) => onUpdate(photo.id, { rating })}
size="md"
/>
<FlagButtons
value={photo.flag}
onChange={(flag) => onUpdate(photo.id, { flag })}
/>
</div>
<button
type="button"
className="loupe-cull-nav"
onClick={() => navigateFilm(1)}
title="Next photo (→)"
>
›
</button>
</div>
)}
{clipPreview && (
<div className="clip-legend">
<span className="clip-dot r" /> red
<span className="clip-dot g" /> green
<span className="clip-dot b" /> blue
<span className="clip-dot y" /> two channels
<span className="clip-dot w" /> all three
</div>
)}
{loupe && !adjustOpen && (
<button
type="button"
className="loupe-adjust-tab"
onClick={() => setAdjustOpen(true)}
title="Open the adjustment panel"
>
Adjustments
</button>
)}
{loupe && adjustOpen && (
<aside className="loupe-adjust" aria-label="Develop adjustments">
<div className="loupe-adjust-head">
<div>
<strong>Adjustments</strong>
<span>{photo.name}</span>
</div>
<button
type="button"
className="icon-btn"
onClick={() => setAdjustOpen(false)}
aria-label="Close adjustments"
title="Close adjustments"
>
×
</button>
</div>
<div className="loupe-adjust-scroll">
<div className="histo-wrap loupe-histo">
<Histogram
data={histRef.current}
version={histVersion}
clipping={clipping}
onClipping={setClipping}
/>
<div className="histo-legend">
<span>ISO {photo.meta.iso ?? '—'}</span>
<span>{photo.meta.aperture ? `f/${photo.meta.aperture}` : '—'}</span>
<span>{photo.meta.shutter ?? '—'}</span>
<span>{photo.meta.focal ? `${photo.meta.focal}mm` : '—'}</span>
</div>
</div>
{adjustmentPanels(false)}
</div>
</aside>
)}
</div>
<aside
id="dev-right-panel"
className={`dev-right ${rightOpen ? '' : 'collapsed'} ${mobileAdjustOpen ? 'mobile-open' : ''}`}
>
{mobile && (
<>
<div className="dev-mobile-sheet-head">
<div>
<strong>Adjustments</strong>
<span>{photo.name}</span>
</div>
<button
type="button"
className="icon-btn"
onClick={() => setMobileAdjustOpen(false)}
aria-label="Close adjustments"
title="Close adjustments"
>
×
</button>
</div>
<div className="dev-mobile-actions">
<button type="button" className="btn ghost small" onClick={undo} disabled={!canUndo}>
Undo
</button>
<button type="button" className="btn ghost small" onClick={redo} disabled={!canRedo}>
Redo
</button>
<button
type="button"
className={`btn ghost small ${cropMode ? 'on' : ''}`}
onClick={() => setCropMode((v) => !v)}
>
Crop
</button>
<button
type="button"
className={`btn ghost small ${healMode ? 'on' : ''}`}
onClick={toggleHeal}
>
Heal
</button>
<button type="button" className="btn ghost small" onClick={onCopy}>
Copy
</button>
<button
type="button"
className="btn ghost small"
onClick={() => onPaste(filmSel)}
disabled={!clipboard || !filmSel.length}
>
Paste{filmSel.length > 1 ? ` (${filmSel.length})` : ''}
</button>
<button type="button" className="btn ghost small" onClick={resetAll}>
Reset
</button>
<button type="button" className="btn primary small" onClick={onExport}>
Export
</button>
</div>
</>
)}
<div className="histo-wrap">
<Histogram
data={histRef.current}
version={histVersion}
clipping={clipping}
onClipping={setClipping}
/>
<div className="histo-legend">
<span>ISO {photo.meta.iso ?? '—'}</span>
<span>{photo.meta.aperture ? `f/${photo.meta.aperture}` : '—'}</span>
<span>{photo.meta.shutter ?? '—'}</span>
<span>{photo.meta.focal ? `${photo.meta.focal}mm` : '—'}</span>
</div>
</div>
<div className="panel-scroll">{adjustmentPanels(true)}</div>
</aside>
<button
type="button"
className={`dev-edge right ${rightOpen ? '' : 'closed'}`}
onClick={() => setRightOpen((open) => !open)}
aria-controls="dev-right-panel"
aria-expanded={rightOpen}
aria-label={rightOpen ? 'Collapse adjustment panels' : 'Expand adjustment panels'}
title={rightOpen ? 'Collapse adjustment panels' : 'Expand adjustment panels'}
>
<span className="dev-edge-tab" aria-hidden="true">{rightOpen ? '›' : '‹'}</span>
</button>
</div>
<div className={`film-deck ${shownStripOpen ? '' : 'collapsed'}`}>
<button
type="button"
className="film-edge"
onClick={toggleStrip}
aria-controls="filmstrip-panel"
aria-expanded={shownStripOpen}
aria-label={shownStripOpen ? 'Collapse filmstrip' : 'Expand filmstrip'}
title={shownStripOpen ? 'Collapse filmstrip' : 'Expand filmstrip'}
>
<span className="film-edge-tab" aria-hidden="true">{shownStripOpen ? '▾' : '▴'}</span>
</button>
<div className="film-bar">
<button
type="button"
className="film-collapse"
onClick={toggleStrip}
aria-expanded={shownStripOpen}
title={shownStripOpen ? 'Collapse filmstrip' : 'Expand filmstrip'}
>
<span className="chev">{shownStripOpen ? '▾' : '▸'}</span>
<span>Filmstrip</span>
</button>
<div className="film-filter">
<span className="film-filter-label">Rating</span>
{[0, 1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
className={`film-chip ${filmMinRating === n ? 'on' : ''}`}
onClick={() => setFilmMinRating(n)}
title={n === 0 ? 'Any rating' : `${n} stars and up`}
>
{n === 0 ? 'Any' : `${n}★+`}
</button>
))}
</div>
<div className="film-filter">
<span className="film-filter-label">Flag</span>
{(['any', 'pick', 'none', 'reject'] as const).map((value) => (
<button
key={value}
type="button"
className={`film-chip ${filmFlag === value ? 'on' : ''}`}
onClick={() => setFilmFlag(value)}
title={value === 'any' ? 'Any flag' : value === 'pick' ? 'Picked only' : value === 'none' ? 'Unflagged only' : 'Rejected only'}
>
{value === 'any' ? 'Any' : value === 'pick' ? 'Picked' : value === 'none' ? 'Unflagged' : 'Rejected'}
</button>
))}
</div>
{filmFilterActive && (
<button
type="button"
className="chip ghost small"
onClick={() => {
setFilmMinRating(0);
setFilmFlag('any');
}}
>
Clear filter
</button>
)}
{filmFilterActive && !currentInFilm && (
<>
<span className="film-hidden-note">Current photo is hidden by this filter</span>
<button
type="button"
className="film-show-current"
onClick={() => {
setFilmMinRating(0);
setFilmFlag('any');
}}
>
Show current
</button>
</>
)}
<div className="spacer" />
{filmSel.length > 1 && (
<span className="film-count">{filmSel.length} selected</span>
)}
<span className="film-count">
{filmPhotos.length} / {photos.length}
</span>
</div>
{shownStripOpen && (
<div id="filmstrip-panel" className="filmstrip" ref={stripRef}>
{filmPhotos.map((p) => (
<button
key={p.id}
className={`film ${p.id === photo.id ? 'active' : ''} ${
filmSel.includes(p.id) ? 'selected' : ''
}`}
onClick={(e) => clickFilm(p, e)}
onContextMenu={(e) => {
e.preventDefault();
const inSelection = filmSel.includes(p.id);
const ids = inSelection ? filmSel : [p.id];
if (!inSelection) {
setFilmSel([p.id]);
setFilmAnchor(p.id);
if (p.id !== photo.id) onSelect(p.id);
}
setMenu({ x: e.clientX, y: e.clientY, kind: 'film', ids });
}}
title={
filmSel.length > 1 && filmSel.includes(p.id)
? `${p.name} · ${filmSel.length} selected`
: `${p.name} · Shift-click or Ctrl-click to select more`
}
>
<EditedImage photo={p} alt={p.name} boxAspect={3 / 2} />
{p.rating > 0 && <span className="film-rating">{'★'.repeat(p.rating)}</span>}
</button>
))}
{!filmPhotos.length && (
<div className="film-empty">No photos match this filter.</div>
)}
</div>
)}
</div>
{menu && (
<ContextMenu
x={menu.x}
y={menu.y}
onClose={() => setMenu(null)}
header={
menu.kind === 'film' ? (
<div className="ctx-rows">
<Stars value={photo.rating} onChange={(r) => onUpdate(photo.id, { rating: r })} size="md" />
<FlagButtons value={photo.flag} onChange={(f) => onUpdate(photo.id, { flag: f })} />
<ColorSwatches value={photo.color} onChange={(c) => onUpdate(photo.id, { color: c })} />
</div>
) : undefined
}
entries={menu.kind === 'canvas' ? canvasMenu : filmMenu}
/>
)}
</div>
);
}