feat(editor): bridge the advanced photo editor into the event workflow
CI / build (push) Has been cancelled
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:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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} />;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 & white mix</span>
|
||||
</label>
|
||||
{edits.bw && (
|
||||
<>
|
||||
<div className="subhead">
|
||||
<span>B&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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user