feat(editor): bridge the advanced photo editor into the event workflow
CI / build (push) Has been cancelled

Event photos can now be opened in Lumenroom, a WebGL2 develop module, from the
photo editor's Advanced button. The dashboard signs a short-lived token scoped
to one user and event; Lumenroom exchanges it, imports the event's photo list
and proxies bytes on demand, so nothing is copied and the temporary catalog
expires with the bridge session. Saving in Lumenroom renders the photo and
writes it back as the event's edited JPEG, with the advanced recipe kept in
event_photos.advanced_edit_json.

Lumenroom is vendored under lumenroom/ and built as a second compose service,
so one clone and `docker compose up -d --build` deploys both apps.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-21 01:34:20 +00:00
parent 982f9048e1
commit 0cb315ea88
89 changed files with 22087 additions and 1 deletions
File diff suppressed because it is too large Load Diff
+196
View File
@@ -0,0 +1,196 @@
import { useEffect, useState } from 'react';
import type { Health, SessionUser } from '../lib/api';
interface Props {
health: Health | null;
user: SessionUser | null;
busy: boolean;
note: string | null;
error: string | null;
onLogin: (email: string, password: string) => void;
onRegister: (input: { email: string; password: string; name: string; invite: string }) => void;
onLogout: () => void;
onSync: () => void;
onClose: () => void;
}
function fmtBytes(bytes: number) {
if (bytes > 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
if (bytes > 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`;
return `${Math.round(bytes / 1024)} KB`;
}
export default function CloudPanel({
health,
user,
busy,
note,
error,
onLogin,
onRegister,
onLogout,
onSync,
onClose,
}: Props) {
const [mode, setMode] = useState<'signin' | 'signup'>('signin');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [invite, setInvite] = useState('');
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const submit = () => {
if (busy) return;
if (mode === 'signin') onLogin(email.trim(), password);
else onRegister({ email: email.trim(), password, name: name.trim(), invite: invite.trim() });
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal cloud-modal">
<header className="modal-head">
<h2>Team server</h2>
<button className="icon-btn" onClick={onClose}>
✕
</button>
</header>
<div className="modal-body">
{!health ? (
<div className="cloud-offline">
<strong>No server detected</strong>
<p className="muted small">
The library is running fully in this browser. To share photos with the team, start the
server and reload:
</p>
<pre className="code-block">npm run server</pre>
<p className="muted small">
Originals, edits and ratings are then stored on disk under <code>server/data</code>.
</p>
</div>
) : user ? (
<div className="cloud-account">
<div className="cloud-hero">
<div className="cloud-avatar">{(user.name || user.email).slice(0, 1).toUpperCase()}</div>
<div>
<strong>{user.name || user.email}</strong>
<div className="muted small">
{user.email} · {user.role}
</div>
</div>
</div>
<dl className="cloud-stats">
<div>
<dt>Photos on server</dt>
<dd>{health.photos}</dd>
</div>
<div>
<dt>Storage used</dt>
<dd>{fmtBytes(health.bytes)}</dd>
</div>
<div>
<dt>Raw engine</dt>
<dd>{health.raw.libraw ? 'LibRaw demosaic' : 'Embedded previews'}</dd>
</div>
<div>
<dt>Server version</dt>
<dd>{health.version}</dd>
</div>
</dl>
<div className="btn-row">
<button className="btn primary" onClick={onSync} disabled={busy}>
{busy ? 'Syncing…' : 'Sync library'}
</button>
<button className="btn ghost" onClick={onLogout} disabled={busy}>
Sign out
</button>
</div>
{note && <div className="banner ok">{note}</div>}
</div>
) : (
<>
<div className="tabs">
<button className={`tab ${mode === 'signin' ? 'on' : ''}`} onClick={() => setMode('signin')}>
Sign in
</button>
<button className={`tab ${mode === 'signup' ? 'on' : ''}`} onClick={() => setMode('signup')}>
{health.needsSetup ? 'Create admin' : 'Join team'}
</button>
</div>
<label className="field">
<span>Email</span>
<input
type="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && submit()}
/>
</label>
{mode === 'signup' && (
<label className="field">
<span>Display name</span>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Optional" />
</label>
)}
<label className="field">
<span>Password</span>
<input
type="password"
autoComplete={mode === 'signin' ? 'current-password' : 'new-password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && submit()}
/>
</label>
{mode === 'signup' && !health.needsSetup && (
<label className="field">
<span>Invite code</span>
<input
value={invite}
onChange={(e) => setInvite(e.target.value)}
placeholder="From your admin"
/>
</label>
)}
{mode === 'signup' && health.needsSetup && (
<p className="muted small">
The first account becomes the team admin. Share the invite code you set in{' '}
<code>LUMENROOM_INVITE</code> with everyone else.
</p>
)}
<button className="btn primary wide" onClick={submit} disabled={busy || !email || !password}>
{busy ? 'Working…' : mode === 'signin' ? 'Sign in' : 'Create account'}
</button>
</>
)}
{error && <div className="banner error">{error}</div>}
{health && (
<p className="muted small cloud-foot">
Server sharing the folder <code>server/data</code> · raw formats:{' '}
{health.raw.formats.length} · {health.raw.sharp ? 'JPEG encoder ready' : 'PNG fallback'}
</p>
)}
</div>
</div>
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
export interface MenuAction {
label: string;
shortcut?: string;
onSelect: () => void;
disabled?: boolean;
danger?: boolean;
}
export type MenuEntry = MenuAction | 'separator';
interface Props {
x: number;
y: number;
entries: MenuEntry[];
header?: ReactNode;
onClose: () => void;
}
/**
* Right-click menu anchored to the pointer. Rendered in a portal so the app's
* scroll containers and panel overflow cannot clip it, and nudged inside the
* window when the cursor is close to an edge.
*/
export default function ContextMenu({ x, y, entries, header, onClose }: Props) {
const ref = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const margin = 8;
setPos({
left: Math.max(margin, Math.min(x, window.innerWidth - rect.width - margin)),
top: Math.max(margin, Math.min(y, window.innerHeight - rect.height - margin)),
});
}, [x, y]);
useEffect(() => {
const onPointerDown = (e: PointerEvent) => {
if (ref.current && e.target instanceof Node && ref.current.contains(e.target)) return;
onClose();
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
onClose();
};
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('resize', onClose);
window.addEventListener('blur', onClose);
window.addEventListener('wheel', onClose, { passive: true });
return () => {
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('keydown', onKeyDown, true);
window.removeEventListener('resize', onClose);
window.removeEventListener('blur', onClose);
window.removeEventListener('wheel', onClose);
};
}, [onClose]);
return createPortal(
<div
ref={ref}
className="ctx-menu"
role="menu"
style={{ left: pos?.left ?? x, top: pos?.top ?? y, visibility: pos ? 'visible' : 'hidden' }}
onContextMenu={(e) => e.preventDefault()}
>
{header && <div className="ctx-header">{header}</div>}
{entries.map((entry, i) =>
entry === 'separator' ? (
<div className="ctx-sep" key={`sep-${i}`} />
) : (
<button
key={`${entry.label}-${i}`}
type="button"
role="menuitem"
className={`ctx-item ${entry.danger ? 'danger' : ''}`}
disabled={entry.disabled}
onClick={() => {
onClose();
entry.onSelect();
}}
>
<span>{entry.label}</span>
{entry.shortcut && <span className="ctx-key">{entry.shortcut}</span>}
</button>
),
)}
</div>,
document.body,
);
}
+268
View File
@@ -0,0 +1,268 @@
import { useEffect, useRef, useState, type PointerEvent } from 'react';
import { clamp } from '../lib/curves';
import { grainSampleWindow, Renderer } from '../gl/renderer';
import type { CropState, Edits } from '../types';
type Mode = 'move' | 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
/**
* Point (frame uv) the loupe sits on when dragged to `u`,`v` inside the crop
* rectangle, kept a half-box away from its edges so the patch stays inside.
*/
export function clampLoupe(
crop: { x: number; y: number; w: number; h: number },
u: number,
v: number,
halfU: number,
halfV: number,
) {
const cx = Math.min(1 - halfU, Math.max(halfU, Math.min(1, Math.max(0, u))));
const cy = Math.min(1 - halfV, Math.max(halfV, Math.min(1, Math.max(0, v))));
return { x: crop.x + cx * crop.w, y: crop.y + cy * crop.h };
}
interface Props {
crop: CropState;
frame: { w: number; h: number };
ratio: number | null;
bitmap: ImageBitmap | null;
edits: Edits;
onChange: (rect: Partial<CropState>) => void;
/** lets the preview hold the grain still while a handle is moving */
onDragChange?: (busy: boolean) => void;
}
const MIN = 0.04;
function clampRect(r: CropState): CropState {
let w = clamp(r.w, MIN, 1);
let h = clamp(r.h, MIN, 1);
const x = clamp(r.x, 0, 1 - w);
const y = clamp(r.y, 0, 1 - h);
return { ...r, x, y, w, h };
}
function applyDrag(
start: CropState,
mode: Mode,
dx: number,
dy: number,
ratio: number | null,
frame: { w: number; h: number },
): Partial<CropState> {
let { x, y, w, h } = start;
if (mode === 'move') {
x = clamp(x + dx, 0, 1 - w);
y = clamp(y + dy, 0, 1 - h);
return { x, y };
}
if (mode.includes('e')) w = clamp(w + dx, MIN, 1 - x);
if (mode.includes('s')) h = clamp(h + dy, MIN, 1 - y);
if (mode.includes('w')) {
const nx = clamp(x + dx, 0, x + w - MIN);
w += x - nx;
x = nx;
}
if (mode.includes('n')) {
const ny = clamp(y + dy, 0, y + h - MIN);
h += y - ny;
y = ny;
}
if (ratio) {
const frameRatio = frame.w / frame.h;
const dragsWidth = mode.includes('e') || mode.includes('w');
if (dragsWidth) {
const targetH = (w * frameRatio) / ratio;
if (mode.includes('n')) y = y + h - targetH;
h = targetH;
} else if (mode.includes('n') || mode.includes('s')) {
const targetW = (h * ratio) / frameRatio;
x += (w - targetW) / 2;
w = targetW;
}
if (w > 1) {
const k = 1 / w;
w *= k;
h *= k;
}
if (h > 1) {
const k = 1 / h;
w *= k;
h *= k;
}
if (mode.includes('w')) x = start.x + start.w - w;
if (mode.includes('n')) y = start.y + start.h - h;
x = clamp(x, 0, 1 - w);
y = clamp(y, 0, 1 - h);
}
return clampRect({ ...start, x, y, w, h });
}
export default function CropOverlay({ crop, frame, ratio, bitmap, edits, onChange, onDragChange }: Props) {
const ref = useRef<HTMLDivElement>(null);
const start = useRef<{ mode: Mode; x: number; y: number; rect: CropState } | null>(null);
const [dragging, setDragging] = useState(false);
const loupe = useRef<HTMLCanvasElement>(null);
const loupeRenderer = useRef<Renderer | null>(null);
/** where the patch is sampling, in frame uv; null = centre of the rectangle */
const [loupePoint, setLoupePoint] = useState<{ x: number; y: number } | null>(null);
/** pointer offset from the patch centre while it is being dragged */
const grab = useRef<{ x: number; y: number } | null>(null);
useEffect(
() => () => {
loupeRenderer.current?.dispose();
loupeRenderer.current = null;
},
[],
);
// A live 1:1 grain patch inside the crop rectangle: it samples whatever area the
// rectangle frames, so the rectangle can be judged as it is dragged.
useEffect(() => {
const canvas = loupe.current;
if (!canvas || !bitmap) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cssW = 120;
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const cssH = Math.round(Math.min(96, Math.max(48, 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 (!loupeRenderer.current) loupeRenderer.current = new Renderer(canvas);
const r = loupeRenderer.current;
r.setImage(bitmap);
const view = grainSampleWindow(frame, crop, W, H, loupePoint);
r.render({ ...edits, crop }, { width: W, height: H, view });
} catch {
// The overlay still works if the engine cannot start a second context.
}
}, [bitmap, crop, edits, frame, loupePoint]);
const dpr = Math.min(typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1, 2);
const loupeCssW = 120;
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const loupeCssH = Math.round(Math.min(96, Math.max(48, loupeCssW * (cropPxH / cropPxW))));
const loupeW = Math.max(1, Math.round(loupeCssW * dpr));
const loupeH = Math.max(1, Math.round(loupeCssH * dpr));
const view = grainSampleWindow(frame, crop, loupeW, loupeH, loupePoint);
const fits = crop.w > 0.16 && crop.h > 0.16;
const loupeAt = {
left: `${((view.x + view.w / 2 - crop.x) / crop.w) * 100}%`,
top: `${((view.y + view.h / 2 - crop.y) / crop.h) * 100}%`,
width: `${loupeCssW}px`,
height: `${loupeCssH}px`,
transform: 'translate(-50%, -50%)',
display: fits && bitmap ? 'block' : 'none',
};
const startLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
e.preventDefault();
e.stopPropagation();
e.currentTarget.setPointerCapture(e.pointerId);
const box = e.currentTarget.parentElement?.getBoundingClientRect();
if (!box || !box.width || !box.height) return;
const cx = box.left + ((view.x + view.w / 2 - crop.x) / crop.w) * box.width;
const cy = box.top + ((view.y + view.h / 2 - crop.y) / crop.h) * box.height;
grab.current = { x: e.clientX - cx, y: e.clientY - cy };
};
const moveLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
const g = grab.current;
if (!g) return;
const box = e.currentTarget.parentElement?.getBoundingClientRect();
if (!box || !box.width || !box.height) return;
const halfU = Math.min(0.5, loupeCssW / 2 / box.width);
const halfV = Math.min(0.5, loupeCssH / 2 / box.height);
setLoupePoint(
clampLoupe(
crop,
(e.clientX - g.x - box.left) / box.width,
(e.clientY - g.y - box.top) / box.height,
halfU,
halfV,
),
);
};
const endLoupe = () => {
grab.current = null;
};
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
const el = e.target as HTMLElement;
const mode = (el.dataset.mode ?? 'move') as Mode;
e.preventDefault();
e.stopPropagation();
ref.current?.setPointerCapture(e.pointerId);
start.current = { mode, x: e.clientX, y: e.clientY, rect: { ...crop } };
setDragging(true);
onDragChange?.(true);
};
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const s = start.current;
const el = ref.current;
if (!s || !el) return;
const rect = el.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dx = (e.clientX - s.x) / rect.width;
const dy = (e.clientY - s.y) / rect.height;
onChange(applyDrag(s.rect, s.mode, dx, dy, ratio, frame));
};
const end = (e: React.PointerEvent<HTMLDivElement>) => {
if (ref.current?.hasPointerCapture(e.pointerId)) ref.current.releasePointerCapture(e.pointerId);
start.current = null;
setDragging(false);
onDragChange?.(false);
};
const style = {
left: `${crop.x * 100}%`,
top: `${crop.y * 100}%`,
width: `${crop.w * 100}%`,
height: `${crop.h * 100}%`,
};
return (
<div
ref={ref}
className={`crop-overlay ${dragging ? 'dragging' : ''}`}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={end}
onPointerCancel={end}
>
<div className="crop-rect" style={style}>
<div className="crop-grid" data-mode="move" />
{(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as Mode[]).map((m) => (
<span key={m} className={`handle ${m}`} data-mode={m} />
))}
<canvas
ref={loupe}
className="crop-loupe"
style={loupeAt}
title="Grain at 100% · drag to sample any point in the crop"
onPointerDown={startLoupe}
onPointerMove={moveLoupe}
onPointerUp={endLoupe}
onPointerCancel={endLoupe}
/>
<span className="crop-size">
{Math.round(crop.w * 100)}% × {Math.round(crop.h * 100)}%
</span>
</div>
</div>
);
}
+122
View File
@@ -0,0 +1,122 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { buildSampler, clamp01 } from '../lib/curves';
import type { CurvePoint } from '../types';
interface Props {
points: CurvePoint[];
onChange: (points: CurvePoint[]) => void;
color: string;
}
export default function CurveEditor({ points, onChange, color }: Props) {
const svgRef = useRef<SVGSVGElement>(null);
const pointsRef = useRef(points);
const [drag, setDrag] = useState<number | null>(null);
const [hover, setHover] = useState<number | null>(null);
useEffect(() => {
pointsRef.current = points;
}, [points]);
const sampler = useMemo(() => buildSampler(points), [points]);
const path = useMemo(() => {
const segs: string[] = [];
for (let i = 0; i <= 80; i++) {
const x = i / 80;
const y = sampler(x);
segs.push(`${i === 0 ? 'M' : 'L'}${(x * 100).toFixed(2)},${((1 - y) * 100).toFixed(2)}`);
}
return segs.join(' ');
}, [sampler]);
const toNorm = useCallback((clientX: number, clientY: number) => {
const svg = svgRef.current;
if (!svg) return { x: 0, y: 0 };
const rect = svg.getBoundingClientRect();
return {
x: clamp01((clientX - rect.left) / rect.width),
y: clamp01(1 - (clientY - rect.top) / rect.height),
};
}, []);
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
e.preventDefault();
const idxAttr = (e.target as Element).getAttribute('data-idx');
let idx: number;
if (idxAttr !== null) {
idx = Number(idxAttr);
} else {
const p = toNorm(e.clientX, e.clientY);
const next = [...points, { x: p.x, y: p.y }].sort((a, b) => a.x - b.x);
idx = next.findIndex((pt) => pt.x === p.x && pt.y === p.y);
onChange(next);
}
setDrag(idx);
e.currentTarget.setPointerCapture(e.pointerId);
};
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
if (drag === null) return;
const pts = pointsRef.current;
const idx = drag;
if (!pts[idx]) return;
const p = toNorm(e.clientX, e.clientY);
const lo = idx > 0 ? pts[idx - 1].x + 0.01 : 0;
const hi = idx < pts.length - 1 ? pts[idx + 1].x - 0.01 : 1;
const next = pts.map((pt, i) => (i === idx ? { x: Math.min(hi, Math.max(lo, p.x)), y: p.y } : pt));
onChange(next);
};
const handleUp = () => setDrag(null);
const removePoint = (idx: number) => {
const pts = pointsRef.current;
if (pts.length <= 2) return;
onChange(pts.filter((_, i) => i !== idx));
setDrag(null);
};
return (
<div className="curve-wrap">
<svg
ref={svgRef}
className="curve"
viewBox="0 0 100 100"
preserveAspectRatio="none"
onPointerDown={handleDown}
onPointerMove={handleMove}
onPointerUp={handleUp}
onPointerCancel={handleUp}
onDoubleClick={(e) => {
const idxAttr = (e.target as Element).getAttribute('data-idx');
if (idxAttr !== null) removePoint(Number(idxAttr));
}}
>
<rect x="0" y="0" width="100" height="100" className="curve-bg" />
{[25, 50, 75].map((v) => (
<g key={v}>
<line x1={v} y1="0" x2={v} y2="100" className="curve-grid" />
<line x1="0" y1={v} x2="100" y2={v} className="curve-grid" />
</g>
))}
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
{points.map((p, i) => (
<circle
key={`${i}-${p.x.toFixed(3)}`}
data-idx={i}
cx={p.x * 100}
cy={(1 - p.y) * 100}
r={hover === i || drag === i ? 3 : 2.1}
className="curve-point"
fill={color}
onPointerEnter={() => setHover(i)}
onPointerLeave={() => setHover((h) => (h === i ? null : h))}
/>
))}
</svg>
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
</div>
);
}
+736
View File
@@ -0,0 +1,736 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits';
import { getBitmap } from '../lib/images';
import { rotatedBounds, Renderer } from '../gl/renderer';
import type { Edits, EventRecord, PhotoRecord, Preset } from '../types';
import ContextMenu, { type MenuEntry } from './ContextMenu';
import CropOverlay from './CropOverlay';
import Histogram from './Histogram';
import {
BasicPanel,
ColorGradingPanel,
CropPanel,
CurvePanel,
DetailPanel,
EffectsPanel,
HistoryPanel,
HslPanel,
MetadataPanel,
NavigatorPanel,
PresetsPanel,
} from './Panels';
import Stars, { ColorSwatches, FlagButtons } from './Stars';
/** Zoom is expressed as a percentage of actual pixels, like Lightroom's readout. */
const MAX_ZOOM = 400;
const clampNum = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
interface Rect {
x: number;
y: number;
w: number;
h: number;
}
interface Geometry {
fitScale: number;
fitPct: number;
frameW: number;
frameH: number;
zoomFactor: number;
availW: number;
availH: number;
content: Rect;
view: Rect;
}
const EMPTY_GEO: Geometry = {
fitScale: 0,
fitPct: 100,
frameW: 1,
frameH: 1,
zoomFactor: 1,
availW: 0,
availH: 0,
content: { x: 0, y: 0, w: 1, h: 1 },
view: { x: 0, y: 0, w: 1, h: 1 },
};
interface Props {
photo: PhotoRecord;
photos: PhotoRecord[];
events: EventRecord[];
onSelect: (id: string) => void;
onExit: () => void;
onUpdate: (id: string, patch: Partial<PhotoRecord>, historyLabel?: string) => void;
onNavigate: (dir: -1 | 1) => void;
clipboard: Edits | null;
onCopy: () => void;
onPaste: () => void;
onExport: () => void;
presets: Preset[];
onSavePreset: (name: string, edits: Edits) => void;
onDelete: () => void;
}
export default function Develop({
photo,
photos,
events,
onSelect,
onExit,
onUpdate,
onNavigate,
clipboard,
onCopy,
onPaste,
onExport,
presets,
onSavePreset,
onDelete,
}: Props) {
const canvasRef = useRef<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 [stage, setStage] = useState({ w: 0, h: 0 });
const [cropMode, setCropMode] = useState(false);
const [cropDrag, setCropDrag] = useState(false);
const [showOriginal, setShowOriginal] = useState(false);
const [histVersion, setHistVersion] = useState(0);
const [error, setError] = useState<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 [readout, setReadout] = useState({ shown: 100, fit: 100 });
const [menu, setMenu] = useState<{ x: number; y: number; kind: 'canvas' | 'film' } | null>(null);
const edits = photo.edits;
const zoomed = zoom.pct !== 'fit';
const setEdits = useCallback(
(patch: Partial<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;
};
}, []);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
setStage({ w: el.clientWidth, h: el.clientHeight });
const ro = new ResizeObserver((entries) => {
const rect = entries[0].contentRect;
setStage({ w: Math.round(rect.width), h: Math.round(rect.height) });
});
ro.observe(el);
return () => ro.disconnect();
}, [cropMode]);
useEffect(() => {
let alive = true;
setLoading(true);
getBitmap(photo)
.then((bmp) => {
if (!alive) return;
setBitmap(bmp);
setLoading(false);
})
.catch((err) => {
if (!alive) return;
setError(err instanceof Error ? err.message : 'Could not load the original image');
setLoading(false);
});
return () => {
alive = false;
};
}, [photo.id, photo.raw, photo.previewUrl]);
// A new photo, a crop change or entering crop mode all invalidate the current view.
useEffect(() => {
setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 });
}, [photo.id, cropMode, edits.crop]);
// Leaving crop mode mid-drag must not leave the grain frozen.
useEffect(() => {
if (!cropMode) setCropDrag(false);
}, [cropMode]);
const drawPreview = useCallback(() => {
const renderer = rendererRef.current;
const canvas = canvasRef.current;
if (!renderer || !canvas || !bitmap) return;
if (stage.w < 40 || stage.h < 40) return;
const activeEdits = showOriginal ? { ...defaultEdits(), crop: edits.crop } : edits;
const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter);
const content: Rect = cropMode
? { x: 0, y: 0, w: 1, h: 1 }
: { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h };
const contentW = Math.max(1, frame.w * content.w);
const contentH = Math.max(1, frame.h * content.h);
const availW = Math.max(60, stage.w - 48);
const availH = Math.max(60, stage.h - 48);
const fitScale = Math.min(availW / contentW, availH / contentH);
const fitPct = Math.min(100, fitScale * 100);
const zoomFactor = zoom.pct === 'fit' ? 1 : Math.max(1, zoom.pct / 100 / fitScale);
let view: Rect = content;
let cssW = Math.max(40, Math.round(contentW * fitScale));
let cssH = Math.max(40, Math.round(contentH * fitScale));
if (zoomFactor > 1.0001) {
// The visible window keeps the stage's aspect, so the canvas is stage sized
// and the shader maps it onto a sub-rect of the frame. Cost stays constant
// no matter how far you zoom, and detail comes from the source bitmap.
const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w);
const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h);
const cx =
vw >= content.w
? content.x + content.w / 2
: clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
const cy =
vh >= content.h
? content.y + content.h / 2
: clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh };
cssW = Math.round(availW);
cssH = Math.round(availH);
}
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cap = Math.min(1, 3200 / Math.max(1, Math.max(cssW * dpr, cssH * dpr)));
const pxW = Math.max(1, Math.round(cssW * dpr * cap));
const pxH = Math.max(1, Math.round(cssH * dpr * cap));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
geoRef.current = {
fitScale,
fitPct,
frameW: frame.w,
frameH: frame.h,
zoomFactor,
availW,
availH,
content,
view,
};
const shown = Math.round(fitScale * zoomFactor * 100);
const fit = Math.round(fitPct);
setReadout((prev) => (prev.shown === shown && prev.fit === fit ? prev : { shown, fit }));
try {
renderer.setImage(bitmap);
renderer.render(activeEdits, {
width: pxW,
height: pxH,
cropPreview: cropMode,
// The histogram describes the whole photo, so it is only refreshed at fit.
histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001,
view: zoomFactor <= 1.0001 ? undefined : view,
// Holding the grain still keeps the noise from crawling while a crop
// handle moves; the new crop-relative scale applies on release.
freezeGrain: cropDrag,
// One source pixel per device pixel is the crossover: below it mipmaps
// resample cleanly, above it bicubic keeps magnified detail from squaring off.
upscale: dpr * cap * fitScale * zoomFactor > 1.1,
});
histRef.current = renderer.histogram;
setHistVersion((v) => v + 1);
} catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed');
}
}, [bitmap, edits, cropMode, showOriginal, stage, zoom, cropDrag]);
useEffect(() => {
if (!bitmap) return;
const raf = requestAnimationFrame(drawPreview);
return () => cancelAnimationFrame(raf);
}, [bitmap, drawPreview]);
/* ------------------------------------------------------------ zoom & pan */
const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => {
const geo = geoRef.current;
if (!geo.fitScale) return;
const fitPct = geo.fitPct;
if (rawPct === 'fit' || rawPct <= fitPct * 1.015 || fitPct >= 99.5) {
setZoom({ pct: 'fit', cx: 0.5, cy: 0.5 });
return;
}
const next = clampNum(rawPct, fitPct * 1.02, MAX_ZOOM);
const zNow = Math.max(1, geo.zoomFactor);
const zNext = Math.max(1, next / fitPct);
const centerX = geo.view.x + geo.view.w / 2;
const centerY = geo.view.y + geo.view.h / 2;
let cx = centerX;
let cy = centerY;
if (point) {
// Keep the frame point under the cursor fixed while the scale changes.
const rect = canvasRef.current?.getBoundingClientRect();
if (rect) {
const dx = point.x - (rect.left + rect.width / 2);
const dy = point.y - (rect.top + rect.height / 2);
const pointX = centerX + dx / (geo.fitScale * zNow) / geo.frameW;
const pointY = centerY + dy / (geo.fitScale * zNow) / geo.frameH;
cx = pointX - dx / (geo.fitScale * zNext) / geo.frameW;
cy = pointY - dy / (geo.fitScale * zNext) / geo.frameH;
}
}
const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW;
const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH;
const c = geo.content;
cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
setZoom({ pct: next, cx, cy });
}, []);
// Filmstrip: the wheel browses photos sideways, and the current one is kept
// in view as you move through the shoot.
useEffect(() => {
const el = stripRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
e.preventDefault();
el.scrollLeft += e.deltaY;
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
useEffect(() => {
stripRef.current?.querySelector('.film.active')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}, [photo.id]);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (cropMode) return;
const geo = geoRef.current;
if (!geo.fitScale) return;
if (!e.ctrlKey && Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
e.preventDefault();
const base = geo.fitPct * Math.max(1, geo.zoomFactor);
applyZoom(base * Math.exp(-e.deltaY * 0.0022), { x: e.clientX, y: e.clientY });
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [cropMode, applyZoom]);
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (cropMode || !zoomed || e.button !== 0) return;
const geo = geoRef.current;
panRef.current = {
x: e.clientX,
y: e.clientY,
cx: geo.view.x + geo.view.w / 2,
cy: geo.view.y + geo.view.h / 2,
};
e.currentTarget.setPointerCapture(e.pointerId);
setPanning(true);
};
const movePan = (e: React.PointerEvent<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);
};
const toggleZoom = (x?: number, y?: number) => {
if (cropMode) return;
if (zoomed) applyZoom('fit');
else applyZoom(100, x !== undefined && y !== undefined ? { x, y } : undefined);
};
const undo = useCallback(() => {
const hist = photo.history;
if (hist.length < 2) return;
const idx = hist.findIndex((h) => h.edits === photo.edits);
const target = idx > 0 ? hist[idx - 1] : hist[hist.length - 2];
if (target) onUpdate(photo.id, { edits: target.edits });
}, [photo.history, photo.edits, photo.id, onUpdate]);
useEffect(() => {
const down = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null;
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return;
if (e.key === '\\') {
setShowOriginal(true);
return;
}
if (e.key === 'ArrowRight') {
onNavigate(1);
e.preventDefault();
} else if (e.key === 'ArrowLeft') {
onNavigate(-1);
e.preventDefault();
} else if (e.key.toLowerCase() === 'c' && !e.metaKey && !e.ctrlKey) {
setCropMode((v) => !v);
} else if (e.key.toLowerCase() === 'z' && !e.metaKey && !e.ctrlKey) {
toggleZoom();
e.preventDefault();
} else if (e.key === 'Enter' && cropMode) {
setCropMode(false);
} else if (e.key === 'Escape') {
if (cropMode) setCropMode(false);
else onExit();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
undo();
e.preventDefault();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c') {
onCopy();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') {
onPaste();
}
};
const up = (e: KeyboardEvent) => {
if (e.key === '\\') setShowOriginal(false);
};
window.addEventListener('keydown', down);
window.addEventListener('keyup', up);
return () => {
window.removeEventListener('keydown', down);
window.removeEventListener('keyup', up);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cropMode, onExit, onNavigate, onCopy, onPaste, undo, applyZoom, zoomed]);
const applyPreset = useCallback(
(preset: Preset) => {
const next: Edits =
preset.id === 'original'
? { ...defaultEdits(), crop: photo.edits.crop }
: { ...photo.edits, ...preset.edits, crop: photo.edits.crop };
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
},
[onUpdate, photo.id, photo.edits],
);
const frame = bitmap
? rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter)
: { w: 1, h: 1 };
const lockedRatio = useMemo(() => {
const def = ASPECTS.find((a) => a.id === edits.crop.aspect);
return def?.ratio ?? null;
}, [edits.crop.aspect]);
const applyAspect = useCallback(
(id: string) => {
const def = ASPECTS.find((a) => a.id === id);
if (!def) return;
const f = bitmap
? rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter)
: { w: 1, h: 1 };
let w = 1;
let h = 1;
if (def.ratio) {
const frameRatio = f.w / f.h;
if (def.ratio > frameRatio) {
w = 1;
h = frameRatio / def.ratio;
} else {
h = 1;
w = def.ratio / frameRatio;
}
}
setEdits(
{ crop: { ...photo.edits.crop, x: (1 - w) / 2, y: (1 - h) / 2, w, h, aspect: id } },
def.ratio ? `Crop ${def.label}` : 'Crop',
);
},
[bitmap, photo.edits.crop, setEdits],
);
const rotate = useCallback(
(dir: -1 | 1) => {
const c = photo.edits.crop;
const quarter = ((c.quarter + dir) % 4 + 4) % 4;
const rect =
dir === 1
? { x: 1 - (c.y + c.h), y: c.x, w: c.h, h: c.w }
: { x: c.y, y: 1 - (c.x + c.w), w: c.h, h: c.w };
setEdits(
{ crop: { ...c, quarter, ...rect } },
dir === 1 ? 'Rotate 90° right' : 'Rotate 90° left',
);
},
[photo.edits.crop, setEdits],
);
const resetAll = () => {
if (!window.confirm('Reset all develop settings for this photo?')) return;
onUpdate(photo.id, { edits: { ...defaultEdits(), crop: photo.edits.crop } }, 'Reset');
};
const canvasMenu: MenuEntry[] = [
{ label: 'Zoom to Fit', shortcut: 'Z', onSelect: () => applyZoom('fit') },
{ label: 'Zoom to 100%', onSelect: () => applyZoom(100) },
'separator',
{ label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) },
{ label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) },
'separator',
{ label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy },
{ label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard },
{ label: 'Reset settings', onSelect: resetAll },
'separator',
{ label: 'Export…', onSelect: onExport },
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
];
const filmMenu: MenuEntry[] = [
{ label: 'Copy settings', onSelect: onCopy },
{ label: 'Paste settings', onSelect: onPaste, disabled: !clipboard },
{ label: 'Reset settings', onSelect: resetAll },
'separator',
{ label: 'Export…', onSelect: onExport },
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
];
const index = photos.findIndex((p) => p.id === photo.id);
return (
<div className={`develop ${cropMode ? 'cropping' : ''}`}>
<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" onClick={onCopy} title="Copy develop settings (⌘C)">
Copy
</button>
<button className="btn ghost small" onClick={onPaste} disabled={!clipboard} title="Paste develop settings (⌘V)">
Paste
</button>
<button className="btn ghost small" onClick={resetAll}>
Reset
</button>
<button className="btn ghost small danger" onClick={onDelete}>
Delete
</button>
<button className="btn primary small" onClick={onExport}>
Export
</button>
</div>
<div className="dev-body">
<aside className="dev-left">
<NavigatorPanel photo={photo} />
<PresetsPanel
presets={presets}
photo={photo}
onApply={applyPreset}
onSave={(name) => onSavePreset(name, photo.edits)}
/>
<HistoryPanel history={photo.history} onRestore={(next) => onUpdate(photo.id, { edits: next })} />
</aside>
<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' : ''}`}
onPointerDown={beginPan}
onPointerMove={movePan}
onPointerUp={endPan}
onPointerCancel={endPan}
onDoubleClick={(e) => toggleZoom(e.clientX, e.clientY)}
/>
{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>
)}
{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>
</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>}
</div>
<aside className="dev-right">
<div className="histo-wrap">
<Histogram data={histRef.current} version={histVersion} />
<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">
{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} />
<CurvePanel edits={edits} photo={photo} set={setEdits} />
<HslPanel edits={edits} photo={photo} set={setEdits} />
<ColorGradingPanel edits={edits} photo={photo} set={setEdits} />
<EffectsPanel edits={edits} photo={photo} set={setEdits} grainFreeze={cropDrag} />
<DetailPanel edits={edits} photo={photo} set={setEdits} />
<MetadataPanel photo={photo} events={events} />
</div>
</aside>
</div>
<div className="filmstrip" ref={stripRef}>
{photos.map((p) => (
<button
key={p.id}
className={`film ${p.id === photo.id ? 'active' : ''}`}
onClick={() => onSelect(p.id)}
onContextMenu={(e) => {
e.preventDefault();
if (p.id !== photo.id) onSelect(p.id);
setMenu({ x: e.clientX, y: e.clientY, kind: 'film' });
}}
title={p.name}
>
<img
src={p.thumbUrl ?? p.thumb}
alt={p.name}
loading="lazy"
draggable={false}
style={{ transform: thumbTransform(p, 3 / 2) }}
/>
{p.rating > 0 && <span className="film-rating">{'★'.repeat(p.rating)}</span>}
</button>
))}
</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>
);
}
+202
View File
@@ -0,0 +1,202 @@
import { useState } from 'react';
import {
draggedEventId,
draggedPhotoIds,
endDrag,
EVENT_DRAG,
PHOTO_DRAG,
startEventDrag,
startPhotoDrag,
} from '../lib/drag';
import type { EventRecord, PhotoRecord } from '../types';
interface Props {
events: EventRecord[];
photos: PhotoRecord[];
eventId: string;
onSelectEvent: (id: string) => void;
onCreate: (name: string) => Promise<void> | void;
onRename: (id: string, name: string) => void;
onDelete: (id: string) => void;
onReorderEvents: (dragId: string, targetId: string) => void;
onDropPhotos: (ids: string[], eventId: string) => void;
storageNote: string;
}
export default function EventSidebar({
events,
photos,
eventId,
onSelectEvent,
onCreate,
onRename,
onDelete,
onReorderEvents,
onDropPhotos,
storageNote,
}: Props) {
const [adding, setAdding] = useState(false);
const [name, setName] = useState('');
const [dropTarget, setDropTarget] = useState<string | null>(null);
const counts = new Map<string, number>();
let unsorted = 0;
for (const p of photos) {
if (!p.eventId) {
unsorted++;
continue;
}
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1);
}
const submit = async () => {
if (!name.trim()) {
setAdding(false);
return;
}
await onCreate(name);
setName('');
setAdding(false);
};
const dropProps = (targetId: string) => ({
onDragOver: (e: React.DragEvent) => {
if (draggedPhotoIds().length) {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
setDropTarget(targetId);
}
},
onDragLeave: () => setDropTarget((cur) => (cur === targetId ? null : cur)),
onDrop: (e: React.DragEvent) => {
const ids = draggedPhotoIds();
setDropTarget(null);
if (!ids.length) return;
e.preventDefault();
e.stopPropagation();
onDropPhotos(ids, targetId);
endDrag();
},
});
return (
<aside className="sidebar">
<div className="sidebar-head">
<span>Catalog</span>
<button className="icon-btn" title="New event" onClick={() => setAdding((v) => !v)}>
+
</button>
</div>
<div className="catalog-links">
<button className={`event-item all ${eventId === 'all' ? 'active' : ''}`} onClick={() => onSelectEvent('all')}>
<span className="event-name">All photos</span>
<span className="event-count">{photos.length}</span>
</button>
{unsorted > 0 && (
<button
className={`event-item all ${eventId === 'unsorted' ? 'active' : ''}`}
onClick={() => onSelectEvent('unsorted')}
>
<span className="event-name">Unsorted</span>
<span className="event-count">{unsorted}</span>
</button>
)}
</div>
<div className="sidebar-head sub">
<span>Events</span>
<span className="muted small">{events.length}</span>
</div>
{adding && (
<div className="new-event">
<input
autoFocus
value={name}
placeholder="Event name"
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void submit();
if (e.key === 'Escape') {
setAdding(false);
setName('');
}
}}
/>
<button className="btn primary small" onClick={() => void submit()}>
Add
</button>
</div>
)}
<div className="event-list">
{events.map((event) => (
<div
key={event.id}
className={`event-item ${eventId === event.id ? 'active' : ''} ${dropTarget === event.id ? 'drop' : ''}`}
draggable
onDragStart={(e) => {
startEventDrag(event.id);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(EVENT_DRAG, event.id);
}}
onDragEnd={() => endDrag()}
onDragOver={(e) => {
const eventDrag = draggedEventId();
if (eventDrag && eventDrag !== event.id) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
setDropTarget(event.id);
return;
}
dropProps(event.id).onDragOver(e);
}}
onDragLeave={() => setDropTarget((cur) => (cur === event.id ? null : cur))}
onDrop={(e) => {
const eventDrag = draggedEventId();
if (eventDrag && eventDrag !== event.id) {
e.preventDefault();
setDropTarget(null);
onReorderEvents(eventDrag, event.id);
endDrag();
return;
}
dropProps(event.id).onDrop(e);
}}
>
<button className="event-main" onClick={() => onSelectEvent(event.id)}>
<span className="event-name" title={event.name}>
{event.name}
</span>
<span className="event-count">{counts.get(event.id) ?? 0}</span>
</button>
<div className="event-tools">
<button
className="icon-btn"
title="Rename event"
onClick={() => {
const next = window.prompt('Rename event', event.name);
if (next) onRename(event.id, next);
}}
>
✎
</button>
<button className="icon-btn danger" title="Remove event" onClick={() => onDelete(event.id)}>
🗑
</button>
</div>
</div>
))}
{!events.length && (
<p className="muted small sidebar-hint">Create an event, then drag photos onto it.</p>
)}
</div>
<div className="sidebar-foot" {...dropProps('')}>
{dropTarget === '' ? <strong>Drop to move to Unsorted</strong> : storageNote}
</div>
</aside>
);
}
+385
View File
@@ -0,0 +1,385 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ExportOptions, ExportFormat, ResizeMode } from '../lib/export';
import { buildFileName, DEFAULT_EXPORT, exportPhotos } from '../lib/export';
import { getBitmap } from '../lib/images';
import { frameToSource, grainCellPx, grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import type { PhotoRecord } from '../types';
interface Props {
photos: PhotoRecord[];
initial: ExportOptions;
onClose: () => void;
onDone: (message: string, options: ExportOptions) => void;
}
const FORMATS: { value: ExportFormat; label: string }[] = [
{ value: 'jpeg', label: 'JPEG' },
{ value: 'png', label: 'PNG' },
{ value: 'webp', label: 'WebP' },
];
/**
* Three 1:1 patches of the export at half, current and double the chosen size.
* Each patch is rendered on the export's own pixel grid, so it shows exactly the
* grain and detail that file will carry at 100%.
*/
function ExportDetailStrip({ photo, size }: { photo: PhotoRecord; size: { w: number; h: number } | null }) {
const tiles = useRef<(HTMLCanvasElement | null)[]>([]);
const pick = useRef<HTMLCanvasElement | null>(null);
const work = useRef<HTMLCanvasElement | null>(null);
const renderer = useRef<Renderer | null>(null);
const bitmap = useRef<ImageBitmap | null>(null);
const [ready, setReady] = useState(false);
const [point, setPoint] = useState<{ x: number; y: number } | null>(null);
const { crop } = photo.edits;
const srcW = Math.max(1, photo.width);
const srcH = Math.max(1, photo.height);
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;
},
[],
);
const steps = useMemo(() => {
if (!size) return [];
const long = Math.max(size.w, size.h);
return [Math.max(200, Math.round(long / 2)), long, Math.min(20000, long * 2)];
}, [size]);
useEffect(() => {
const bmp = bitmap.current;
if (!ready || !bmp || !size || !steps.length) return;
if (!work.current) work.current = document.createElement('canvas');
const workCanvas = work.current;
try {
if (!renderer.current) renderer.current = new Renderer(workCanvas);
const r = renderer.current;
r.setImage(bmp);
const frame = rotatedBounds(bmp.width, bmp.height, crop.angle, crop.quarter);
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const PW = 132;
const PH = Math.round(Math.min(92, Math.max(56, PW * (cropPxH / cropPxW))));
const outLong = Math.max(1, Math.max(size.w, size.h));
steps.forEach((longEdge, i) => {
const tile = tiles.current[i];
if (!tile) return;
if (tile.width !== PW) tile.width = PW;
if (tile.height !== PH) tile.height = PH;
const scale = longEdge / outLong;
const pxPerSource = (size.w * scale) / cropPxW;
const view = grainSampleWindow(
frame,
crop,
Math.max(1, Math.round(PW / pxPerSource)),
Math.max(1, Math.round(PH / pxPerSource)),
point,
);
r.render(photo.edits, { width: PW, height: PH, view, upscale: pxPerSource > 1.05 });
const ctx = tile.getContext('2d');
if (ctx) ctx.drawImage(workCanvas, 0, 0);
});
// The picker shows the whole exported crop, oriented like the main view.
const pickCanvas = pick.current;
if (pickCanvas) {
const pickW = 132;
const pickH = Math.round(Math.min(112, Math.max(56, pickW * (cropPxH / cropPxW))));
r.render(photo.edits, { width: pickW, height: pickH, upscale: pickW / cropPxW > 1.05 });
const ctx = pickCanvas.getContext('2d');
if (ctx) {
if (pickCanvas.width !== pickW) pickCanvas.width = pickW;
if (pickCanvas.height !== pickH) pickCanvas.height = pickH;
ctx.imageSmoothingQuality = 'high';
ctx.clearRect(0, 0, pickW, pickH);
ctx.drawImage(workCanvas, 0, 0, pickW, pickH);
}
}
} catch {
// Keep the previous patches if the engine is unavailable.
}
}, [ready, photo, crop, size, steps, point]);
// Where the patch is, in photo terms, and how big a grain cell is in the file.
const info = useMemo(() => {
// The point lives in frame coordinates; the picker shows only the crop.
const p = point ?? { x: crop.x + crop.w / 2, y: crop.y + crop.h / 2 };
const at = frameToSource(p, srcW, srcH, crop.angle, crop.quarter, crop.flipH, crop.flipV);
return {
sx: at.x,
sy: at.y,
px: Math.round(at.x * 100),
py: Math.round(at.y * 100),
ux: (p.x - crop.x) / crop.w,
uy: (p.y - crop.y) / crop.h,
cell: size ? grainCellPx(photo.edits, srcW, srcH, size.w) : 0,
};
}, [point, crop, srcW, srcH, size, photo.edits]);
if (!size || !steps.length) return null;
return (
<>
<div className="export-detail-pick">
<div
className="pick-frame"
title="Choose the sample point for the 100% patches"
onPointerDown={(e) => {
const r = pick.current?.getBoundingClientRect();
if (!r || !r.width || !r.height) return;
const u = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
const v = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height));
setPoint({ x: crop.x + u * crop.w, y: crop.y + v * crop.h });
}}
>
<canvas ref={pick} />
<span
className="pick-dot"
style={{ left: `${info.ux * 100}%`, top: `${info.uy * 100}%` }}
/>
</div>
<span className="hint">Click the photo to move the 100% patches</span>
</div>
<div className="export-detail">
{steps.map((longEdge, i) => (
<figure key={longEdge}>
<canvas ref={(el) => { tiles.current[i] = el; }} />
<figcaption>
{longEdge === steps[1] ? 'This export' : longEdge < steps[1] ? 'Half size' : 'Double size'} · {longEdge} px · 100%
</figcaption>
</figure>
))}
</div>
<p className="muted small export-detail-info">
Sample {info.px}% × {info.py}% of the photo ·{' '}
{photo.edits.grain.amount > 1
? `grain ${info.cell < 1 ? info.cell.toFixed(2) : info.cell.toFixed(1)} px cells${
info.cell < 0.9 ? ' (fades: finer than a pixel)' : ''
} at this size`
: 'grain off'}
</p>
</>
);
}
export default function ExportModal({ photos, initial, onClose, onDone }: Props) {
const [opts, setOpts] = useState<ExportOptions>({ ...DEFAULT_EXPORT, ...initial });
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState({ done: 0, total: 0 });
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Capture phase so Escape closes the dialog even with the photo open behind it.
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const patch = (p: Partial<ExportOptions>) => setOpts((prev) => ({ ...prev, ...p }));
const sample = photos[0];
const previewSize = useMemo(() => {
if (!sample) return null;
const w = sample.width || 1;
const h = sample.height || 1;
const crop = sample.edits.crop;
const swapped = Math.round(crop.quarter) % 2 === 1;
const frameW = swapped ? h : w;
const frameH = swapped ? w : h;
const baseW = Math.max(1, Math.round(frameW * crop.w));
const baseH = Math.max(1, Math.round(frameH * crop.h));
let k = 1;
if (opts.resize === 'longEdge' && opts.longEdge > 0 && Math.max(baseW, baseH) > opts.longEdge) {
k = opts.longEdge / Math.max(baseW, baseH);
} else if (opts.resize === 'percent') {
k = Math.min(2, Math.max(0.05, opts.percent / 100));
}
return { w: Math.round(baseW * k), h: Math.round(baseH * k) };
}, [sample, opts.resize, opts.longEdge, opts.percent]);
const sampleName = sample
? buildFileName(opts.nameTemplate, sample, 0, opts)
: `export.${opts.format === 'jpeg' ? 'jpg' : opts.format}`;
const run = async () => {
if (!photos.length || busy) return;
setBusy(true);
setError(null);
try {
const { count, failed } = await exportPhotos(photos, opts, (done, total) =>
setProgress({ done, total }),
);
if (!count) {
setError(failed.length ? 'Nothing could be exported. Check the browser console.' : 'Nothing to export');
setBusy(false);
return;
}
onDone(`Exported ${count} photo${count === 1 ? '' : 's'}`, opts);
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Export failed');
setBusy(false);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal export-modal">
<header className="modal-head">
<h2>Export</h2>
<button className="icon-btn" onClick={onClose} disabled={busy}>
✕
</button>
</header>
<div className="modal-body">
<div className="export-summary">
<strong>
{photos.length} photo{photos.length === 1 ? '' : 's'}
</strong>
{previewSize && (
<span className="muted small">
{previewSize.w} × {previewSize.h} px
</span>
)}
</div>
<div className="field-row">
<label className="field">
<span>Format</span>
<select
value={opts.format}
onChange={(e) => patch({ format: e.target.value as ExportFormat })}
disabled={busy}
>
{FORMATS.map((f) => (
<option key={f.value} value={f.value}>
{f.label}
</option>
))}
</select>
</label>
<label className="field">
<span>Resize</span>
<select
value={opts.resize}
onChange={(e) => patch({ resize: e.target.value as ResizeMode })}
disabled={busy}
>
<option value="none">Full resolution</option>
<option value="longEdge">Long edge</option>
<option value="percent">Percent</option>
</select>
</label>
{opts.resize === 'longEdge' && (
<label className="field narrow">
<span>Pixels</span>
<input
type="number"
min={200}
max={20000}
step={100}
value={opts.longEdge}
onChange={(e) => patch({ longEdge: Number(e.target.value) || 0 })}
disabled={busy}
/>
</label>
)}
{opts.resize === 'percent' && (
<label className="field narrow">
<span>Percent</span>
<input
type="number"
min={5}
max={200}
value={opts.percent}
onChange={(e) => patch({ percent: Number(e.target.value) || 100 })}
disabled={busy}
/>
</label>
)}
</div>
{opts.format !== 'png' && (
<label className="field">
<span>Quality · {opts.quality}</span>
<input
type="range"
min={40}
max={100}
value={opts.quality}
onChange={(e) => patch({ quality: Number(e.target.value) })}
disabled={busy}
/>
</label>
)}
{sample && <ExportDetailStrip photo={sample} size={previewSize} />}
<label className="field">
<span>File name</span>
<input
value={opts.nameTemplate}
onChange={(e) => patch({ nameTemplate: e.target.value })}
disabled={busy}
placeholder="{name}"
/>
</label>
<p className="muted small">
Tokens: <code>{'{name}'}</code> <code>{'{date}'}</code> <code>{'{time}'}</code>{' '}
<code>{'{index}'}</code> · first file: <code>{sampleName}</code>
</p>
{busy && progress.total > 0 && (
<div className="progress">
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${(progress.done / progress.total) * 100}%` }}
/>
</div>
<div className="muted small">
{progress.done} / {progress.total}
</div>
</div>
)}
{error && <div className="banner error">{error}</div>}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose} disabled={busy}>
Cancel
</button>
<button className="btn primary" onClick={() => void run()} disabled={busy || !photos.length}>
{busy ? 'Exporting…' : `Export ${photos.length}`}
</button>
</footer>
</div>
</div>
);
}
+140
View File
@@ -0,0 +1,140 @@
import { COLOR_LABELS } from '../lib/edits';
import type { ColorLabel, Filters, Flag, SortKey } from '../types';
interface Props {
filters: Filters;
setFilters: (next: Filters) => void;
count: number;
total: number;
sort: SortKey;
setSort: (s: SortKey) => void;
asc: boolean;
setAsc: (v: boolean) => void;
}
const FLAGS: { value: Flag | 'any'; label: string }[] = [
{ value: 'any', label: 'Any' },
{ value: 'pick', label: 'Picked' },
{ value: 'none', label: 'Unflagged' },
{ value: 'reject', label: 'Rejected' },
];
export default function FilterBar({ filters, setFilters, count, total, sort, setSort, asc, setAsc }: Props) {
const patch = (p: Partial<Filters>) => setFilters({ ...filters, ...p });
const active = filters.minRating > 0 || filters.flag !== 'any' || filters.colors.length > 0 || !!filters.text || filters.editedOnly || filters.unrated;
const toggleColor = (color: ColorLabel) => {
const exists = filters.colors.includes(color);
patch({ colors: exists ? filters.colors.filter((c) => c !== color) : [...filters.colors, color] });
};
return (
<div className="filterbar">
<div className="filter-group">
<span className="filter-label">Rating</span>
<div className="rating-filter">
{[0, 1, 2, 3, 4, 5].map((n) => (
<button
key={n}
className={`chip ${filters.minRating === n ? 'on' : ''}`}
onClick={() => patch({ minRating: n, unrated: false })}
title={n === 0 ? 'Any rating' : `${n} stars and up`}
>
{n === 0 ? 'Any' : `${n}★+`}
</button>
))}
<button
className={`chip ${filters.unrated ? 'on' : ''}`}
onClick={() => patch({ unrated: !filters.unrated, minRating: 0 })}
title="Only photos with no rating"
>
Unrated
</button>
</div>
</div>
<div className="filter-group">
<span className="filter-label">Flag</span>
<div className="rating-filter">
{FLAGS.map((f) => (
<button
key={f.value}
className={`chip ${filters.flag === f.value ? 'on' : ''}`}
onClick={() => patch({ flag: f.value })}
>
{f.label}
</button>
))}
</div>
</div>
<div className="filter-group">
<span className="filter-label">Label</span>
<div className="color-filter">
{COLOR_LABELS.map((c) => (
<button
key={c.value}
className={`swatch ${filters.colors.includes(c.value) ? 'on' : ''}`}
style={{ background: c.hex }}
title={c.name}
onClick={() => toggleColor(c.value)}
/>
))}
</div>
</div>
<div className="filter-group grow">
<input
className="search"
type="search"
placeholder="Search name, camera, lens, keywords…"
value={filters.text}
onChange={(e) => patch({ text: e.target.value })}
/>
</div>
<button
className={`chip ${filters.editedOnly ? 'on' : ''}`}
onClick={() => patch({ editedOnly: !filters.editedOnly })}
title="Only show photos with develop adjustments"
>
Edited
</button>
<div className="filter-group">
<span className="filter-label">Sort</span>
<select className="select" value={sort} onChange={(e) => setSort(e.target.value as SortKey)}>
<option value="taken">Capture date</option>
<option value="added">Import date</option>
<option value="name">File name</option>
<option value="rating">Rating</option>
<option value="custom">Manual order</option>
</select>
<button
className="icon-btn"
title={asc ? 'Ascending' : 'Descending'}
onClick={() => setAsc(!asc)}
disabled={sort === 'custom'}
>
{asc ? '↑' : '↓'}
</button>
</div>
{active && (
<button
className="chip ghost"
onClick={() =>
setFilters({ minRating: 0, flag: 'any', colors: [], text: '', editedOnly: false, unrated: false })
}
>
Clear filters
</button>
)}
<div className="filter-count">
{count}
{count !== total ? ` / ${total}` : ''} shown
</div>
</div>
);
}
+63
View File
@@ -0,0 +1,63 @@
import { useEffect, useRef } from 'react';
import type { Histogram as HistogramData } from '../gl/renderer';
export default function Histogram({ data, version }: { data: HistogramData | null; version: number }) {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = ref.current;
if (!canvas) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const rect = canvas.getBoundingClientRect();
const w = Math.max(1, Math.round(rect.width * dpr));
const h = Math.max(1, Math.round(rect.height * dpr));
if (canvas.width !== w) canvas.width = w;
if (canvas.height !== h) canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = '#121214';
ctx.fillRect(0, 0, w, h);
// grid
ctx.strokeStyle = 'rgba(255,255,255,0.06)';
ctx.lineWidth = 1;
for (let i = 1; i < 4; i++) {
const x = (i / 4) * w;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, h);
ctx.stroke();
}
if (!data) return;
let peak = 0;
for (let i = 1; i < 255; i++) {
peak = Math.max(peak, data.r[i], data.g[i], data.b[i]);
}
if (peak <= 0) return;
const scale = (v: number) => Math.pow(v / peak, 0.42);
const drawChannel = (bins: Uint32Array, color: string) => {
ctx.beginPath();
ctx.moveTo(0, h);
for (let i = 0; i < 256; i++) {
const x = (i / 255) * w;
const y = h - scale(bins[i]) * (h - 2);
ctx.lineTo(x, y);
}
ctx.lineTo(w, h);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
};
ctx.globalCompositeOperation = 'lighter';
drawChannel(data.r, 'rgba(220,64,64,0.55)');
drawChannel(data.g, 'rgba(64,200,96,0.55)');
drawChannel(data.b, 'rgba(72,120,240,0.55)');
ctx.globalCompositeOperation = 'source-over';
}, [data, version]);
return <canvas className="histogram" ref={ref} />;
}
+224
View File
@@ -0,0 +1,224 @@
import { useEffect, useRef, useState } from 'react';
import type { CloudImport, ImportProgress } from '../lib/import';
import { importFiles, isSupportedFile } from '../lib/import';
import { isRawFile, RAW_ACCEPT } from '../lib/raw';
import type { EventRecord, PhotoRecord } from '../types';
interface Props {
events: EventRecord[];
initialEventId: string;
initialFiles: File[];
onClose: () => void;
onImported: (photos: PhotoRecord[], eventId: string) => void;
onCreateEvent: (name: string) => Promise<EventRecord>;
cloud?: CloudImport | null;
onNeedServer: () => void;
}
export default function ImportModal({
events,
initialEventId,
initialFiles,
onClose,
onImported,
onCreateEvent,
cloud,
onNeedServer,
}: Props) {
const startId = initialEventId !== 'all' && initialEventId !== 'unsorted' ? initialEventId : events[0]?.id ?? '__new';
const [eventId, setEventId] = useState(startId);
const [newName, setNewName] = useState('');
const [files, setFiles] = useState<File[]>(initialFiles);
const [dragOver, setDragOver] = useState(false);
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState<ImportProgress | null>(null);
const [failures, setFailures] = useState<string[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
const rawCount = files.filter(isRawFile).length;
useEffect(() => {
// Capture phase: Escape closes this dialog even while a photo is open behind it.
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const addFiles = (list: FileList | null) => {
if (!list) return;
const incoming = Array.from(list).filter(isSupportedFile);
setFiles((prev) => {
const seen = new Set(prev.map((f) => `${f.name}:${f.size}`));
return [...prev, ...incoming.filter((f) => !seen.has(`${f.name}:${f.size}`))];
});
};
const run = async () => {
if (!files.length || busy) return;
setBusy(true);
setFailures([]);
try {
let targetId = eventId;
if (targetId === '__new') {
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
targetId = created.id;
}
const result = await importFiles(files, targetId, [], setProgress, cloud ?? null);
if (result.photos.length) onImported(result.photos, targetId);
if (result.failed.length) {
setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`));
setBusy(false);
setFiles([]);
setProgress(null);
if (result.photos.length) setTimeout(onClose, 1200);
} else {
onClose();
}
} catch (err) {
setFailures([err instanceof Error ? err.message : 'Import failed']);
setBusy(false);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal">
<header className="modal-head">
<h2>Import photos</h2>
<button className="icon-btn" onClick={onClose} disabled={busy}>
✕
</button>
</header>
<div className="modal-body">
<label className="field">
<span>Event / album</span>
<select value={eventId} onChange={(e) => setEventId(e.target.value)} disabled={busy}>
{events.map((ev) => (
<option key={ev.id} value={ev.id}>
{ev.name}
</option>
))}
<option value="__new">+ New event…</option>
</select>
</label>
{eventId === '__new' && (
<label className="field">
<span>New event name</span>
<input
value={newName}
placeholder={`Event ${new Date().toLocaleDateString()}`}
onChange={(e) => setNewName(e.target.value)}
disabled={busy}
/>
</label>
)}
<div
className={`dropzone ${dragOver ? 'over' : ''}`}
onDragOver={(e) => {
e.preventDefault();
setDragOver(true);
}}
onDragLeave={() => setDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setDragOver(false);
addFiles(e.dataTransfer.files);
}}
onClick={() => inputRef.current?.click()}
>
<div className="dropzone-icon">⤒</div>
<div>
<strong>Drop photos here</strong>
<p className="muted">
or click to choose files. JPEG, PNG, WebP, AVIF, TIFF and camera raw (CR2, CR3, NEF,
ARW, ORF, RW2, RAF, DNG, PEF…) — raw needs the team server.
</p>
</div>
<input
ref={inputRef}
type="file"
accept={`image/*,${RAW_ACCEPT}`}
multiple
hidden
onChange={(e) => addFiles(e.target.files)}
/>
</div>
{files.length > 0 && (
<div className="file-summary">
<span>
{files.length} file{files.length === 1 ? '' : 's'} ready ·{' '}
{(files.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024)).toFixed(1)} MB
{rawCount > 0 ? ` · ${rawCount} raw` : ''}
</span>
<button className="link-btn" onClick={() => setFiles([])} disabled={busy}>
Clear
</button>
</div>
)}
{rawCount > 0 && !cloud && (
<div className="banner warn">
<strong>
{rawCount} raw file{rawCount === 1 ? '' : 's'} cannot be read by the browser.
</strong>{' '}
They are decoded by the team server, so sign in before importing — or import them later
from the library.
<button className="btn primary small banner-action" onClick={onNeedServer} disabled={busy}>
Sign in to the server
</button>
</div>
)}
{rawCount > 0 && cloud && (
<div className="banner info">
Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each file
usually takes 2–4 seconds.
</div>
)}
{progress && (
<div className="progress">
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${progress.total ? (progress.done / progress.total) * 100 : 0}%` }}
/>
</div>
<div className="muted small">
{progress.done} / {progress.total} {progress.current ? `· ${progress.current}` : ''}
</div>
</div>
)}
{failures.length > 0 && (
<div className="failures">
<strong>Some files could not be imported</strong>
<ul>
{failures.map((f) => (
<li key={f}>{f}</li>
))}
</ul>
</div>
)}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose} disabled={busy}>
Cancel
</button>
<button className="btn primary" onClick={() => void run()} disabled={busy || !files.length}>
{busy ? 'Importing…' : `Import ${files.length || ''}`}
</button>
</footer>
</div>
</div>
);
}
+358
View File
@@ -0,0 +1,358 @@
import { useRef, useState } from 'react';
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
import type { ColorLabel, Flag, PhotoRecord } from '../types';
import Stars, { ColorSwatches, FlagButtons } from './Stars';
interface Props {
photos: PhotoRecord[];
totalCount: number;
selected: string[];
onSelect: (id: string, e: React.MouseEvent) => void;
onContextMenu: (e: React.MouseEvent, id: string) => void;
onOpen: (id: string) => void;
onRate: (id: string, rating: number) => void;
onBulkRate: (rating: number) => void;
onBulkFlag: (flag: Flag) => void;
onBulkColor: (color: ColorLabel) => void;
onDelete: () => void;
onExport: () => void;
onImport: () => void;
onDropFiles: (files: File[]) => void;
onClearSelection: () => void;
onReorder: (ids: string[], targetId: string | null) => void;
/** rubber-band selection: the complete new selection */
onMarqueeSelect: (ids: string[]) => void;
}
function fmtSize(bytes: number) {
if (bytes > 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export default function LibraryGrid({
photos,
totalCount,
selected,
onSelect,
onContextMenu,
onOpen,
onRate,
onBulkRate,
onBulkFlag,
onBulkColor,
onDelete,
onExport,
onImport,
onDropFiles,
onClearSelection,
onReorder,
onMarqueeSelect,
}: Props) {
const gridRef = useRef<HTMLDivElement>(null);
const band = useRef<{ sx: number; sy: number; base: string[]; moved: boolean; box: DOMRect } | null>(null);
const [bandRect, setBandRect] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
const selectedSet = new Set(selected);
const someSelected = selected.length > 0;
const sharedRating = (() => {
if (!someSelected) return 0;
const rated = photos.filter((p) => selectedSet.has(p.id));
if (!rated.length) return 0;
const first = rated[0].rating;
return rated.every((p) => p.rating === first) ? first : 0;
})();
if (!photos.length) {
return (
<div
className="grid-empty"
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
const ids = draggedPhotoIds();
if (ids.length) { onReorder(ids, null);
endDrag();
return;
}
onDropFiles(Array.from(e.dataTransfer.files));
}}
ref={gridRef}
onPointerDown={(e) => {
const grid = gridRef.current;
// A band starts on empty grid space; cards keep their own click/drag.
if (!grid || e.button !== 0 || e.target !== grid) return;
e.preventDefault();
const box = grid.getBoundingClientRect();
band.current = {
sx: e.clientX,
sy: e.clientY,
base: e.shiftKey || e.metaKey || e.ctrlKey ? [...selected] : [],
moved: false,
box,
};
setBandRect({ x: e.clientX - box.left + grid.scrollLeft, y: e.clientY - box.top + grid.scrollTop, w: 0, h: 0 });
grid.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
const grid = gridRef.current;
const start = band.current;
if (!grid || !start) return;
const left = Math.min(start.sx, e.clientX);
const top = Math.min(start.sy, e.clientY);
const right = Math.max(start.sx, e.clientX);
const bottom = Math.max(start.sy, e.clientY);
if (Math.abs(e.clientX - start.sx) > 3 || Math.abs(e.clientY - start.sy) > 3) start.moved = true;
setBandRect({
x: left - start.box.left + grid.scrollLeft,
y: top - start.box.top + grid.scrollTop,
w: right - left,
h: bottom - top,
});
if (!start.moved) return;
const hits: string[] = [];
for (const el of grid.querySelectorAll<HTMLElement>('.card')) {
const r = el.getBoundingClientRect();
if (r.right > left && r.left < right && r.bottom > top && r.top < bottom) {
const id = el.dataset.id;
if (id) hits.push(id);
}
}
onMarqueeSelect([...start.base, ...hits.filter((id) => !start.base.includes(id))]);
}}
onPointerUp={(e) => {
const grid = gridRef.current;
const start = band.current;
band.current = null;
setBandRect(null);
if (!grid || !start) return;
if (grid.hasPointerCapture(e.pointerId)) grid.releasePointerCapture(e.pointerId);
if (!start.moved && !start.base.length) onClearSelection();
}}
onPointerCancel={() => {
band.current = null;
setBandRect(null);
}}
>
<div className="empty-card">
{totalCount > 0 ? (
<>
<h2>No photos match these filters</h2>
<p className="muted">Loosen the rating, flag or label filters to see more of this event.</p>
</>
) : (
<>
<h2>Your library is empty</h2>
<p className="muted">
Create an event and import a shoot. Photos are stored locally, or on your team server
when one is connected.
</p>
<button className="btn primary" onClick={onImport}>
Import photos
</button>
<p className="muted small">
Drop JPEG, PNG, TIFF or camera raw files anywhere in this area.
</p>
</>
)}
</div>
</div>
);
}
return (
<div className="grid-area">
<div className="grid-toolbar">
{someSelected ? (
<>
<span className="selection-count">{selected.length} selected</span>
<Stars value={sharedRating} onChange={onBulkRate} size="md" title="Set rating for selection (0–5)" />
<FlagButtons value={'none'} onChange={onBulkFlag} />
<ColorSwatches value={''} onChange={onBulkColor} />
<div className="spacer" />
<button className="btn ghost small" onClick={onExport}>
Export
</button>
<button className="btn ghost small danger" onClick={onDelete}>
Delete
</button>
<button className="icon-btn" title="Clear selection" onClick={onClearSelection}>
✕
</button>
</>
) : (
<>
<span className="muted small">
Click to select · drag on empty space to marquee · double-click to edit · 1–5 to rate ·{' '}
? for shortcuts
</span>
<div className="spacer" />
<span className="muted small">{photos.length} photos</span>
</>
)} </div>
<div className="grid"
onDragOver={(e) => {
if (draggedPhotoIds().length) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
}
}}
onDrop={(e) => {
e.preventDefault();
const ids = draggedPhotoIds();
if (ids.length) { onReorder(ids, null);
endDrag();
return;
}
onDropFiles(Array.from(e.dataTransfer.files));
}}
ref={gridRef}
onPointerDown={(e) => {
const grid = gridRef.current;
// A band starts on empty grid space; cards keep their own click/drag.
if (!grid || e.button !== 0 || e.target !== grid) return;
e.preventDefault();
const box = grid.getBoundingClientRect();
band.current = {
sx: e.clientX,
sy: e.clientY,
base: e.shiftKey || e.metaKey || e.ctrlKey ? [...selected] : [],
moved: false,
box,
};
setBandRect({ x: e.clientX - box.left + grid.scrollLeft, y: e.clientY - box.top + grid.scrollTop, w: 0, h: 0 });
grid.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
const grid = gridRef.current;
const start = band.current;
if (!grid || !start) return;
const left = Math.min(start.sx, e.clientX);
const top = Math.min(start.sy, e.clientY);
const right = Math.max(start.sx, e.clientX);
const bottom = Math.max(start.sy, e.clientY);
if (Math.abs(e.clientX - start.sx) > 3 || Math.abs(e.clientY - start.sy) > 3) start.moved = true;
setBandRect({
x: left - start.box.left + grid.scrollLeft,
y: top - start.box.top + grid.scrollTop,
w: right - left,
h: bottom - top,
});
if (!start.moved) return;
const hits: string[] = [];
for (const el of grid.querySelectorAll<HTMLElement>('.card')) {
const r = el.getBoundingClientRect();
if (r.right > left && r.left < right && r.bottom > top && r.top < bottom) {
const id = el.dataset.id;
if (id) hits.push(id);
}
}
onMarqueeSelect([...start.base, ...hits.filter((id) => !start.base.includes(id))]);
}}
onPointerUp={(e) => {
const grid = gridRef.current;
const start = band.current;
band.current = null;
setBandRect(null);
if (!grid || !start) return;
if (grid.hasPointerCapture(e.pointerId)) grid.releasePointerCapture(e.pointerId);
if (!start.moved && !start.base.length) onClearSelection();
}}
onPointerCancel={() => {
band.current = null;
setBandRect(null);
}}
>
{bandRect && (
<div
className="marquee"
style={{ left: bandRect.x, top: bandRect.y, width: bandRect.w, height: bandRect.h }}
/>
)}
{photos.map((p) => {
const color = COLOR_LABELS.find((c) => c.value === p.color);
const isDragging = draggedPhotoIds().includes(p.id);
return ( <figure
key={p.id}
data-id={p.id}
className={`card ${selectedSet.has(p.id) ? 'selected' : ''} ${p.flag === 'reject' ? 'rejected' : ''} ${isDragging ? 'dragging' : ''}`}
onClick={(e) => onSelect(p.id, e)}
onContextMenu={(e) => onContextMenu(e, p.id)}
onDoubleClick={() => onOpen(p.id)}
draggable
onDragStart={(e) => {
const ids = selectedSet.has(p.id) && selected.length > 1 ? selected : [p.id];
startPhotoDrag(ids);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(PHOTO_DRAG, ids.join(','));
e.dataTransfer.setData('text/plain', ids.join(','));
e.currentTarget.classList.add('dragging');
}}
onDragEnd={(e) => {
e.currentTarget.classList.remove('dragging');
endDrag();
}}
onDragOver={(e) => {
if (!draggedPhotoIds().length) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
e.currentTarget.classList.add('drop-target');
}}
onDragLeave={(e) => e.currentTarget.classList.remove('drop-target')}
onDrop={(e) => {
const ids = draggedPhotoIds();
e.currentTarget.classList.remove('drop-target');
if (!ids.length) return;
e.preventDefault();
e.stopPropagation();
onReorder(ids, p.id);
endDrag();
}}
>
<div className="card-thumb">
<img
src={p.thumbUrl ?? p.thumb}
alt={p.name}
loading="lazy"
draggable={false}
style={{ transform: thumbTransform(p) }}
/>
<div className="card-badges">
{p.flag === 'pick' && <span className="badge pick">✓</span>}
{p.flag === 'reject' && <span className="badge reject">✕</span>}
{p.raw && (
<span className="badge raw" title={p.decode === 'embedded' ? 'Raw (camera preview)' : 'Raw (demosaiced)'}>
RAW
</span>
)}
{isEdited(p.edits) && (
<span className="badge edit" title="Has develop adjustments">
✎
</span>
)}
</div>
{color && <span className="color-strip" style={{ background: color.hex }} />}
<div className="card-hover">
<span className="muted small">{fmtSize(p.size)}</span>
<span className="muted small">
{p.width}×{p.height}
</span>
</div>
</div>
<figcaption>
<div className="card-name" title={p.name}>
{p.name}
</div>
<div className="card-bottom">
<Stars value={p.rating} onChange={(n) => onRate(p.id, n)} />
{p.meta.camera && <span className="card-cam">{p.meta.camera}</span>}
</div>
</figcaption>
</figure>
);
})}
</div>
</div>
);
}
+700
View File
@@ -0,0 +1,700 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, thumbTransform } from '../lib/edits';
import { computeAutoEdits } from '../lib/auto';
import { clamp } from '../lib/curves';
import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types';
import CurveEditor from './CurveEditor';
import { getBitmap } from '../lib/images';
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets';
import { usePresetThumbs } from './PresetThumbs';
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 }: PanelSetProps) {
const [autoBusy, setAutoBusy] = useState(false);
const auto = async () => {
setAutoBusy(true);
try {
const partial = await computeAutoEdits(photo.thumb);
set(partial, 'Auto tone');
} finally {
setAutoBusy(false);
}
};
return (
<Panel title="Light">
<div className="subhead">
<span>White balance</span>
<button className="link-btn" onClick={() => set({ temp: 0, tint: 0 }, 'As shot')}>
As shot
</button>
</div>
<Slider
label="Temp"
value={edits.temp}
onChange={(v) => set({ temp: v }, 'Temperature')}
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)}
/>
<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')} />
<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={() => update(identityCurve())}>
Reset
</button>
}
>
<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]} />
</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, set }: PanelSetProps) {
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')}
/>
<div className="subhead">
<span>Noise reduction</span>
</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')}
/>
</Panel>
);
}
const BRAND_PREFIX = /^(Kodak|Fujifilm|Ilford|Agfa|CineStill|Lomography) /;
export function PresetsPanel({
presets,
photo,
onApply,
onSave,
}: {
presets: Preset[];
photo: PhotoRecord;
onApply: (preset: Preset) => void;
onSave: (name: string) => void;
}) {
const [variant, setVariant] = useState<FilmVariant>('base');
// Variants are derived on the fly, so every stock gets push/pull and split
// grade versions without tripling the catalogue.
const shown = useMemo(() => presets.map((p) => applyFilmVariant(p, variant)), [presets, variant]);
const groups = new Map<string, Preset[]>();
for (const preset of shown) {
const arr = groups.get(preset.group) ?? [];
arr.push(preset);
groups.set(preset.group, arr);
}
const thumbs = usePresetThumbs(photo, shown);
return (
<div className="panel-stack">
<div className="dev-panel-head">
<span>Presets</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="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>
{[...groups.entries()].map(([group, items]) => (
<div key={group} className="preset-group">
<div className="preset-group-name">{group}</div>
<div className="preset-grid">
{items.map((preset) => {
const src = thumbs[preset.id];
return (
<button
key={preset.id}
className="preset-tile"
onClick={() => onApply(preset)}
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">{preset.name.replace(BRAND_PREFIX, '')}</span>
</button>
);
})}
</div>
</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 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>
);
}
export function NavigatorPanel({ photo }: { photo: PhotoRecord }) {
return (
<div className="panel-stack navigator">
<div className="dev-panel-head">
<span>Navigator</span>
<span className="muted small">Fit</span>
</div>
<div className="navigator-thumb">
<img
src={photo.thumbUrl ?? photo.thumb}
alt={photo.name}
style={{ transform: thumbTransform(photo) }}
/>
</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>
);
}
export function MetadataPanel({ photo, events }: { photo: PhotoRecord; events: EventRecord[] }) {
const event = events.find((e) => e.id === photo.eventId);
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'],
];
return (
<Panel title="Info" defaultOpen={false}>
<dl className="meta">
{rows.map(([key, value]) => (
<div key={key} className="meta-row">
<dt>{key}</dt>
<dd title={value}>{value}</dd>
</div>
))}
</dl>
</Panel>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { useEffect, useState } from 'react';
import { normalizeEdits } from '../lib/edits';
import { getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types';
/**
* Preset thumbnails are rendered once per photo/preset pair and cached as small
* JPEG data URLs. One shared Renderer does all of them: a WebGL context per tile
* would exhaust the browser's context limit long before 70 presets.
*/
const cache = new Map<string, string>();
const CACHE_LIMIT = 900;
const THUMB_EDGE = 200;
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({});
// Preset edits never change after creation, so a stable id list is enough to
// avoid re-running for every parent render.
const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
useEffect(() => {
let alive = true;
let renderer: Renderer | null = null;
const canvas = document.createElement('canvas');
const known: Record<string, string> = {};
for (const preset of presets) {
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
if (hit) known[preset.id] = hit;
}
setThumbs(known);
const pending = presets.filter((p) => !known[p.id]);
if (!pending.length) return;
(async () => {
try {
const bitmap = await getBitmap(photo);
if (!alive) return;
renderer = new Renderer(canvas);
// Every tile shows the photo as it is framed now, so a turned photo's
// presets are turned too.
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
const cropW = Math.max(1, frame.w * crop.w);
const cropH = Math.max(1, frame.h * crop.h);
const scale = THUMB_EDGE / Math.max(cropW, cropH);
const width = Math.max(1, Math.round(cropW * scale));
const height = Math.max(1, Math.round(cropH * scale));
renderer.setImage(bitmap);
for (const preset of pending) {
if (!alive) break;
try {
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
width,
height,
upscale: Math.max(width / cropW, height / cropH) > 1.05,
});
const url = canvas.toDataURL('image/jpeg', 0.72);
cache.set(keyOf(photo.id, preset.id, cropKey), url);
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
} catch {
// One bad preset must not stop the rest of the grid.
}
// Yield between tiles so the panel fills in progressively.
await new Promise((resolve) => setTimeout(resolve, 0));
}
if (cache.size > CACHE_LIMIT) {
for (const key of [...cache.keys()].slice(0, cache.size - CACHE_LIMIT)) cache.delete(key);
}
} catch {
// No bitmap yet (raw not synced) or no WebGL: tiles keep their placeholders.
}
})();
return () => {
alive = false;
renderer?.dispose();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [photo.id, presetKey, cropKey]);
return thumbs;
}
+85
View File
@@ -0,0 +1,85 @@
import { useEffect } from 'react';
const GROUPS: { title: string; rows: [string, string][] }[] = [
{
title: 'Everywhere',
rows: [
['?', 'Show or hide this list'],
['⌘ / Ctrl + I', 'Import photos'],
['⌘ / Ctrl + E', 'Export'],
['Esc', 'Close a dialog'],
],
},
{
title: 'Library',
rows: [
['G', 'Library grid'],
['E', 'Open in Develop'],
['← → ↑ ↓', 'Move the selection'],
['Shift + arrows', 'Extend the selection'],
['⌘ / Ctrl + A', 'Select all shown'],
['1 – 5', 'Star rating'],
['0', 'Clear rating'],
['6 – 9', 'Red, yellow, green, blue label'],
['P / X / U', 'Pick · reject · unflag'],
['Delete', 'Remove selected photos'],
['⌘ / Ctrl + C / V', 'Copy · paste develop settings'],
['Drag on empty space', 'Rubber-band select'],
],
},
{
title: 'Develop',
rows: [
['Z', 'Fit · 100%'],
['C', 'Crop & straighten'],
['Enter', 'Apply the crop'],
['\\ (hold)', 'Before / after'],
['← →', 'Previous · next photo'],
['Scroll · drag', 'Zoom · pan'],
['⌘ / Ctrl + Z', 'Undo'],
['⌘ / Ctrl + C / V', 'Copy · paste settings'],
['Esc', 'Back to library'],
],
},
];
export default function Shortcuts({ onClose }: { onClose: () => void }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
// Keep Escape from also closing the photo or crop behind the sheet.
e.stopImmediatePropagation();
onClose();
}
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose]);
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal shortcuts-modal">
<header className="modal-head">
<h2>Keyboard shortcuts</h2>
<button className="icon-btn" onClick={onClose} title="Close">
✕
</button>
</header>
<div className="modal-body shortcut-grid">
{GROUPS.map((group) => (
<section key={group.title}>
<h3>{group.title}</h3>
{group.rows.map(([keys, what]) => (
<div className="shortcut-row" key={keys}>
<span className="shortcut-keys">{keys}</span>
<span className="shortcut-what">{what}</span>
</div>
))}
</section>
))}
</div>
</div>
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useState } from 'react';
export interface SliderProps {
label: string;
value: number;
min?: number;
max?: number;
step?: number;
def?: number;
onChange: (value: number) => void;
format?: (value: number) => string;
track?: string;
disabled?: boolean;
}
function NumberField({ value, onChange, format }: { value: number; onChange: (v: number) => void; format?: (v: number) => string }) {
const [focused, setFocused] = useState(false);
const [text, setText] = useState('');
const display = focused ? text : format ? format(value) : String(Math.round(value));
useEffect(() => {
if (!focused) setText(format ? format(value) : String(Math.round(value)));
}, [value, focused, format]);
return (
<input
className="row-num"
inputMode="decimal"
value={display}
onFocus={() => {
setText(String(Math.round(value * 100) / 100));
setFocused(true);
}}
onBlur={() => setFocused(false)}
onChange={(e) => {
setText(e.target.value);
const v = parseFloat(e.target.value);
if (Number.isFinite(v)) onChange(v);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
}}
/>
);
}
export default function Slider({
label,
value,
min = -100,
max = 100,
step = 1,
def = 0,
onChange,
format,
track,
disabled,
}: SliderProps) {
const pct = max === min ? 0 : ((value - min) / (max - min)) * 100;
return (
<div className={`row ${disabled ? 'disabled' : ''}`}>
<span
className="row-label"
title="Double-click to reset"
onDoubleClick={() => !disabled && onChange(def)}
>
{label}
</span>
<input
className="row-range"
type="range"
min={min}
max={max}
step={step}
value={value}
disabled={disabled}
style={{ '--pct': `${pct}%`, ...(track ? { '--track': track } : {}) } as React.CSSProperties}
onChange={(e) => onChange(parseFloat(e.target.value))}
onDoubleClick={() => onChange(def)}
/>
<NumberField value={value} onChange={onChange} format={format} />
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
import type { ColorLabel, Flag } from '../types';
interface Props {
value: number;
onChange?: (rating: number) => void;
size?: 'sm' | 'md' | 'lg';
title?: string;
}
export default function Stars({ value, onChange, size = 'sm', title }: Props) {
return (
<div className={`stars ${size}`} title={title}>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
disabled={!onChange}
className={`star ${value >= n ? 'on' : ''}`}
aria-label={`${n} star${n === 1 ? '' : 's'}`}
onClick={(e) => {
e.stopPropagation();
onChange?.(value === n ? 0 : n);
}}
>
★
</button>
))}
</div>
);
}
export function FlagButtons({ value, onChange }: { value: Flag; onChange: (flag: Flag) => void }) {
return (
<div className="flag-buttons">
<button
className={`flag-btn pick ${value === 'pick' ? 'on' : ''}`}
title="Pick (P)"
onClick={() => onChange(value === 'pick' ? 'none' : 'pick')}
>
✓
</button>
<button
className={`flag-btn reject ${value === 'reject' ? 'on' : ''}`}
title="Reject (X)"
onClick={() => onChange(value === 'reject' ? 'none' : 'reject')}
>
✕
</button>
</div>
);
}
export function ColorSwatches({ value, onChange }: { value: ColorLabel; onChange: (color: ColorLabel) => void }) {
return (
<div className="color-filter">
{(
[
{ c: 'red' as ColorLabel, hex: '#e05252' },
{ c: 'yellow' as ColorLabel, hex: '#e0c04a' },
{ c: 'green' as ColorLabel, hex: '#56b268' },
{ c: 'blue' as ColorLabel, hex: '#4f86e0' },
{ c: 'purple' as ColorLabel, hex: '#9b6ede' },
] as const
).map(({ c, hex }) => (
<button
key={c}
className={`swatch ${value === c ? 'on' : ''}`}
style={{ background: hex }}
title={c}
onClick={() => onChange(value === c ? '' : c)}
/>
))}
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
import type { ViewMode } from '../types';
interface Props {
view: ViewMode;
eventName: string;
photoCount: number;
selectedCount: number;
cloudLabel: string;
cloudOn: boolean;
onViewChange: (view: ViewMode) => void;
onImport: () => void;
onExport: () => void;
onCloud: () => void;
onHelp: () => void;
}
export default function TopBar({
view,
eventName,
photoCount,
selectedCount,
cloudLabel,
cloudOn,
onViewChange,
onImport,
onExport,
onCloud,
onHelp,
}: Props) {
return (
<header className="topbar">
<div className="brand">
<span className="dot" />
Lumenroom
</div>
<div className="topbar-title">
{eventName}
<span className="muted">
{' '}
· {photoCount} photo{photoCount === 1 ? '' : 's'}
{selectedCount > 1 ? ` · ${selectedCount} selected` : ''}
</span>
</div>
<nav className="module-bar">
<button className={view === 'grid' ? 'active' : ''} onClick={() => onViewChange('grid')}>
Library
</button>
<button className={view === 'develop' ? 'active' : ''} onClick={() => onViewChange('develop')}>
Develop
</button>
</nav>
<div className="topbar-actions">
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
<span className="cloud-dot" />
{cloudLabel}
</button>
<button className="btn ghost" onClick={onExport}>
Export
</button>
<button className="icon-btn help-btn" onClick={onHelp} title="Keyboard shortcuts (?)">
?
</button>
<a
className="guide-btn"
href="/lumenroom-user-guide.pdf"
target="_blank"
rel="noreferrer"
title="User guide (PDF)"
>
Guide
</a>
<button className="btn primary" onClick={onImport}>
Import photos
</button>
</div>
</header>
);
}
+970
View File
@@ -0,0 +1,970 @@
import type { Edits } from '../types';
import { buildSampler, clamp01 } from '../lib/curves';
import { bwFilterRgb } from '../lib/edits';
const VERT = `#version 300 es
layout(location = 0) in vec2 a_pos;
out vec2 v_uv;
void main(){
v_uv = a_pos * 0.5 + 0.5;
gl_Position = vec4(a_pos, 0.0, 1.0);
}`;
const GRADE_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_src;
uniform sampler2D u_curve;
uniform vec2 u_srcSize;
uniform vec2 u_frameSize;
uniform vec4 u_crop;
uniform vec4 u_valid;
uniform float u_angle;
uniform int u_quarter;
uniform vec2 u_flip;
uniform float u_upscale;
uniform float u_temp;
uniform float u_tint;
uniform float u_exposure;
uniform float u_contrast;
uniform float u_highlights;
uniform float u_shadows;
uniform float u_whites;
uniform float u_blacks;
uniform float u_vibrance;
uniform float u_saturation;
uniform float u_bw;
uniform vec3 u_bwFilter;
uniform float u_bwFilterAmt;
uniform float u_hue[8];
uniform float u_sat[8];
uniform float u_lum[8];
uniform float u_gSh;
uniform float u_gSs;
uniform float u_gHi;
uniform float u_gHs;
uniform float u_gBal;
const float HUE_CENTERS[8] = float[8](0.0, 32.0, 62.0, 120.0, 180.0, 230.0, 280.0, 320.0);
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
vec3 toLinear(vec3 c){
c = max(c, vec3(0.0));
return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
}
vec3 toSRGB(vec3 c){
c = max(c, vec3(0.0));
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
}
vec3 rgb2hsv(vec3 c){
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
vec3 hsv2rgb(vec3 c){
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
// Catmull-Rom weights for one axis; t is the fraction inside a texel.
vec4 cubicWeights(float t){
float t2 = t * t;
float t3 = t2 * t;
return vec4(
-0.5 * t3 + t2 - 0.5 * t,
1.5 * t3 - 2.5 * t2 + 1.0,
-1.5 * t3 + 2.0 * t2 + 0.5 * t,
0.5 * t3 - 0.5 * t2
);
}
// Bicubic magnification. Bilinear leaves texel-sized squares with hard edges
// once a photo is zoomed past 1:1, which reads as blocky rather than soft.
vec3 sampleBicubic(sampler2D tex, vec2 uv, vec2 size){
vec2 coord = uv * size - 0.5;
vec2 base = floor(coord);
vec2 f = coord - base;
vec4 wx = cubicWeights(f.x);
vec4 wy = cubicWeights(f.y);
float ax[4] = float[4](wx.x, wx.y, wx.z, wx.w);
float ay[4] = float[4](wy.x, wy.y, wy.z, wy.w);
vec3 sum = vec3(0.0);
for (int j = 0; j < 4; j++){
for (int i = 0; i < 4; i++){
vec2 p = (base + vec2(float(i) - 1.0, float(j) - 1.0) + 0.5) / size;
sum += texture(tex, clamp(p, vec2(0.0), vec2(1.0))).rgb * ax[i] * ay[j];
}
}
return sum;
}
void main(){
vec2 frame = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y));
// Only the cropped area carries picture data; the rest is letterbox when the
// view is zoomed out or the window aspect differs from the photo.
if (frame.x < u_valid.x || frame.y < u_valid.y ||
frame.x > u_valid.x + u_valid.z || frame.y > u_valid.y + u_valid.w) {
outColor = vec4(0.035, 0.035, 0.04, 1.0);
return;
}
vec2 p = (frame - 0.5) * u_frameSize;
float a = -(u_angle + float(u_quarter) * 1.57079632679);
float ca = cos(a);
float sa = sin(a);
vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca);
vec2 s = rp / u_srcSize + 0.5;
s = (s - 0.5) * u_flip + 0.5;
if (s.x < 0.0 || s.x > 1.0 || s.y < 0.0 || s.y > 1.0) {
outColor = vec4(0.035, 0.035, 0.04, 1.0);
return;
}
// s is already in the texture's own top-down row order, so it is sampled as
// it stands: negating y here would mirror the photo top to bottom.
vec2 uv = s;
vec3 src = u_upscale > 0.5
? sampleBicubic(u_src, uv, u_srcSize)
: texture(u_src, uv).rgb;
vec3 col = toLinear(clamp(src, 0.0, 1.0));
// White balance (relative to as-shot)
float t = u_temp / 100.0;
float ti = u_tint / 100.0;
vec3 wb = vec3(1.0 + 0.30 * t + 0.06 * ti, 1.0 - 0.16 * ti, 1.0 - 0.26 * t + 0.06 * ti);
col *= wb / max(0.05, luma(wb));
// Exposure
col *= exp2(u_exposure);
// Tonal range
float lm = clamp(luma(col), 0.0, 1.0);
col += (u_shadows / 100.0) * 0.45 * pow(1.0 - lm, 3.0);
col += (u_highlights / 100.0) * 0.50 * pow(lm, 2.0);
col += (u_whites / 100.0) * 0.34 * smoothstep(0.55, 1.0, lm);
col += (u_blacks / 100.0) * 0.13 * smoothstep(0.30, 0.0, lm);
vec3 srgb = clamp(toSRGB(col), 0.0, 1.0);
// Contrast
srgb = clamp((srgb - 0.5) * (1.0 + (u_contrast / 100.0) * 1.1) + 0.5, 0.0, 1.0);
// Tone curve (composite baked with per-channel curves)
srgb = vec3(
texture(u_curve, vec2(clamp(srgb.r, 0.0, 1.0), 0.5)).r,
texture(u_curve, vec2(clamp(srgb.g, 0.0, 1.0), 0.5)).g,
texture(u_curve, vec2(clamp(srgb.b, 0.0, 1.0), 0.5)).b
);
// HSL bands
vec3 hsv = rgb2hsv(srgb);
float hdeg = hsv.x * 360.0;
float hueWeight = smoothstep(0.02, 0.18, hsv.y);
float hShift = 0.0;
float sShift = 0.0;
float lShift = 0.0;
float wsum = 0.0;
for (int i = 0; i < 8; i++) {
float d = abs(hdeg - HUE_CENTERS[i]);
d = min(d, 360.0 - d);
float w = smoothstep(52.0, 0.0, d);
hShift += w * u_hue[i];
sShift += w * u_sat[i];
lShift += w * u_lum[i];
wsum += w;
}
float norm = max(wsum, 0.0001);
hShift = (hShift / norm) * hueWeight;
sShift = sShift / norm;
lShift = lShift / norm;
hsv.x = fract(hsv.x + (hShift / 100.0) * 0.08 + 1.0);
float satMul = sShift >= 0.0 ? 1.0 + (sShift / 100.0) * 0.8 : 1.0 + sShift / 100.0;
hsv.y = clamp(hsv.y * satMul, 0.0, 1.0);
hsv.z = clamp(hsv.z * (1.0 + (lShift / 100.0) * 0.5), 0.0, 1.0);
srgb = hsv2rgb(hsv);
if (u_bw > 0.5) {
// A colored filter over the lens changes which hues turn dark in the print:
// red drops blue skies, green lifts foliage, blue opens up shadows. The
// strength blends the transmission back towards a neutral filter.
vec3 bwTint = mix(vec3(1.0), u_bwFilter, clamp(u_bwFilterAmt, 0.0, 1.0));
float wl = max(0.05, luma(bwTint));
srgb = vec3(luma(srgb * bwTint) / wl);
}
// Vibrance and saturation
vec3 satRgb = clamp(srgb, 0.0, 1.0);
float mx = max(max(satRgb.r, satRgb.g), satRgb.b);
float mn = min(min(satRgb.r, satRgb.g), satRgb.b);
float curSat = mx - mn;
float gray = luma(satRgb);
srgb = mix(vec3(gray), satRgb, clamp(1.0 + (u_vibrance / 100.0) * (1.0 - curSat) * 0.9, 0.0, 3.0));
srgb = mix(vec3(luma(srgb)), srgb, clamp(1.0 + u_saturation / 100.0, 0.0, 3.0));
// Color grading
float gl = clamp(luma(srgb), 0.0, 1.0);
float bal = u_gBal / 100.0;
float sMask = pow(1.0 - gl, 2.0 + bal);
float hMask = pow(gl, 2.0 - bal);
vec3 shCol = hsv2rgb(vec3(u_gSh, 1.0, 1.0));
shCol -= vec3(luma(shCol));
vec3 hiCol = hsv2rgb(vec3(u_gHi, 1.0, 1.0));
hiCol -= vec3(luma(hiCol));
srgb += shCol * (u_gSs / 100.0) * 0.45 * sMask;
srgb += hiCol * (u_gHs / 100.0) * 0.45 * hMask;
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
}`;
const BLUR_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_tex;
uniform vec2 u_dir;
void main(){
vec3 s = texture(u_tex, v_uv).rgb * 0.2270270270;
s += texture(u_tex, v_uv + u_dir * 1.3846153846).rgb * 0.3162162162;
s += texture(u_tex, v_uv - u_dir * 1.3846153846).rgb * 0.3162162162;
s += texture(u_tex, v_uv + u_dir * 3.2307692308).rgb * 0.0702702703;
s += texture(u_tex, v_uv - u_dir * 3.2307692308).rgb * 0.0702702703;
outColor = vec4(s, 1.0);
}`;
const FINISH_FRAG = `#version 300 es
precision highp float;
in vec2 v_uv;
out vec4 outColor;
uniform sampler2D u_graded;
uniform sampler2D u_blurSmall;
uniform sampler2D u_blurBig;
uniform float u_texture;
uniform float u_clarity;
uniform float u_dehaze;
uniform float u_sharpen;
uniform float u_nr;
uniform float u_vigAmt;
uniform float u_vigMid;
uniform float u_vigFeather;
uniform float u_grainAmt;
uniform float u_grainSize;
uniform float u_grainRough;
uniform vec4 u_crop;
uniform vec4 u_grainFrame;
uniform vec2 u_grainSpace;
uniform vec2 u_outSize;
uniform vec2 u_frameSize;
uniform vec2 u_grainFlip;
uniform float u_grainRot;
uniform float u_grainUnits;
uniform float u_aspect;
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
// Integer hash (Dave Hoskins). A sin-based hash correlates at whole-pixel
// lattice points, which is exactly what drew diagonal streaks through grain.
float hash(vec2 p){
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
// Smooth value noise: interpolates between lattice samples instead of hashing
// whole blocks, so neighbouring pixels never sit at identical values.
float valueNoise(vec2 p){
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(
mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
u.y
);
}
void main(){
vec3 c = texture(u_graded, v_uv).rgb;
vec3 bs = texture(u_blurSmall, v_uv).rgb;
vec3 bb = texture(u_blurBig, v_uv).rgb;
// Noise reduction blends towards a smoothed version first.
float nr = clamp(u_nr / 100.0, 0.0, 1.0);
vec3 base = mix(c, mix(bs, bb, 0.5), nr * 0.6);
// Local contrast / detail work on gamma encoded values.
vec3 detailSmall = c - bs;
vec3 detailBig = base - bb;
vec3 col = base;
col += detailSmall * ((u_texture / 100.0) * 0.9 + (u_sharpen / 100.0) * 1.35);
col += detailBig * (u_clarity / 100.0) * 1.25;
// Dehaze
float d = u_dehaze / 100.0;
if (d > 0.0) {
float veil = luma(bb);
col = (col - d * 0.32 * veil * vec3(0.95, 0.98, 1.02)) / max(0.05, 1.0 - d * 0.28);
} else if (d < 0.0) {
col = mix(col, bb * 0.85 + vec3(0.09), -d * 0.55);
}
// Vignette
float amt = u_vigAmt / 100.0;
if (abs(amt) > 0.001) {
vec2 q = (v_uv - 0.5) * vec2(u_aspect, 1.0);
float r = length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5));
float mid = mix(0.18, 1.05, u_vigMid / 100.0);
float feather = mix(0.05, 1.0, u_vigFeather / 100.0);
float v = smoothstep(mid, mid + feather * 0.6, r);
float strength = abs(amt) * v;
if (amt < 0.0) col *= 1.0 - strength * 0.92;
else col = mix(col, vec3(1.0), strength * 0.6);
}
// Grain: film-like noise laid down in image space. Measured in output pixels
// a 6000 px export came out four times finer than the 1500 px preview, so the
// pattern is generated from the frame instead and every octave is band limited:
// nothing here depends on how many pixels the target happens to have.
float ga = u_grainAmt / 100.0;
if (ga > 0.001) {
float cell = mix(1.0, 3.0, clamp((u_grainSize - 10.0) / 90.0, 0.0, 1.0));
vec2 frameUv = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y));
// Grain lives on the photo, not on the output frame: the coordinates go
// through the same rotation/quarter/flip the frame uses, so straightening
// and rotating carry the texture along with the pixels instead of shifting
// it underneath them.
vec2 p = (frameUv - 0.5) * u_frameSize;
float ca = cos(u_grainRot);
float sa = sin(u_grainRot);
vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca) * u_grainFlip;
vec2 px = rp * u_grainUnits;
float pxPerUnit = length(u_outSize) / max(1.0, length(u_grainSpace * (u_crop.zw / u_grainFrame.zw)));
// Grain below a pixel cannot be drawn: it would either moire or read as a
// different, coarser pattern, so fade it out instead of rescaling it.
float vis = smoothstep(0.45, 1.0, cell * max(pxPerUnit, 1e-4));
// Roughness adds a finer octave on top of the clumps: cream at 0, bite at 100.
float w = clamp(u_grainRough / 100.0, 0.0, 1.0) * 0.85;
float fineCell = max(cell * 0.45, 1.25 / max(pxPerUnit, 1e-4));
float n = (valueNoise(px / cell) - 0.5)
+ (valueNoise(px / fineCell + 11.7) - 0.5) * w;
n *= vis * inversesqrt(1.0 + w * w);
float mask = 1.0 - abs(clamp(luma(col), 0.0, 1.0) * 2.0 - 1.0);
col += n * ga * 0.20 * (0.6 + mask * 0.4);
}
outColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}`;
export interface Histogram {
r: Uint32Array;
g: Uint32Array;
b: Uint32Array;
l: Uint32Array;
}
interface Target {
tex: WebGLTexture;
fbo: WebGLFramebuffer;
w: number;
h: number;
}
function makeHistogram(): Histogram {
return {
r: new Uint32Array(256),
g: new Uint32Array(256),
b: new Uint32Array(256),
l: new Uint32Array(256),
};
}
export function rotatedBounds(imgW: number, imgH: number, angleDeg: number, quarter = 0) {
const swap = (((Math.round(quarter) % 4) + 4) % 4) % 2 === 1;
const w0 = swap ? imgH : imgW;
const h0 = swap ? imgW : imgH;
const a = (angleDeg * Math.PI) / 180;
const c = Math.abs(Math.cos(a));
const s = Math.abs(Math.sin(a));
return {
w: Math.max(1, w0 * c + h0 * s),
h: Math.max(1, w0 * s + h0 * c),
};
}
export function outputSize(edits: Edits, imgW: number, imgH: number) {
const frame = rotatedBounds(imgW, imgH, edits.crop.angle, edits.crop.quarter);
return {
w: Math.max(1, Math.round(frame.w * edits.crop.w)),
h: Math.max(1, Math.round(frame.h * edits.crop.h)),
};
}
/**
* Frame-uv window for a loupe that tracks the crop: a `pxW` x `pxH` source-pixel
* window (pass the export's span for output-size patches), centred on the crop or
* on an explicit point, and clamped so it never samples outside the crop.
*/
export function grainSampleWindow(
frame: { w: number; h: number },
crop: { x: number; y: number; w: number; h: number },
pxW: number,
pxH: number,
point?: { x: number; y: number } | null,
) {
const w = Math.min(crop.w, pxW / Math.max(1, frame.w));
const h = Math.min(crop.h, pxH / Math.max(1, frame.h));
const cx = point ? Math.min(Math.max(point.x, crop.x), crop.x + crop.w) : crop.x + crop.w / 2;
const cy = point ? Math.min(Math.max(point.y, crop.y), crop.y + crop.h) : crop.y + crop.h / 2;
return {
x: Math.min(Math.max(cx - w / 2, crop.x), crop.x + crop.w - w),
y: Math.min(Math.max(cy - h / 2, crop.y), crop.y + crop.h - h),
w,
h,
};
}
function frameAngle(angle: number, quarter: number) {
return -((angle * Math.PI) / 180 + (quarter * Math.PI) / 2);
}
/**
* Photo coordinates (0-1 over the untouched file) to frame coordinates, through
* the same rotate / quarter turn / flip the renderer applies. Lets a click on an
* unrotated thumbnail pick the point that lands there in the straightened crop.
*/
export function sourceToFrame(
p: { x: number; y: number },
srcW: number,
srcH: number,
angle: number,
quarter: number,
flipH = false,
flipV = false,
) {
const b = rotatedBounds(srcW, srcH, angle, quarter);
// Frame uv grows the same way as the photo's pixels (y down, as the canvas
// draws them), so only a flip mirror the offset.
const sx = (p.x - 0.5) * srcW * (flipH ? -1 : 1);
const sy = (p.y - 0.5) * srcH * (flipV ? -1 : 1);
const a = frameAngle(angle, quarter);
const ca = Math.cos(-a);
const sa = Math.sin(-a);
return {
x: (sx * ca - sy * sa) / b.w + 0.5,
y: (sx * sa + sy * ca) / b.h + 0.5,
};
}
/** The inverse of `sourceToFrame`, for drawing a marker back onto the thumbnail. */
export function frameToSource(
p: { x: number; y: number },
srcW: number,
srcH: number,
angle: number,
quarter: number,
flipH = false,
flipV = false,
) {
const b = rotatedBounds(srcW, srcH, angle, quarter);
const dx = (p.x - 0.5) * b.w;
const dy = (p.y - 0.5) * b.h;
const a = frameAngle(angle, quarter);
const ca = Math.cos(a);
const sa = Math.sin(a);
const sx = (dx * ca - dy * sa) * (flipH ? -1 : 1);
const sy = (dx * sa + dy * ca) * (flipV ? -1 : 1);
return { x: sx / srcW + 0.5, y: sy / srcH + 0.5 };
}
/**
* Size of one grain cell in exported pixels, using the renderer's own scale:
* 1200 cells across the crop's long edge, cell size 1-3 units from the slider.
*/
export function grainCellPx(
edits: {
crop: { x: number; y: number; w: number; h: number; angle: number; quarter: number };
grain: { size: number };
},
srcW: number,
srcH: number,
outW: number,
) {
const { crop } = edits;
const base = rotatedBounds(srcW, srcH, 0, crop.quarter);
const unitsPerPx = 1200 / Math.max(1, base.w * crop.w, base.h * crop.h);
const frame = rotatedBounds(srcW, srcH, crop.angle, crop.quarter);
const pxPerSource = outW / Math.max(1, frame.w * crop.w);
const cell = 1 + 2 * Math.min(1, Math.max(0, (edits.grain.size - 10) / 90));
return (cell / unitsPerPx) * pxPerSource;
}
/** Builds a 256px LUT with the composite curve baked together with each channel curve. */
export function buildCurveLUT(edits: Edits): Uint8Array {
const rgb = buildSampler(edits.curve.rgb);
const red = buildSampler(edits.curve.red);
const green = buildSampler(edits.curve.green);
const blue = buildSampler(edits.curve.blue);
const data = new Uint8Array(256 * 4);
for (let i = 0; i < 256; i++) {
const base = rgb(i / 255);
data[i * 4 + 0] = Math.round(clamp01(red(base)) * 255);
data[i * 4 + 1] = Math.round(clamp01(green(base)) * 255);
data[i * 4 + 2] = Math.round(clamp01(blue(base)) * 255);
data[i * 4 + 3] = 255;
}
return data;
}
class Prog {
private cache = new Map<string, WebGLUniformLocation | null>();
constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {}
loc(name: string): WebGLUniformLocation | null {
if (!this.cache.has(name)) this.cache.set(name, this.gl.getUniformLocation(this.program, name));
return this.cache.get(name) ?? null;
}
f(name: string, v: number) {
const l = this.loc(name);
if (l) this.gl.uniform1f(l, v);
}
i(name: string, v: number) {
const l = this.loc(name);
if (l) this.gl.uniform1i(l, v);
}
v2(name: string, a: number, b: number) {
const l = this.loc(name);
if (l) this.gl.uniform2f(l, a, b);
}
v4(name: string, a: number, b: number, c: number, d: number) {
const l = this.loc(name);
if (l) this.gl.uniform4f(l, a, b, c, d);
}
v3(name: string, a: number, b: number, c: number) {
const l = this.loc(name);
if (l) this.gl.uniform3f(l, a, b, c);
}
fv(name: string, values: Float32Array) {
const l = this.loc(`${name}[0]`) ?? this.loc(name);
if (l) this.gl.uniform1fv(l, values);
}
tex(name: string, texture: WebGLTexture, unit: number) {
const l = this.loc(name);
if (!l) return;
this.gl.activeTexture(this.gl.TEXTURE0 + unit);
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
this.gl.uniform1i(l, unit);
}
}
function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader {
const shader = gl.createShader(type);
if (!shader) throw new Error('Unable to create shader');
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(`Shader compile error: ${log}`);
}
return shader;
}
function link(gl: WebGL2RenderingContext, vsSource: string, fsSource: string): WebGLProgram {
const vs = compile(gl, gl.VERTEX_SHADER, vsSource);
const fs = compile(gl, gl.FRAGMENT_SHADER, fsSource);
const program = gl.createProgram();
if (!program) throw new Error('Unable to create program');
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const log = gl.getProgramInfoLog(program);
gl.deleteProgram(program);
throw new Error(`Program link error: ${log}`);
}
return program;
}
export class Renderer {
readonly canvas: HTMLCanvasElement;
private gl: WebGL2RenderingContext;
private grade: Prog;
private blur: Prog;
private finish: Prog;
private quad: WebGLBuffer;
private vao: WebGLVertexArrayObject;
private srcTex: WebGLTexture;
private srcBitmap: ImageBitmap | null = null;
private srcW = 1;
private srcH = 1;
private curveTex: WebGLTexture;
private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {};
private histTarget: Target | null = null;
private histW = 160;
private histH = 112;
private grainRef: { x: number; y: number; w: number; h: number; sx: number; sy: number; units: number } | null = null;
histogram: Histogram = makeHistogram();
constructor(canvas: HTMLCanvasElement) {
this.canvas = canvas;
const gl = canvas.getContext('webgl2', {
alpha: false,
antialias: false,
depth: false,
stencil: false,
preserveDrawingBuffer: false,
powerPreference: 'high-performance',
});
if (!gl) throw new Error('This browser does not support WebGL2, which the editor needs.');
this.gl = gl;
this.grade = new Prog(gl, link(gl, VERT, GRADE_FRAG));
this.blur = new Prog(gl, link(gl, VERT, BLUR_FRAG));
this.finish = new Prog(gl, link(gl, VERT, FINISH_FRAG));
const quad = gl.createBuffer();
if (!quad) throw new Error('Unable to create buffer');
this.quad = quad;
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
const vao = gl.createVertexArray();
if (!vao) throw new Error('Unable to create vertex array');
this.vao = vao;
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
const srcTex = gl.createTexture();
if (!srcTex) throw new Error('Unable to create texture');
this.srcTex = srcTex;
gl.bindTexture(gl.TEXTURE_2D, srcTex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const curveTex = gl.createTexture();
if (!curveTex) throw new Error('Unable to create texture');
this.curveTex = curveTex;
gl.bindTexture(gl.TEXTURE_2D, curveTex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.disable(gl.BLEND);
gl.disable(gl.DEPTH_TEST);
}
static isSupported(): boolean {
try {
const c = document.createElement('canvas');
return !!c.getContext('webgl2');
} catch {
return false;
}
}
setImage(bitmap: ImageBitmap) {
if (this.srcBitmap === bitmap) return;
this.grainRef = null;
const gl = this.gl;
this.srcBitmap = bitmap;
this.srcW = bitmap.width;
this.srcH = bitmap.height;
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
// badly with plain bilinear sampling.
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
}
private makeTarget(w: number, h: number): Target {
const gl = this.gl;
const tex = gl.createTexture();
const fbo = gl.createFramebuffer();
if (!tex || !fbo) throw new Error('Unable to allocate render target');
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return { tex, fbo, w, h };
}
private freeTarget(target?: Target) {
if (!target) return;
this.gl.deleteTexture(target.tex);
this.gl.deleteFramebuffer(target.fbo);
}
private ensureTargets(w: number, h: number) {
const t = this.targets;
if (!t.graded || t.graded.w !== w || t.graded.h !== h) {
this.freeTarget(t.graded);
this.freeTarget(t.smallA);
this.freeTarget(t.smallB);
this.freeTarget(t.bigA);
this.freeTarget(t.bigB);
const sw = Math.max(1, Math.ceil(w / 2));
const sh = Math.max(1, Math.ceil(h / 2));
const bw = Math.max(1, Math.ceil(w / 4));
const bh = Math.max(1, Math.ceil(h / 4));
this.targets = {
graded: this.makeTarget(w, h),
smallA: this.makeTarget(sw, sh),
smallB: this.makeTarget(sw, sh),
bigA: this.makeTarget(bw, bh),
bigB: this.makeTarget(bw, bh),
};
}
}
private drawQuad() {
const gl = this.gl;
gl.bindVertexArray(this.vao);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.bindVertexArray(null);
}
private uploadCurve(edits: Edits) {
const gl = this.gl;
const data = buildCurveLUT(edits);
gl.bindTexture(gl.TEXTURE_2D, this.curveTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}
render(
edits: Edits,
opts: {
width: number;
height: number;
cropPreview?: boolean;
histogram?: boolean;
/** visible sub-rect of the frame, normalized; defaults to the whole crop */
view?: { x: number; y: number; w: number; h: number };
/** sample bicubically, for when the view magnifies the source beyond 1:1 */
upscale?: boolean;
/** hold the grain pattern still, e.g. while a crop handle is being dragged */
freezeGrain?: boolean;
},
) {
const gl = this.gl;
if (!this.srcBitmap) return;
const w = Math.max(1, Math.round(opts.width));
const h = Math.max(1, Math.round(opts.height));
if (this.canvas.width !== w) this.canvas.width = w;
if (this.canvas.height !== h) this.canvas.height = h;
this.ensureTargets(w, h);
const t = this.targets;
if (!t.graded || !t.smallA || !t.smallB || !t.bigA || !t.bigB) return;
this.uploadCurve(edits);
const bounds = rotatedBounds(this.srcW, this.srcH, edits.crop.angle, edits.crop.quarter);
const valid = opts.cropPreview
? { 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 crop = opts.view ?? valid;
// Pass 1: white balance, tone, curve, color
gl.bindFramebuffer(gl.FRAMEBUFFER, t.graded.fbo);
gl.viewport(0, 0, w, h);
const g = this.grade;
gl.useProgram(g.program);
g.tex('u_src', this.srcTex, 0);
g.tex('u_curve', this.curveTex, 1);
g.v2('u_srcSize', this.srcW, this.srcH);
g.v2('u_frameSize', bounds.w, bounds.h);
g.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
g.v4('u_valid', valid.x, valid.y, valid.w, valid.h);
g.f('u_angle', (edits.crop.angle * Math.PI) / 180);
g.i('u_quarter', edits.crop.quarter);
g.v2('u_flip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1);
g.f('u_upscale', opts.upscale ? 1 : 0);
g.f('u_temp', edits.temp);
g.f('u_tint', edits.tint);
g.f('u_exposure', edits.exposure);
g.f('u_contrast', edits.contrast);
g.f('u_highlights', edits.highlights);
g.f('u_shadows', edits.shadows);
g.f('u_whites', edits.whites);
g.f('u_blacks', edits.blacks);
g.f('u_vibrance', edits.vibrance);
g.f('u_saturation', edits.saturation);
g.f('u_bw', edits.bw ? 1 : 0);
const bwFilter = bwFilterRgb(edits.bwFilter);
g.v3('u_bwFilter', bwFilter[0], bwFilter[1], bwFilter[2]);
g.f('u_bwFilterAmt', clamp01(edits.bwFilterAmount / 100));
g.fv('u_hue', new Float32Array(edits.hsl.hue));
g.fv('u_sat', new Float32Array(edits.hsl.sat));
g.fv('u_lum', new Float32Array(edits.hsl.lum));
g.f('u_gSh', edits.grading.shadows.h / 360);
g.f('u_gSs', edits.grading.shadows.s);
g.f('u_gHi', edits.grading.highlights.h / 360);
g.f('u_gHs', edits.grading.highlights.s);
g.f('u_gBal', edits.grading.balance);
this.drawQuad();
// Passes 2-3: small blur (detail) and large blur (clarity) from the graded image
const blurPass = (from: Target, to: Target, dx: number, dy: number, srcTex: WebGLTexture) => {
const gl2 = this.gl;
gl2.bindFramebuffer(gl2.FRAMEBUFFER, to.fbo);
gl2.viewport(0, 0, to.w, to.h);
gl2.useProgram(this.blur.program);
this.blur.tex('u_tex', srcTex, 0);
this.blur.v2('u_dir', dx, dy);
this.drawQuad();
};
gl.bindFramebuffer(gl.FRAMEBUFFER, t.smallA.fbo);
gl.viewport(0, 0, t.smallA.w, t.smallA.h);
gl.useProgram(this.blur.program);
this.blur.tex('u_tex', t.graded.tex, 0);
this.blur.v2('u_dir', (edits.sharpen.radius / t.smallA.w) * 0.75, 0);
this.drawQuad();
blurPass(t.smallA, t.smallB, 0, (edits.sharpen.radius / t.smallB.h) * 0.75, t.smallA.tex);
gl.bindFramebuffer(gl.FRAMEBUFFER, t.bigA.fbo);
gl.viewport(0, 0, t.bigA.w, t.bigA.h);
gl.useProgram(this.blur.program);
this.blur.tex('u_tex', t.graded.tex, 0);
this.blur.v2('u_dir', 2.0 / t.bigA.w, 0);
this.drawQuad();
blurPass(t.bigA, t.bigB, 0, 2.0 / t.bigB.h, t.bigA.tex);
// Grain cells are counted across the crop's long edge: the same slider value
// covers the same share of the picture at every resolution and crop. While a
// handle is being dragged the reference is held, so the noise stands still.
const GRAIN_UNITS = 1200;
// Scaled from the un-straightened frame: straightening grows the rotating
// bounding box, which would otherwise resize the grain along with it.
const base = rotatedBounds(this.srcW, this.srcH, 0, edits.crop.quarter);
const cropW = Math.max(1, base.w * valid.w);
const cropH = Math.max(1, base.h * valid.h);
const grainUnits = GRAIN_UNITS / Math.max(cropW, cropH);
if (!opts.freezeGrain || !this.grainRef) {
this.grainRef = {
x: valid.x,
y: valid.y,
w: valid.w,
h: valid.h,
sx: cropW * grainUnits,
sy: cropH * grainUnits,
units: grainUnits,
};
}
const grain = this.grainRef;
const grainRot = -((edits.crop.angle * Math.PI) / 180 + (edits.crop.quarter * Math.PI) / 2);
// Pass 4: detail, effects, grain -> canvas
const finishDraw = (target: Target | null) => {
const gl2 = this.gl;
if (target) {
gl2.bindFramebuffer(gl2.FRAMEBUFFER, target.fbo);
gl2.viewport(0, 0, target.w, target.h);
} else {
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
gl2.viewport(0, 0, w, h);
}
gl2.useProgram(this.finish.program);
this.finish.tex('u_graded', t.graded!.tex, 0);
this.finish.tex('u_blurSmall', t.smallB!.tex, 1);
this.finish.tex('u_blurBig', t.bigB!.tex, 2);
this.finish.f('u_texture', edits.texture);
this.finish.f('u_clarity', edits.clarity);
this.finish.f('u_dehaze', edits.dehaze);
this.finish.f('u_sharpen', edits.sharpen.amount);
this.finish.f('u_nr', edits.noise.luminance);
this.finish.f('u_vigAmt', edits.vignette.amount);
this.finish.f('u_vigMid', edits.vignette.midpoint);
this.finish.f('u_vigFeather', edits.vignette.feather);
this.finish.f('u_grainAmt', edits.grain.amount);
this.finish.f('u_grainSize', edits.grain.size);
this.finish.f('u_grainRough', edits.grain.roughness);
this.finish.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
this.finish.v4('u_grainFrame', grain.x, grain.y, grain.w, grain.h);
this.finish.v2('u_grainSpace', grain.sx, grain.sy);
this.finish.f('u_grainUnits', grain.units);
this.finish.v2('u_frameSize', bounds.w, bounds.h);
this.finish.f('u_grainRot', grainRot);
this.finish.v2('u_grainFlip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1);
this.finish.v2('u_outSize', target ? target.w : w, target ? target.h : h);
this.finish.f('u_aspect', w / h);
this.drawQuad();
};
finishDraw(null);
if (opts.histogram) {
if (!this.histTarget) this.histTarget = this.makeTarget(this.histW, this.histH);
finishDraw(this.histTarget);
const pixels = new Uint8Array(this.histW * this.histH * 4);
gl.readPixels(0, 0, this.histW, this.histH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const hist = this.histogram;
hist.r.fill(0);
hist.g.fill(0);
hist.b.fill(0);
hist.l.fill(0);
for (let i = 0; i < pixels.length; i += 4) {
const r = pixels[i];
const gg = pixels[i + 1];
const b = pixels[i + 2];
hist.r[r]++;
hist.g[gg]++;
hist.b[b]++;
hist.l[Math.round(0.2126 * r + 0.7152 * gg + 0.0722 * b)]++;
}
}
}
dispose() {
const gl = this.gl;
this.freeTarget(this.targets.graded);
this.freeTarget(this.targets.smallA);
this.freeTarget(this.targets.smallB);
this.freeTarget(this.targets.bigA);
this.freeTarget(this.targets.bigB);
this.freeTarget(this.histTarget ?? undefined);
gl.deleteTexture(this.srcTex);
gl.deleteTexture(this.curveTex);
gl.deleteBuffer(this.quad);
gl.deleteVertexArray(this.vao);
gl.deleteProgram(this.grade.program);
gl.deleteProgram(this.blur.program);
gl.deleteProgram(this.finish.program);
// Release the context slot so switching between library and develop does not
// exhaust the browser's WebGL context limit.
const ext = gl.getExtension('WEBGL_lose_context');
ext?.loseContext();
}
}
+161
View File
@@ -0,0 +1,161 @@
import type { EventRecord, PhotoRecord, Preset } from '../types';
export interface Health {
ok: boolean;
app: string;
version: string;
needsSetup: boolean;
registrationOpen: boolean;
photos: number;
bytes: number;
raw: { libraw: boolean; sharp: boolean; formats: string[] };
}
export interface SessionUser {
id: string;
email: string;
name: string;
role: string;
}
export interface UploadResult {
raw: boolean;
engine?: 'libraw' | 'embedded';
width?: number;
height?: number;
mime?: string;
size?: number;
previewUrl?: string;
thumbUrl?: string;
note?: string | null;
}
export class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(path, { credentials: 'same-origin', ...init });
} catch {
throw new ApiError('Cannot reach the Lumenroom server', 0);
}
if (!res.ok) {
let message = `Request failed (${res.status})`;
try {
const body = (await res.json()) as { error?: string };
if (body?.error) message = body.error;
} catch {
/* non-JSON error body */
}
throw new ApiError(message, res.status);
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
}
function jsonBody(payload: unknown): RequestInit {
return {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
};
}
/** Returns null when the app is running without a server (pure browser library). */
export async function getHealth(): Promise<Health | null> {
try {
const res = await fetch('/api/health', { credentials: 'same-origin' });
if (!res.ok) return null;
const body = (await res.json()) as Health;
return body?.ok ? body : null;
} catch {
return null;
}
}
export async function register(input: {
email: string;
password: string;
name?: string;
invite?: string;
}): Promise<SessionUser> {
const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input));
return res.user;
}
export async function login(email: string, password: string): Promise<SessionUser> {
const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password }));
return res.user;
}
export async function logout(): Promise<void> {
await request('/api/auth/logout', { method: 'POST' });
}
export async function currentUser(): Promise<SessionUser | null> {
try {
const res = await request<{ user: SessionUser }>('/api/auth/me');
return res.user;
} catch (err) {
if (err instanceof ApiError && err.status === 401) return null;
return null;
}
}
export interface SyncPayload {
user: SessionUser;
events: EventRecord[];
photos: PhotoRecord[];
presets: Preset[];
}
export function pullAll(): Promise<SyncPayload> {
return request<SyncPayload>('/api/sync');
}
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> {
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: file,
});
}
export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(photo),
}).then((res) => res.photo);
}
export function deletePhotoRemote(id: string): Promise<void> {
return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
export function pushEvent(event: EventRecord): Promise<EventRecord> {
return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event),
}).then((res) => res.event);
}
export function deleteEventRemote(id: string): Promise<void> {
return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
export function pushPresets(presets: Preset[]): Promise<void> {
return request('/api/presets', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ presets }),
});
}
+73
View File
@@ -0,0 +1,73 @@
import type { Edits } from '../types';
import { clamp } from './curves';
interface Stats {
mean: number;
p05: number;
p95: number;
saturation: number;
}
async function analyze(thumb: string): Promise<Stats> {
const img = new Image();
img.src = thumb;
await img.decode();
const w = 96;
const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas unavailable');
ctx.drawImage(img, 0, 0, w, h);
const { data } = ctx.getImageData(0, 0, w, h);
const hist = new Uint32Array(256);
let total = 0;
let lumaSum = 0;
let satSum = 0;
for (let i = 0; i < data.length; i += 4) {
const r = data[i] / 255;
const g = data[i + 1] / 255;
const b = data[i + 2] / 255;
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
hist[Math.round(l * 255)]++;
lumaSum += l;
satSum += Math.max(r, g, b) - Math.min(r, g, b);
total++;
}
const percentile = (p: number) => {
const target = total * p;
let acc = 0;
for (let i = 0; i < 256; i++) {
acc += hist[i];
if (acc >= target) return i / 255;
}
return 1;
};
return {
mean: lumaSum / total,
p05: percentile(0.05),
p95: percentile(0.95),
saturation: satSum / total,
};
}
/** Simple histogram based auto tone, in the spirit of Lightroom's Auto button. */
export async function computeAutoEdits(thumb: string): Promise<Partial<Edits>> {
try {
const s = await analyze(thumb);
const mean = clamp(s.mean, 0.03, 0.97);
const exposure = clamp(Math.log2(0.46 / mean), -2, 2);
return {
exposure: Math.round(exposure * 100) / 100,
contrast: s.p95 - s.p05 < 0.55 ? 18 : 10,
highlights: s.p95 > 0.94 ? -32 : 4,
shadows: s.p05 < 0.055 ? 32 : 4,
whites: s.p95 > 0.96 ? -8 : 10,
blacks: s.p05 < 0.03 ? 6 : -6,
vibrance: s.saturation < 0.18 ? 18 : 8,
};
} catch {
return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 };
}
}
+71
View File
@@ -0,0 +1,71 @@
import type { CurvePoint } from '../types';
export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
export const clamp01 = (v: number) => clamp(v, 0, 1);
export const round2 = (v: number) => Math.round(v * 100) / 100;
export type CurveSampler = (x: number) => number;
/** Monotone cubic (Fritsch-Carlson) interpolation through normalized curve points. */
export function buildSampler(input: CurvePoint[]): CurveSampler {
const pts = [...input].sort((a, b) => a.x - b.x);
if (pts.length < 2) return (x: number) => clamp01(x);
const xs = pts.map((p) => clamp01(p.x));
const ys = pts.map((p) => clamp01(p.y));
const n = xs.length;
const d: number[] = [];
for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / Math.max(1e-6, xs[i + 1] - xs[i]));
const m: number[] = new Array(n);
m[0] = d[0];
m[n - 1] = d[n - 2];
for (let i = 1; i < n - 1; i++) {
if (d[i - 1] * d[i] <= 0) m[i] = 0;
else m[i] = (d[i - 1] + d[i]) / 2;
}
for (let i = 0; i < n - 1; i++) {
if (d[i] === 0) {
m[i] = 0;
m[i + 1] = 0;
continue;
}
const a = m[i] / d[i];
const b = m[i + 1] / d[i];
const s = a * a + b * b;
if (s > 9) {
const t = 3 / Math.sqrt(s);
m[i] = t * a * d[i];
m[i + 1] = t * b * d[i];
}
}
return (x: number) => {
if (x <= xs[0]) return clamp01(ys[0] + (x - xs[0]) * m[0]);
if (x >= xs[n - 1]) return clamp01(ys[n - 1] + (x - xs[n - 1]) * m[n - 1]);
let i = 0;
while (i < n - 2 && x > xs[i + 1]) i++;
const h = xs[i + 1] - xs[i];
const t = (x - xs[i]) / h;
const t2 = t * t;
const t3 = t2 * t;
const h00 = 2 * t3 - 3 * t2 + 1;
const h10 = t3 - 2 * t2 + t;
const h01 = -2 * t3 + 3 * t2;
const h11 = t3 - t2;
return clamp01(h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]);
};
}
export function sanitizeCurve(input: unknown): CurvePoint[] {
const fallback: CurvePoint[] = [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
if (!Array.isArray(input)) return fallback;
const pts = input
.filter((p): p is CurvePoint => !!p && typeof p.x === 'number' && typeof p.y === 'number')
.map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) }))
.sort((a, b) => a.x - b.x);
return pts.length >= 2 ? pts : fallback;
}
+91
View File
@@ -0,0 +1,91 @@
import type { EventRecord, PhotoRecord } from '../types';
const DB_NAME = 'lumenroom';
const DB_VERSION = 1;
let dbPromise: Promise<IDBDatabase> | null = null;
export function openDB(): Promise<IDBDatabase> {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains('photos')) {
const store = db.createObjectStore('photos', { keyPath: 'id' });
store.createIndex('eventId', 'eventId', { unique: false });
}
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
});
return dbPromise;
}
function wrap<T>(request: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));
});
}
async function store(name: string, mode: IDBTransactionMode = 'readonly') {
const db = await openDB();
return db.transaction(name, mode).objectStore(name);
}
export async function getAllPhotos(): Promise<PhotoRecord[]> {
return wrap((await store('photos')).getAll() as IDBRequest<PhotoRecord[]>);
}
export async function putPhoto(photo: PhotoRecord): Promise<void> {
await wrap((await store('photos', 'readwrite')).put(photo));
}
export async function deletePhotoRecord(id: string): Promise<void> {
const db = await openDB();
const tx = db.transaction(['photos', 'assets'], 'readwrite');
tx.objectStore('photos').delete(id);
tx.objectStore('assets').delete(id);
await new Promise<void>((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function putAsset(id: string, blob: Blob): Promise<void> {
await wrap((await store('assets', 'readwrite')).put(blob, id));
}
export async function getAsset(id: string): Promise<Blob | undefined> {
return wrap((await store('assets')).get(id) as IDBRequest<Blob | undefined>);
}
export async function getAllEvents(): Promise<EventRecord[]> {
return wrap((await store('events')).getAll() as IDBRequest<EventRecord[]>);
}
export async function putEvent(event: EventRecord): Promise<void> {
await wrap((await store('events', 'readwrite')).put(event));
}
export async function deleteEventRecord(id: string): Promise<void> {
await wrap((await store('events', 'readwrite')).delete(id));
}
export async function getKV<T>(key: string): Promise<T | undefined> {
return wrap((await store('kv')).get(key) as IDBRequest<T | undefined>);
}
export async function setKV(key: string, value: unknown): Promise<void> {
await wrap((await store('kv', 'readwrite')).put(value, key));
}
export async function estimateUsage(): Promise<{ usage: number; quota: number }> {
if (!navigator.storage?.estimate) return { usage: 0, quota: 0 };
const est = await navigator.storage.estimate();
return { usage: est.usage ?? 0, quota: est.quota ?? 0 };
}
+34
View File
@@ -0,0 +1,34 @@
/**
* Drag payloads live in a module variable because browsers only expose
* `dataTransfer.getData` on drop, not during dragover — and we need to know
* whether a photo (rather than an OS file) is being dragged while hovering.
*/
let photoIds: string[] = [];
let eventId: string | null = null;
export const PHOTO_DRAG = 'application/x-lumen-photos';
export const EVENT_DRAG = 'application/x-lumen-event';
export function startPhotoDrag(ids: string[]) {
photoIds = ids;
eventId = null;
}
export function draggedPhotoIds(): string[] {
return photoIds;
}
export function startEventDrag(id: string) {
eventId = id;
photoIds = [];
}
export function draggedEventId(): string | null {
return eventId;
}
export function endDrag() {
photoIds = [];
eventId = null;
}
+296
View File
@@ -0,0 +1,296 @@
import type { BwFilter, ColorLabel, CropState, CurvePoint, Edits, Flag, PhotoRecord, PhotoMeta } from '../types';
import { clamp, clamp01, sanitizeCurve } from './curves';
export interface HueBand {
key: string;
name: string;
center: number;
swatch: string;
}
export const HUE_BANDS: HueBand[] = [
{ key: 'red', name: 'Red', center: 0, swatch: '#e2453c' },
{ key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' },
{ key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' },
{ key: 'green', name: 'Green', center: 120, swatch: '#57a95a' },
{ key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' },
{ key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' },
{ key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' },
{ key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' },
];
/**
* Photographic contrast filters for black & white: transmission per channel.
* A red filter passes red and blocks blue, so skies print almost black.
*/
export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [
{ id: 'none', label: 'None', rgb: [1, 1, 1] },
{ id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] },
{ id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] },
{ id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] },
{ id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] },
{ id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] },
];
export function bwFilterRgb(id: BwFilter): [number, number, number] {
return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1];
}
/**
* CSS transform that shows a grid thumbnail in the photo's *current* orientation.
* Uses the same order as the renderer: flips act on the photo, then the quarter
* turns and straighten rotate it, and the result is scaled so the rotated image
* still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps).
*/
export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
const { quarter, angle, flipH, flipV } = photo.edits.crop;
const deg = quarter * 90 + angle;
if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none';
const w = Math.max(1, photo.width || 1);
const h = Math.max(1, photo.height || 1);
const boxH = 1 / boxAspect;
// object-fit: cover — the photo already fills the card before any transform.
const cover = Math.max(1 / w, boxH / h);
const dw = w * cover;
const dh = h * cover;
const rad = (Math.abs(deg) * Math.PI) / 180;
const c = Math.abs(Math.cos(rad));
const s = Math.abs(Math.sin(rad));
// A rotated photo has to contain all four corners of the card, not just its
// bounding box: after un-rotating a card corner by -deg it sits at
// ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide
// and tall. Fitting the bounding box instead leaves gaps on angle-only turns.
const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh);
// A thumbnail's rounded pixel size can differ from the record's ratio by a
// fraction of a percent; a hair of slack keeps it from showing a sliver at
// the edge. It is invisible at any real card size.
const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit;
const parts = [`rotate(${deg.toFixed(2)}deg)`];
// Round up: rounding the scale down would leave a hairline gap at the edge.
const rounded = Math.ceil(fit * 1e4) / 1e4;
if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`);
if (flipH) parts.push('scaleX(-1)');
if (flipV) parts.push('scaleY(-1)');
return parts.join(' ');
}
export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [
{ id: 'original', label: 'Original', ratio: null },
{ id: 'free', label: 'Free', ratio: null },
{ id: '1:1', label: '1 × 1', ratio: 1 },
{ id: '4:5', label: '4 × 5', ratio: 4 / 5 },
{ id: '5:4', label: '5 × 4', ratio: 5 / 4 },
{ id: '4:3', label: '4 × 3', ratio: 4 / 3 },
{ id: '3:2', label: '3 × 2', ratio: 3 / 2 },
{ id: '16:9', label: '16 × 9', ratio: 16 / 9 },
{ id: '2:1', label: '2 × 1', ratio: 2 },
{ id: '9:16', label: '9 × 16', ratio: 9 / 16 },
];
export function defaultCrop(): CropState {
return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false };
}
export function identityCurve(): CurvePoint[] {
return [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
}
export function defaultEdits(): Edits {
return {
temp: 0,
tint: 0,
exposure: 0,
contrast: 0,
highlights: 0,
shadows: 0,
whites: 0,
blacks: 0,
texture: 0,
clarity: 0,
dehaze: 0,
vibrance: 0,
saturation: 0,
bw: false,
bwFilter: 'none',
bwFilterAmount: 100,
curve: {
rgb: identityCurve(),
red: identityCurve(),
green: identityCurve(),
blue: identityCurve(),
},
hsl: {
hue: HUE_BANDS.map(() => 0),
sat: HUE_BANDS.map(() => 0),
lum: HUE_BANDS.map(() => 0),
},
grading: {
shadows: { h: 210, s: 0 },
highlights: { h: 45, s: 0 },
balance: 0,
},
sharpen: { amount: 0, radius: 1, detail: 25 },
noise: { luminance: 0, detail: 50 },
vignette: { amount: 0, midpoint: 50, feather: 50 },
grain: { amount: 0, size: 25, roughness: 50 },
crop: defaultCrop(),
};
}
function bands(input: unknown): number[] {
const arr = Array.isArray(input) ? input : [];
return HUE_BANDS.map((_, i) => {
const v = arr[i];
return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0;
});
}
function num(value: unknown, fallback: number, lo: number, hi: number): number {
return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback;
}
/** Deep-merge stored edits with the current defaults so older records keep working. */
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
const d = defaultEdits();
if (!input) return d;
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
const vignette = (input.vignette ?? {}) as Partial<Edits['vignette']>;
const grain = (input.grain ?? {}) as Partial<Edits['grain']>;
const crop = (input.crop ?? {}) as Partial<CropState>;
return {
...d,
...input,
temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100),
exposure: num(input.exposure, 0, -5, 5),
contrast: num(input.contrast, 0, -100, 100),
highlights: num(input.highlights, 0, -100, 100),
shadows: num(input.shadows, 0, -100, 100),
whites: num(input.whites, 0, -100, 100),
blacks: num(input.blacks, 0, -100, 100),
texture: num(input.texture, 0, -100, 100),
clarity: num(input.clarity, 0, -100, 100),
dehaze: num(input.dehaze, 0, -100, 100),
vibrance: num(input.vibrance, 0, -100, 100),
saturation: num(input.saturation, 0, -100, 100),
bw: !!input.bw,
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
curve: {
rgb: sanitizeCurve(curve.rgb),
red: sanitizeCurve(curve.red),
green: sanitizeCurve(curve.green),
blue: sanitizeCurve(curve.blue),
},
hsl: {
hue: bands(input.hsl?.hue),
sat: bands(input.hsl?.sat),
lum: bands(input.hsl?.lum),
},
grading: {
shadows: {
h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360),
s: num(grading.shadows?.s, 0, 0, 100),
},
highlights: {
h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360),
s: num(grading.highlights?.s, 0, 0, 100),
},
balance: num(grading.balance, 0, -100, 100),
},
sharpen: {
amount: num(sharpen.amount, 0, 0, 150),
radius: num(sharpen.radius, 1, 0.5, 3),
detail: num(sharpen.detail, 25, 0, 100),
},
noise: {
luminance: num(noise.luminance, 0, 0, 100),
detail: num(noise.detail, 50, 0, 100),
},
vignette: {
amount: num(vignette.amount, 0, -100, 100),
midpoint: num(vignette.midpoint, 50, 0, 100),
feather: num(vignette.feather, 50, 0, 100),
},
grain: {
amount: num(grain.amount, 0, 0, 100),
size: num(grain.size, 25, 10, 100),
roughness: num(grain.roughness, 50, 0, 100),
},
crop: {
x: clamp01(num(crop.x, 0, 0, 1)),
y: clamp01(num(crop.y, 0, 0, 1)),
w: clamp01(num(crop.w, 1, 0.02, 1)),
h: clamp01(num(crop.h, 1, 0.02, 1)),
angle: num(crop.angle, 0, -45, 45),
quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter)
? ((Math.round(crop.quarter) % 4) + 4) % 4
: 0,
aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original',
flipH: !!crop.flipH,
flipV: !!crop.flipV,
},
};
}
const editCache = new WeakMap<Edits, boolean>();
export function isEdited(edits: Edits): boolean {
const cached = editCache.get(edits);
if (cached !== undefined) return cached;
const d = defaultEdits();
const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } });
const result = strip(edits) !== strip(d);
editCache.set(edits, result);
return result;
}
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
const edits = normalizeEdits(input.edits);
const addedAt = input.addedAt ?? Date.now();
const meta: PhotoMeta = input.meta ?? {};
return {
id: input.id,
eventId: input.eventId ?? '',
order: typeof input.order === 'number' ? input.order : undefined,
raw: !!input.raw,
decode: input.decode,
previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl,
name: input.name ?? 'Untitled',
width: input.width ?? 0,
height: input.height ?? 0,
size: input.size ?? 0,
mime: input.mime ?? 'image/jpeg',
addedAt,
takenAt: input.takenAt,
meta,
thumb: input.thumb ?? '',
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
flag: (input.flag ?? 'none') as Flag,
color: (input.color ?? '') as ColorLabel,
keywords: Array.isArray(input.keywords) ? input.keywords : [],
edits,
history:
Array.isArray(input.history) && input.history.length
? input.history
: [{ label: 'Import', ts: addedAt, edits }],
};
}
export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [
{ value: 'red', name: 'Red', hex: '#e05252' },
{ value: 'yellow', name: 'Yellow', hex: '#e0c04a' },
{ value: 'green', name: 'Green', hex: '#56b268' },
{ value: 'blue', name: 'Blue', hex: '#4f86e0' },
{ value: 'purple', name: 'Purple', hex: '#9b6ede' },
];
+137
View File
@@ -0,0 +1,137 @@
import type { Edits, PhotoRecord } from '../types';
import { getBitmap } from './images';
import { normalizeEdits } from './edits';
import { outputSize, Renderer } from '../gl/renderer';
export type ExportFormat = 'jpeg' | 'png' | 'webp';
export type ResizeMode = 'none' | 'longEdge' | 'percent';
export interface ExportOptions {
format: ExportFormat;
quality: number;
resize: ResizeMode;
longEdge: number;
percent: number;
nameTemplate: string;
}
export const DEFAULT_EXPORT: ExportOptions = {
format: 'jpeg',
quality: 92,
resize: 'none',
longEdge: 3000,
percent: 100,
nameTemplate: '{name}',
};
const MIME: Record<ExportFormat, string> = {
jpeg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
};
const EXT: Record<ExportFormat, string> = {
jpeg: 'jpg',
png: 'png',
webp: 'webp',
};
function download(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 4000);
}
function pad(n: number) {
return String(n).padStart(2, '0');
}
export function buildFileName(template: string, photo: PhotoRecord, index: number, opts: ExportOptions) {
const stamp = new Date(photo.takenAt ?? photo.addedAt);
const base = photo.name.replace(/\.[^.]+$/, '') || 'export';
const name = (template || '{name}')
.replace(/\{name\}/g, base)
.replace(/\{date\}/g, `${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}`)
.replace(/\{time\}/g, `${pad(stamp.getHours())}${pad(stamp.getMinutes())}`)
.replace(/\{index\}/g, String(index + 1).padStart(3, '0'))
.replace(/[\\/:*?"<>|]+/g, '-')
.trim();
return `${name || 'export'}.${EXT[opts.format]}`;
}
function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts: ExportOptions) {
const size = outputSize(edits, bitmap.width, bitmap.height);
const longEdge = Math.max(size.w, size.h);
let scale = 1;
if (opts.resize === 'longEdge' && opts.longEdge > 0 && longEdge > opts.longEdge) {
scale = opts.longEdge / longEdge;
} else if (opts.resize === 'percent') {
scale = Math.min(2, Math.max(0.05, opts.percent / 100));
}
return {
w: Math.max(1, Math.round(size.w * scale)),
h: Math.max(1, Math.round(size.h * scale)),
};
}
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
const bitmap = await getBitmap(photo);
const edits = normalizeEdits(photo.edits);
const { w, h } = targetSize(photo, edits, bitmap, opts);
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const renderer = new Renderer(canvas);
try {
renderer.setImage(bitmap);
renderer.render(edits, { width: w, height: h });
const mime = MIME[opts.format];
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
);
if (!blob) throw new Error('Export failed while encoding the image');
return blob;
} finally {
renderer.dispose();
}
}
export async function exportPhotos(
photos: PhotoRecord[],
opts: ExportOptions,
onProgress?: (done: number, total: number) => void,
): Promise<{ count: number; failed: string[] }> {
let count = 0;
const failed: string[] = [];
for (let i = 0; i < photos.length; i++) {
const photo = photos[i];
try {
const blob = await renderPhotoBlob(photo, opts);
download(blob, buildFileName(opts.nameTemplate, photo, i, opts));
count++;
} catch (err) {
console.error('Export failed for', photo.name, err);
failed.push(photo.name);
}
onProgress?.(i + 1, photos.length);
// Give the browser a beat so long batches keep the tab responsive.
await new Promise((r) => setTimeout(r, 0));
}
return { count, failed };
}
/** Backwards compatible single-photo export. */
export async function exportPhoto(photo: PhotoRecord, maxLongEdge = 0): Promise<void> {
const opts: ExportOptions = {
...DEFAULT_EXPORT,
resize: maxLongEdge > 0 ? 'longEdge' : 'none',
longEdge: maxLongEdge || DEFAULT_EXPORT.longEdge,
};
const blob = await renderPhotoBlob(photo, opts);
download(blob, buildFileName(opts.nameTemplate, photo, 0, opts));
}
+67
View File
@@ -0,0 +1,67 @@
import type { PhotoRecord } from '../types';
import { getAsset, putAsset } from './db';
const CACHE_LIMIT = 6;
const cache = new Map<string, ImageBitmap>();
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
export function remoteAssetUrl(photo: PhotoRecord): string {
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
return `/api/photos/${encodeURIComponent(photo.id)}/original`;
}
async function fetchRemote(photo: PhotoRecord): Promise<Blob | null> {
try {
const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' });
if (!res.ok) return null;
const blob = await res.blob();
// Cache it locally so the photo keeps working offline after the first look.
await putAsset(photo.id, blob).catch(() => undefined);
return blob;
} catch {
return null;
}
}
export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
const hit = cache.get(photo.id);
if (hit) {
cache.delete(photo.id);
cache.set(photo.id, hit);
return hit;
}
let blob = await getAsset(photo.id);
if (!blob) blob = (await fetchRemote(photo)) ?? undefined;
if (!blob) {
throw new Error(
photo.raw
? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.'
: 'Original image data is missing from browser storage',
);
}
// Apply EXIF orientation so the pixels the editor works on are upright.
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
cache.set(photo.id, bitmap);
while (cache.size > CACHE_LIMIT) {
const first = cache.keys().next();
if (first.done) break;
const old = cache.get(first.value);
cache.delete(first.value);
old?.close();
}
return bitmap;
}
export function evictBitmap(photoId: string) {
const bmp = cache.get(photoId);
if (!bmp) return;
cache.delete(photoId);
bmp.close();
}
export function clearBitmapCache() {
for (const bmp of cache.values()) bmp.close();
cache.clear();
}
+240
View File
@@ -0,0 +1,240 @@
import exifr from 'exifr';
import type { UploadResult } from './api';
import type { PhotoMeta, PhotoRecord } from '../types';
import { putAsset, putPhoto } from './db';
import { defaultEdits, normalizePhoto } from './edits';
import { isRawFile, RAW_EXTENSIONS } from './raw';
export interface ImportProgress {
done: number;
total: number;
current: string;
}
export interface ImportResult {
photos: PhotoRecord[];
failed: { name: string; reason: string }[];
}
/** Provided by the app when a Lumenroom server is connected. */
export interface CloudImport {
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
}
/** Files imported at once; the server bounds how many raws decode in parallel. */
const IMPORT_CONCURRENCY = 4;
export function uid(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
let cursor = 0;
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
for (;;) {
const index = cursor++;
if (index >= items.length) return;
await fn(items[index], index);
}
});
return Promise.all(runners);
}
function formatShutter(time: unknown): string | undefined {
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
return `1/${Math.round(1 / time)}s`;
}
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
try {
const data = (await exifr.parse(file, {
tiff: true,
exif: true,
gps: false,
interop: false,
translateValues: false,
reviveValues: true,
})) as Record<string, unknown> | undefined;
if (!data) return { meta: {} };
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
const meta: PhotoMeta = {
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
shutter: formatShutter(data.ExposureTime),
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
};
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
return { meta, takenAt };
} catch {
return { meta: {} };
}
}
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
const max = 560;
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
const w = Math.max(1, Math.round(bitmap.width * scale));
const h = Math.max(1, Math.round(bitmap.height * scale));
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas 2D is unavailable');
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(bitmap, 0, 0, w, h);
return canvas.toDataURL('image/jpeg', 0.82);
}
export function isSupportedFile(file: File): boolean {
if (file.type.startsWith('image/')) return true;
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
}
/**
* Raw files cannot be decoded by the browser, so they are sent to the server,
* demosaiced there, and represented locally by the returned editable proxy.
*/
async function importRaw(file: File, eventId: string, keywords: string[], cloud: CloudImport): Promise<PhotoRecord> {
const id = uid();
const upload = await cloud.uploadOriginal(id, file, file.name);
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
const res = await fetch(previewUrl, { credentials: 'same-origin' });
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
const blob = await res.blob();
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
const thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file);
const width = upload.width ?? bitmap.width;
const height = upload.height ?? bitmap.height;
bitmap.close();
const record = normalizePhoto({
id,
eventId,
name: file.name,
width,
height,
size: file.size,
mime: 'image/jpeg',
addedAt: Date.now(),
takenAt: takenAt ?? file.lastModified,
meta,
thumb,
rating: 0,
flag: 'none',
color: '',
keywords,
edits: defaultEdits(),
history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }],
raw: true,
decode: upload.engine,
previewUrl,
});
await putPhoto(record);
// No local blob: the multi-megabyte raw stays on the server.
const saved = await cloud.push(record);
const merged = normalizePhoto({ ...record, ...saved });
await putPhoto(merged);
return merged;
}
async function importStandard(
file: File,
eventId: string,
keywords: string[],
cloud?: CloudImport | null,
): Promise<PhotoRecord> {
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
// the thumbnail and the edited proxy agree with what the camera shot.
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
const thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file);
const id = uid();
let record = normalizePhoto({
id,
eventId,
name: file.name,
width: bitmap.width,
height: bitmap.height,
size: file.size,
mime: file.type || 'image/jpeg',
addedAt: Date.now(),
takenAt: takenAt ?? file.lastModified,
meta,
thumb,
rating: 0,
flag: 'none',
color: '',
keywords,
edits: defaultEdits(),
history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }],
});
await putAsset(id, file);
bitmap.close();
if (cloud) {
// Originals are mirrored to the server; failures fall back to a local-only import.
try {
await cloud.uploadOriginal(id, file, file.name);
const saved = await cloud.push(record);
record = normalizePhoto({ ...record, ...saved });
} catch (err) {
console.warn('Could not copy the original to the server', file.name, err);
}
}
await putPhoto(record);
return record;
}
export async function importFiles(
files: File[],
eventId: string,
keywords: string[] = [],
onProgress?: (p: ImportProgress) => void,
cloud?: CloudImport | null,
): Promise<ImportResult> {
const result: ImportResult = { photos: [], failed: [] };
const images = files.filter(isSupportedFile);
const total = images.length;
if (!total) return result;
const collected: { index: number; photo: PhotoRecord }[] = [];
let done = 0;
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
try {
const photo = isRawFile(file)
? cloud
? await importRaw(file, eventId, keywords, cloud)
: (() => {
throw new Error('Raw files need the Lumenroom server. Sign in, then import again.');
})()
: await importStandard(file, eventId, keywords, cloud);
collected.push({ index, photo });
} catch (err) {
result.failed.push({
name: file.name,
reason: err instanceof Error ? err.message : 'Unsupported image format',
});
} finally {
done += 1;
onProgress?.({ done, total, current: file.name });
}
});
// Keep the shoot in capture/selection order regardless of which finished first.
collected.sort((a, b) => a.index - b.index);
result.photos = collected.map((c) => c.photo);
onProgress?.({ done: total, total, current: '' });
return result;
}
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
/** Raw containers the server can demosaic (LibRaw) or fall back to previews for. */
export const RAW_EXTENSIONS = new Set([
'cr2', 'cr3', 'crw',
'nef', 'nrw',
'arw', 'srf', 'sr2',
'orf',
'rw2', 'raw', 'rwl',
'raf',
'pef', 'dng',
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef',
]);
export function isRawFile(file: File): boolean {
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext);
}
export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(',');
+7
View File
@@ -0,0 +1,7 @@
import { createRoot } from 'react-dom/client';
import App from './App';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('root element missing');
createRoot(root).render(<App />);
File diff suppressed because it is too large Load Diff
+145
View File
@@ -0,0 +1,145 @@
export type ViewMode = 'grid' | 'develop';
export type Flag = 'none' | 'pick' | 'reject';
export type ColorLabel = '' | 'red' | 'yellow' | 'green' | 'blue' | 'purple';
/** Contrast filter placed over the lens when shooting black & white film. */
export type BwFilter = 'none' | 'yellow' | 'orange' | 'red' | 'green' | 'blue';
export type CurveChannel = 'rgb' | 'red' | 'green' | 'blue';
export interface CurvePoint {
x: number;
y: number;
}
export interface CropState {
/** normalized crop rect inside the straightened frame, origin top-left */
x: number;
y: number;
w: number;
h: number;
/** straighten angle in degrees */
angle: number;
/** extra 90° turns applied before the straighten angle, 0–3 */
quarter: number;
/** locked aspect preset id, "free" or "original" */
aspect: string;
flipH: boolean;
flipV: boolean;
}
export interface Edits {
temp: number;
tint: number;
exposure: number;
contrast: number;
highlights: number;
shadows: number;
whites: number;
blacks: number;
texture: number;
clarity: number;
dehaze: number;
vibrance: number;
saturation: number;
bw: boolean;
/** colored filter simulated in black & white mode */
bwFilter: BwFilter;
/** how strongly that filter acts, 0–100 */
bwFilterAmount: number;
curve: Record<CurveChannel, CurvePoint[]>;
hsl: { hue: number[]; sat: number[]; lum: number[] };
grading: {
shadows: { h: number; s: number };
highlights: { h: number; s: number };
balance: number;
};
sharpen: { amount: number; radius: number; detail: number };
noise: { luminance: number; detail: number };
vignette: { amount: number; midpoint: number; feather: number };
/** roughness leans from creamy clumps (0) to crisp per-pixel bite (100) */
grain: { amount: number; size: number; roughness: number };
crop: CropState;
}
export interface PhotoMeta {
camera?: string;
lens?: string;
iso?: number;
aperture?: number;
shutter?: string;
focal?: number;
}
export interface HistoryEntry {
label: string;
ts: number;
edits: Edits;
}
export interface PhotoRecord {
id: string;
eventId: string;
/** manual sort position inside the event */
order?: number;
name: string;
width: number;
height: number;
size: number;
mime: string;
addedAt: number;
takenAt?: number;
meta: PhotoMeta;
thumb: string;
rating: number;
flag: Flag;
color: ColorLabel;
keywords: string[];
edits: Edits;
history: HistoryEntry[];
/** true when the original is a camera raw decoded by the server */
raw?: boolean;
/** how the editable proxy was produced */
decode?: 'libraw' | 'embedded';
/** server URL for the editable proxy (raw only) */
previewUrl?: string;
/** server URL for the grid thumbnail */
thumbUrl?: string;
/** Set when the photo is proxied from a dashboard bridge session. */
bridgeSource?: { sessionId: string; sourceId: string };
}
export interface EventRecord {
id: string;
name: string;
date?: number;
createdAt: number;
notes?: string;
/** sidebar position */
order?: number;
/** Set when this event is a temporary import from the dashboard bridge. */
bridge?: {
sessionId: string;
sourceEventId: string;
/** Where "Back to dashboard" goes. */
dashboardUrl: string;
expiresAt: number;
};
}
export interface Filters {
minRating: number;
flag: Flag | 'any';
colors: ColorLabel[];
text: string;
editedOnly: boolean;
unrated: boolean;
}
export type SortKey = 'taken' | 'added' | 'name' | 'rating' | 'custom';
export interface Preset {
id: string;
name: string;
group: string;
edits: Partial<Omit<Edits, 'crop'>>;
custom?: boolean;
}