Initial commit: Luminary photo catalog and RAW editor

Browser-based photo catalog with an optional team server (SQLite + LibRaw).
Local database, uploaded photos, build output and dependencies are gitignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-23 15:19:25 +00:00
commit cd52a2f82f
121 changed files with 101872 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
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;
onAdmin: () => 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,
onAdmin,
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>
{user.role === 'admin' && (
<button className="btn ghost" onClick={onAdmin} disabled={busy}>
Administration
</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 link or code</span>
<input
value={invite}
onChange={(e) => setInvite(e.target.value)}
placeholder="Paste the link from your admin"
/>
</label>
)}
{mode === 'signup' && health.needsSetup && (
<p className="muted small">
The first account becomes the team admin. After that, create single-use invite links under
Administration → Invites.
</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>{health.storage?.root ?? 'server/data'}</code> · raw formats:{' '}
{health.raw.formats.length} · {health.raw.sharp ? 'JPEG encoder ready' : 'PNG fallback'}
</p>
)}
</div>
</div>
</div>
);
}
+183
View File
@@ -0,0 +1,183 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { EventRecord, PhotoRecord } from '../types';
export interface PaletteAction {
id: string;
label: string;
hint?: string;
run: () => void;
}
interface Props {
events: EventRecord[];
photos: PhotoRecord[];
actions: PaletteAction[];
onOpenEvent: (id: string) => void;
onOpenPhoto: (id: string) => void;
onClose: () => void;
}
interface Result {
key: string;
label: string;
hint: string;
kind: 'event' | 'photo' | 'action';
thumb?: string;
run: () => void;
}
export default function CommandPalette({
events,
photos,
actions,
onOpenEvent,
onOpenPhoto,
onClose,
}: Props) {
const [query, setQuery] = useState('');
const [active, setActive] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
useEffect(() => {
setActive(0);
}, [query]);
const eventNames = useMemo(
() => new Map(events.map((event) => [event.id, event.name])),
[events],
);
const results = useMemo(() => {
const term = query.trim().toLowerCase();
const matches = (values: (string | undefined)[]) =>
!term || values.some((value) => value?.toLowerCase().includes(term));
const actionsFound: Result[] = actions
.filter((action) => matches([action.label, action.hint]))
.slice(0, 5)
.map((action) => ({
key: `action:${action.id}`,
label: action.label,
hint: action.hint ?? 'Action',
kind: 'action',
run: action.run,
}));
const eventsFound: Result[] = events
.filter((event) => matches([event.name]))
.slice(0, 6)
.map((event) => ({
key: `event:${event.id}`,
label: event.name,
hint: 'Event',
kind: 'event',
run: () => onOpenEvent(event.id),
}));
const photosFound: Result[] = photos
.filter((photo) =>
matches([
photo.name,
photo.title,
photo.caption,
photo.creator,
photo.meta.camera,
photo.meta.lens,
eventNames.get(photo.eventId),
...photo.keywords,
]),
)
.slice(0, 18)
.map((photo) => ({
key: `photo:${photo.id}`,
label: photo.title || photo.name,
hint: [eventNames.get(photo.eventId), photo.meta.camera].filter(Boolean).join(' · ') || 'Photo',
kind: 'photo',
thumb: photo.thumbUrl ?? photo.thumb,
run: () => onOpenPhoto(photo.id),
}));
return [...actionsFound, ...eventsFound, ...photosFound];
}, [actions, eventNames, events, onOpenEvent, onOpenPhoto, photos, query]);
useEffect(() => {
const item = listRef.current?.querySelector<HTMLElement>(`[data-index="${active}"]`);
item?.scrollIntoView({ block: 'nearest' });
}, [active]);
const choose = (result: Result | undefined) => {
if (!result) return;
result.run();
onClose();
};
return (
<div className="modal-backdrop command-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="command-palette" role="dialog" aria-modal="true" aria-label="Search Luminary">
<div className="command-input-row">
<span className="command-icon" aria-hidden="true">⌕</span>
<input
ref={inputRef}
value={query}
placeholder="Search photos, events, and actions…"
aria-label="Search photos, events, and actions"
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.preventDefault();
onClose();
} else if (e.key === 'ArrowDown') {
e.preventDefault();
setActive((index) => Math.min(results.length - 1, index + 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActive((index) => Math.max(0, index - 1));
} else if (e.key === 'Enter') {
e.preventDefault();
choose(results[active]);
}
}}
/>
<kbd>esc</kbd>
</div>
<div className="command-results" ref={listRef}>
{results.length ? (
results.map((result, index) => (
<button
key={result.key}
type="button"
data-index={index}
className={`command-result ${index === active ? 'active' : ''}`}
onMouseEnter={() => setActive(index)}
onClick={() => choose(result)}
>
{result.kind === 'photo' && result.thumb ? (
<img src={result.thumb} alt="" className="command-thumb" />
) : (
<span className={`command-kind ${result.kind}`}>
{result.kind === 'action' ? '⌘' : result.kind === 'event' ? '▤' : '▧'}
</span>
)}
<span className="command-result-main">
<strong>{result.label}</strong>
<small>{result.hint}</small>
</span>
<span className="command-result-kind">{result.kind}</span>
</button>
))
) : (
<div className="command-empty">No matches for “{query.trim()}”.</div>
)}
</div>
<div className="command-foot">
<span>↑↓ navigate</span>
<span>↵ open</span>
<span>esc close</span>
</div>
</div>
</div>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { useEffect, useRef, useState } from 'react';
import { getBitmap } from '../lib/images';
import { rotatedBounds, Renderer } from '../gl/renderer';
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
import type { PhotoRecord } from '../types';
interface Props {
photos: PhotoRecord[];
onClose: () => void;
onOpen: (id: string) => void;
}
function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: string) => void }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [box, setBox] = useState({ w: 0, h: 0 });
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
getBitmap(photo)
.then((next) => alive && setBitmap(next))
.catch((err) => alive && setError(err instanceof Error ? err.message : 'Could not load the photo'));
return () => {
alive = false;
};
}, [photo]);
useEffect(() => {
let alive = true;
if (!photo.edits.lens || !bitmap) {
setLensCorrection(null);
return;
}
buildLensCorrection(photo.edits.lens, {
width: bitmap.width,
height: bitmap.height,
meta: photo.meta,
})
.then((correction) => alive && setLensCorrection(correction))
.catch(() => alive && setLensCorrection(null));
return () => {
alive = false;
};
}, [bitmap, photo.edits.lens, photo.meta]);
useEffect(() => {
const el = boxRef.current;
if (!el) return;
const measure = () => setBox({ w: el.clientWidth, h: el.clientHeight });
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, []);
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 renderer = rendererRef.current;
const canvas = canvasRef.current;
if (!renderer || !canvas || !bitmap || box.w < 30 || box.h < 30) return;
// Wait for the layout pass, then draw in a frame callback: uploading the
// source while the tile is still being measured can lose the first frame.
const raf = requestAnimationFrame(() => {
const frame = rotatedBounds(bitmap.width, bitmap.height, photo.edits.crop.angle, photo.edits.crop.quarter);
const aspect = (frame.w * photo.edits.crop.w) / Math.max(1, frame.h * photo.edits.crop.h);
let cssW = box.w;
let cssH = cssW / aspect;
if (cssH > box.h) {
cssH = box.h;
cssW = cssH * aspect;
}
cssW = Math.max(20, Math.round(cssW));
cssH = Math.max(20, Math.round(cssH));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cap = Math.min(1, 2200 / Math.max(cssW * dpr, cssH * dpr));
const opts = {
width: Math.max(1, Math.round(cssW * dpr * cap)),
height: Math.max(1, Math.round(cssH * dpr * cap)),
lens: lensCorrection,
};
try {
renderer.setImage(bitmap);
renderer.render(photo.edits, opts);
} catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed');
}
});
return () => cancelAnimationFrame(raf);
}, [bitmap, box, photo, lensCorrection]);
return (
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
<div className="compare-canvas" ref={boxRef}>
{error ? <div className="banner error">{error}</div> : <canvas ref={canvasRef} />}
</div>
<figcaption>
<span className="compare-name" title={photo.name}>
{photo.name}
</span>
<span className="compare-stars">{photo.rating ? '★'.repeat(photo.rating) : '—'}</span>
<button className="btn ghost small" onClick={() => onOpen(photo.id)}>
Develop
</button>
</figcaption>
</figure>
);
}
/** Side-by-side survey of 2–4 selected frames. */
export default function CompareView({ photos, onClose, onOpen }: Props) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopImmediatePropagation();
onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose]);
return (
<div className="compare-page" role="dialog" aria-label="Compare photos">
<header className="compare-head">
<div>
<strong>Compare</strong>
<span className="muted small">
{' '}
· {photos.length} photo{photos.length === 1 ? '' : 's'} · double-click a frame to edit
</span>
</div>
<button className="btn ghost" onClick={onClose}>
Close
</button>
</header>
<div className={`compare-grid count-${photos.length}`}>
{photos.map((photo) => (
<CompareTile key={photo.id} photo={photo} onOpen={onOpen} />
))}
</div>
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
export interface MenuAction {
label: string;
shortcut?: string;
onSelect: () => void;
disabled?: boolean;
danger?: boolean;
}
export type MenuEntry = MenuAction | 'separator';
interface Props {
x: number;
y: number;
entries: MenuEntry[];
header?: ReactNode;
onClose: () => void;
}
/**
* Right-click menu anchored to the pointer. Rendered in a portal so the app's
* scroll containers and panel overflow cannot clip it, and nudged inside the
* window when the cursor is close to an edge.
*/
export default function ContextMenu({ x, y, entries, header, onClose }: Props) {
const ref = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const margin = 8;
setPos({
left: Math.max(margin, Math.min(x, window.innerWidth - rect.width - margin)),
top: Math.max(margin, Math.min(y, window.innerHeight - rect.height - margin)),
});
}, [x, y]);
useEffect(() => {
const onPointerDown = (e: PointerEvent) => {
if (ref.current && e.target instanceof Node && ref.current.contains(e.target)) return;
onClose();
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
onClose();
};
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('resize', onClose);
window.addEventListener('blur', onClose);
window.addEventListener('wheel', onClose, { passive: true });
return () => {
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('keydown', onKeyDown, true);
window.removeEventListener('resize', onClose);
window.removeEventListener('blur', onClose);
window.removeEventListener('wheel', onClose);
};
}, [onClose]);
return createPortal(
<div
ref={ref}
className="ctx-menu"
role="menu"
style={{ left: pos?.left ?? x, top: pos?.top ?? y, visibility: pos ? 'visible' : 'hidden' }}
onContextMenu={(e) => e.preventDefault()}
>
{header && <div className="ctx-header">{header}</div>}
{entries.map((entry, i) =>
entry === 'separator' ? (
<div className="ctx-sep" key={`sep-${i}`} />
) : (
<button
key={`${entry.label}-${i}`}
type="button"
role="menuitem"
className={`ctx-item ${entry.danger ? 'danger' : ''}`}
disabled={entry.disabled}
onClick={() => {
onClose();
entry.onSelect();
}}
>
<span>{entry.label}</span>
{entry.shortcut && <span className="ctx-key">{entry.shortcut}</span>}
</button>
),
)}
</div>,
document.body,
);
}
+268
View File
@@ -0,0 +1,268 @@
import { useEffect, useRef, useState, type PointerEvent } from 'react';
import { clamp } from '../lib/curves';
import { grainSampleWindow, Renderer } from '../gl/renderer';
import type { CropState, Edits } from '../types';
type Mode = 'move' | 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
/**
* Point (frame uv) the loupe sits on when dragged to `u`,`v` inside the crop
* rectangle, kept a half-box away from its edges so the patch stays inside.
*/
export function clampLoupe(
crop: { x: number; y: number; w: number; h: number },
u: number,
v: number,
halfU: number,
halfV: number,
) {
const cx = Math.min(1 - halfU, Math.max(halfU, Math.min(1, Math.max(0, u))));
const cy = Math.min(1 - halfV, Math.max(halfV, Math.min(1, Math.max(0, v))));
return { x: crop.x + cx * crop.w, y: crop.y + cy * crop.h };
}
interface Props {
crop: CropState;
frame: { w: number; h: number };
ratio: number | null;
bitmap: ImageBitmap | null;
edits: Edits;
onChange: (rect: Partial<CropState>) => void;
/** lets the preview hold the grain still while a handle is moving */
onDragChange?: (busy: boolean) => void;
}
const MIN = 0.04;
function clampRect(r: CropState): CropState {
let w = clamp(r.w, MIN, 1);
let h = clamp(r.h, MIN, 1);
const x = clamp(r.x, 0, 1 - w);
const y = clamp(r.y, 0, 1 - h);
return { ...r, x, y, w, h };
}
function applyDrag(
start: CropState,
mode: Mode,
dx: number,
dy: number,
ratio: number | null,
frame: { w: number; h: number },
): Partial<CropState> {
let { x, y, w, h } = start;
if (mode === 'move') {
x = clamp(x + dx, 0, 1 - w);
y = clamp(y + dy, 0, 1 - h);
return { x, y };
}
if (mode.includes('e')) w = clamp(w + dx, MIN, 1 - x);
if (mode.includes('s')) h = clamp(h + dy, MIN, 1 - y);
if (mode.includes('w')) {
const nx = clamp(x + dx, 0, x + w - MIN);
w += x - nx;
x = nx;
}
if (mode.includes('n')) {
const ny = clamp(y + dy, 0, y + h - MIN);
h += y - ny;
y = ny;
}
if (ratio) {
const frameRatio = frame.w / frame.h;
const dragsWidth = mode.includes('e') || mode.includes('w');
if (dragsWidth) {
const targetH = (w * frameRatio) / ratio;
if (mode.includes('n')) y = y + h - targetH;
h = targetH;
} else if (mode.includes('n') || mode.includes('s')) {
const targetW = (h * ratio) / frameRatio;
x += (w - targetW) / 2;
w = targetW;
}
if (w > 1) {
const k = 1 / w;
w *= k;
h *= k;
}
if (h > 1) {
const k = 1 / h;
w *= k;
h *= k;
}
if (mode.includes('w')) x = start.x + start.w - w;
if (mode.includes('n')) y = start.y + start.h - h;
x = clamp(x, 0, 1 - w);
y = clamp(y, 0, 1 - h);
}
return clampRect({ ...start, x, y, w, h });
}
export default function CropOverlay({ crop, frame, ratio, bitmap, edits, onChange, onDragChange }: Props) {
const ref = useRef<HTMLDivElement>(null);
const start = useRef<{ mode: Mode; x: number; y: number; rect: CropState } | null>(null);
const [dragging, setDragging] = useState(false);
const loupe = useRef<HTMLCanvasElement>(null);
const loupeRenderer = useRef<Renderer | null>(null);
/** where the patch is sampling, in frame uv; null = centre of the rectangle */
const [loupePoint, setLoupePoint] = useState<{ x: number; y: number } | null>(null);
/** pointer offset from the patch centre while it is being dragged */
const grab = useRef<{ x: number; y: number } | null>(null);
useEffect(
() => () => {
loupeRenderer.current?.dispose();
loupeRenderer.current = null;
},
[],
);
// A live 1:1 grain patch inside the crop rectangle: it samples whatever area the
// rectangle frames, so the rectangle can be judged as it is dragged.
useEffect(() => {
const canvas = loupe.current;
if (!canvas || !bitmap) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cssW = 120;
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const cssH = Math.round(Math.min(96, Math.max(48, cssW * (cropPxH / cropPxW))));
const W = Math.max(1, Math.round(cssW * dpr));
const H = Math.max(1, Math.round(cssH * dpr));
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
if (canvas.width !== W) canvas.width = W;
if (canvas.height !== H) canvas.height = H;
try {
if (!loupeRenderer.current) loupeRenderer.current = new Renderer(canvas);
const r = loupeRenderer.current;
r.setImage(bitmap);
const view = grainSampleWindow(frame, crop, W, H, loupePoint);
r.render({ ...edits, crop }, { width: W, height: H, view });
} catch {
// The overlay still works if the engine cannot start a second context.
}
}, [bitmap, crop, edits, frame, loupePoint]);
const dpr = Math.min(typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1, 2);
const loupeCssW = 120;
const cropPxW = Math.max(1, frame.w * crop.w);
const cropPxH = Math.max(1, frame.h * crop.h);
const loupeCssH = Math.round(Math.min(96, Math.max(48, loupeCssW * (cropPxH / cropPxW))));
const loupeW = Math.max(1, Math.round(loupeCssW * dpr));
const loupeH = Math.max(1, Math.round(loupeCssH * dpr));
const view = grainSampleWindow(frame, crop, loupeW, loupeH, loupePoint);
const fits = crop.w > 0.16 && crop.h > 0.16;
const loupeAt = {
left: `${((view.x + view.w / 2 - crop.x) / crop.w) * 100}%`,
top: `${((view.y + view.h / 2 - crop.y) / crop.h) * 100}%`,
width: `${loupeCssW}px`,
height: `${loupeCssH}px`,
transform: 'translate(-50%, -50%)',
display: fits && bitmap ? 'block' : 'none',
};
const startLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
e.preventDefault();
e.stopPropagation();
e.currentTarget.setPointerCapture(e.pointerId);
const box = e.currentTarget.parentElement?.getBoundingClientRect();
if (!box || !box.width || !box.height) return;
const cx = box.left + ((view.x + view.w / 2 - crop.x) / crop.w) * box.width;
const cy = box.top + ((view.y + view.h / 2 - crop.y) / crop.h) * box.height;
grab.current = { x: e.clientX - cx, y: e.clientY - cy };
};
const moveLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
const g = grab.current;
if (!g) return;
const box = e.currentTarget.parentElement?.getBoundingClientRect();
if (!box || !box.width || !box.height) return;
const halfU = Math.min(0.5, loupeCssW / 2 / box.width);
const halfV = Math.min(0.5, loupeCssH / 2 / box.height);
setLoupePoint(
clampLoupe(
crop,
(e.clientX - g.x - box.left) / box.width,
(e.clientY - g.y - box.top) / box.height,
halfU,
halfV,
),
);
};
const endLoupe = () => {
grab.current = null;
};
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
const el = e.target as HTMLElement;
const mode = (el.dataset.mode ?? 'move') as Mode;
e.preventDefault();
e.stopPropagation();
ref.current?.setPointerCapture(e.pointerId);
start.current = { mode, x: e.clientX, y: e.clientY, rect: { ...crop } };
setDragging(true);
onDragChange?.(true);
};
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const s = start.current;
const el = ref.current;
if (!s || !el) return;
const rect = el.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dx = (e.clientX - s.x) / rect.width;
const dy = (e.clientY - s.y) / rect.height;
onChange(applyDrag(s.rect, s.mode, dx, dy, ratio, frame));
};
const end = (e: React.PointerEvent<HTMLDivElement>) => {
if (ref.current?.hasPointerCapture(e.pointerId)) ref.current.releasePointerCapture(e.pointerId);
start.current = null;
setDragging(false);
onDragChange?.(false);
};
const style = {
left: `${crop.x * 100}%`,
top: `${crop.y * 100}%`,
width: `${crop.w * 100}%`,
height: `${crop.h * 100}%`,
};
return (
<div
ref={ref}
className={`crop-overlay ${dragging ? 'dragging' : ''}`}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={end}
onPointerCancel={end}
>
<div className="crop-rect" style={style}>
<div className="crop-grid" data-mode="move" />
{(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as Mode[]).map((m) => (
<span key={m} className={`handle ${m}`} data-mode={m} />
))}
<canvas
ref={loupe}
className="crop-loupe"
style={loupeAt}
title="Grain at 100% · drag to sample any point in the crop"
onPointerDown={startLoupe}
onPointerMove={moveLoupe}
onPointerUp={endLoupe}
onPointerCancel={endLoupe}
/>
<span className="crop-size">
{Math.round(crop.w * 100)}% × {Math.round(crop.h * 100)}%
</span>
</div>
</div>
);
}
+122
View File
@@ -0,0 +1,122 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { buildSampler, clamp01 } from '../lib/curves';
import type { CurvePoint } from '../types';
interface Props {
points: CurvePoint[];
onChange: (points: CurvePoint[]) => void;
color: string;
}
export default function CurveEditor({ points, onChange, color }: Props) {
const svgRef = useRef<SVGSVGElement>(null);
const pointsRef = useRef(points);
const [drag, setDrag] = useState<number | null>(null);
const [hover, setHover] = useState<number | null>(null);
useEffect(() => {
pointsRef.current = points;
}, [points]);
const sampler = useMemo(() => buildSampler(points), [points]);
const path = useMemo(() => {
const segs: string[] = [];
for (let i = 0; i <= 80; i++) {
const x = i / 80;
const y = sampler(x);
segs.push(`${i === 0 ? 'M' : 'L'}${(x * 100).toFixed(2)},${((1 - y) * 100).toFixed(2)}`);
}
return segs.join(' ');
}, [sampler]);
const toNorm = useCallback((clientX: number, clientY: number) => {
const svg = svgRef.current;
if (!svg) return { x: 0, y: 0 };
const rect = svg.getBoundingClientRect();
return {
x: clamp01((clientX - rect.left) / rect.width),
y: clamp01(1 - (clientY - rect.top) / rect.height),
};
}, []);
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
e.preventDefault();
const idxAttr = (e.target as Element).getAttribute('data-idx');
let idx: number;
if (idxAttr !== null) {
idx = Number(idxAttr);
} else {
const p = toNorm(e.clientX, e.clientY);
const next = [...points, { x: p.x, y: p.y }].sort((a, b) => a.x - b.x);
idx = next.findIndex((pt) => pt.x === p.x && pt.y === p.y);
onChange(next);
}
setDrag(idx);
e.currentTarget.setPointerCapture(e.pointerId);
};
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
if (drag === null) return;
const pts = pointsRef.current;
const idx = drag;
if (!pts[idx]) return;
const p = toNorm(e.clientX, e.clientY);
const lo = idx > 0 ? pts[idx - 1].x + 0.01 : 0;
const hi = idx < pts.length - 1 ? pts[idx + 1].x - 0.01 : 1;
const next = pts.map((pt, i) => (i === idx ? { x: Math.min(hi, Math.max(lo, p.x)), y: p.y } : pt));
onChange(next);
};
const handleUp = () => setDrag(null);
const removePoint = (idx: number) => {
const pts = pointsRef.current;
if (pts.length <= 2) return;
onChange(pts.filter((_, i) => i !== idx));
setDrag(null);
};
return (
<div className="curve-wrap">
<svg
ref={svgRef}
className="curve"
viewBox="0 0 100 100"
preserveAspectRatio="none"
onPointerDown={handleDown}
onPointerMove={handleMove}
onPointerUp={handleUp}
onPointerCancel={handleUp}
onDoubleClick={(e) => {
const idxAttr = (e.target as Element).getAttribute('data-idx');
if (idxAttr !== null) removePoint(Number(idxAttr));
}}
>
<rect x="0" y="0" width="100" height="100" className="curve-bg" />
{[25, 50, 75].map((v) => (
<g key={v}>
<line x1={v} y1="0" x2={v} y2="100" className="curve-grid" />
<line x1="0" y1={v} x2="100" y2={v} className="curve-grid" />
</g>
))}
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
{points.map((p, i) => (
<circle
key={`${i}-${p.x.toFixed(3)}`}
data-idx={i}
cx={p.x * 100}
cy={(1 - p.y) * 100}
r={hover === i || drag === i ? 3 : 2.1}
className="curve-point"
fill={color}
onPointerEnter={() => setHover(i)}
onPointerLeave={() => setHover((h) => (h === i ? null : h))}
/>
))}
</svg>
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
</div>
);
}
File diff suppressed because it is too large Load Diff
+263
View File
@@ -0,0 +1,263 @@
import { useState } from 'react';
import {
draggedEventId,
draggedPhotoIds,
endDrag,
EVENT_DRAG,
PHOTO_DRAG,
startEventDrag,
startPhotoDrag,
} from '../lib/drag';
import type { EventRecord, PhotoRecord, SmartCollection } from '../types';
interface Props {
collapsed?: boolean;
mobileOpen?: boolean;
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;
trashOpen: boolean;
trashCount: number;
onOpenTrash: () => void;
storageNote: string;
collections: SmartCollection[];
activeCollectionId: string | null;
onSelectCollection: (id: string) => void;
onDeleteCollection: (id: string) => void;
}
export default function EventSidebar({
collapsed = false,
mobileOpen = false,
events,
photos,
eventId,
onSelectEvent,
onCreate,
onRename,
onDelete,
onReorderEvents,
onDropPhotos,
trashOpen,
trashCount,
onOpenTrash,
storageNote,
collections,
activeCollectionId,
onSelectCollection,
onDeleteCollection,
}: 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
id="library-sidebar"
className={`sidebar ${collapsed ? 'collapsed' : ''} ${mobileOpen ? 'mobile-open' : ''}`}
aria-hidden={collapsed && !mobileOpen}
>
<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>
)}
<button
className={`event-item all ${trashOpen ? 'active' : ''}`}
onClick={onOpenTrash}
title="Deleted photos stay here until you empty the trash"
>
<span className="event-name">Trash</span>
<span className="event-count">{trashCount}</span>
</button>
</div>
{collections.length > 0 && (
<>
<div className="sidebar-head sub">
<span>Collections</span>
<span className="muted small">{collections.length}</span>
</div>
<div className="collection-list">
{collections.map((collection) => (
<div
key={collection.id}
className={`event-item collection ${activeCollectionId === collection.id ? 'active' : ''}`}
>
<button className="event-main" onClick={() => onSelectCollection(collection.id)} title="Apply saved view">
<span className="event-name">{collection.name}</span>
<span className="collection-icon">◇</span>
</button>
<div className="event-tools">
<button
className="icon-btn danger"
title="Delete collection"
onClick={() => onDeleteCollection(collection.id)}
>
🗑
</button>
</div>
</div>
))}
</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>
);
}
+569
View File
@@ -0,0 +1,569 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ExportOptions, ExportFormat, ExportRecipe, ResizeMode, WatermarkPosition } from '../lib/export';
import { buildFileName, DEFAULT_EXPORT, exportPhotos } from '../lib/export';
import Slider from './Slider';
import { getBitmap } from '../lib/images';
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
import type { PhotoRecord } from '../types';
interface Props {
photos: PhotoRecord[];
initial: ExportOptions;
recipes: ExportRecipe[];
onSaveRecipe: (name: string, options: ExportOptions) => void;
onDeleteRecipe: (id: string) => void;
onClose: () => void;
onDone: (message: string, options: ExportOptions) => void;
}
const FORMATS: { value: ExportFormat; label: string }[] = [
{ value: 'jpeg', label: 'JPEG' },
{ value: 'png', label: 'PNG (8-bit)' },
{ value: 'webp', label: 'WebP' },
{ value: 'tiff16', label: 'TIFF (16-bit)' },
];
/**
* 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, recipes, onSaveRecipe, onDeleteRecipe, onClose, onDone }: Props) {
const [opts, setOpts] = useState<ExportOptions>({ ...DEFAULT_EXPORT, ...initial });
const [recipeId, setRecipeId] = useState('');
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState({ done: 0, total: 0 });
const [stage, setStage] = useState<'render' | 'pack'>('render');
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 patchWatermark = (p: Partial<ExportOptions['watermark']>) =>
setOpts((prev) => ({ ...prev, watermark: { ...prev.watermark, ...p } }));
const sample = photos[0];
const previewSize = useMemo(() => {
if (!sample) return null;
// Use the renderer's exact crop/rotation calculation, not a rectangle-only
// estimate: straightening expands the frame and changes both dimensions.
const base = outputSize(sample.edits, sample.width || 1, sample.height || 1);
let k = 1;
if (opts.resize === 'longEdge' && opts.longEdge > 0 && Math.max(base.w, base.h) > opts.longEdge) {
k = opts.longEdge / Math.max(base.w, base.h);
} else if (opts.resize === 'percent') {
k = Math.min(2, Math.max(0.05, opts.percent / 100));
}
return { w: Math.max(1, Math.round(base.w * k)), h: Math.max(1, Math.round(base.h * k)) };
}, [sample, opts.resize, opts.longEdge, opts.percent]);
const sampleName = sample
? buildFileName(opts.nameTemplate, sample, 0, opts)
: `export.${opts.format === 'jpeg' ? 'jpg' : opts.format === 'tiff16' ? 'tif' : opts.format}`;
const run = async () => {
if (!photos.length || busy) return;
setBusy(true);
setError(null);
setStage('render');
try {
const { count, failed } = await exportPhotos(
photos,
opts,
(done, total) => setProgress({ done, total }),
setStage,
);
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) => {
const format = e.target.value as ExportFormat;
patch({
format,
// Watermarking needs an 8-bit canvas pass; keep the option off
// rather than silently downgrading the 16-bit file.
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
});
}}
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>
)}
{photos.length > 1 && (
<label className="field">
<span>Delivery</span>
<select
value={opts.zip ? 'zip' : 'files'}
onChange={(e) => patch({ zip: e.target.value === 'zip' })}
disabled={busy}
>
<option value="zip">One ZIP file</option>
<option value="files">Separate files</option>
</select>
</label>
)}
</div>
{(opts.format === 'jpeg' || opts.format === 'webp') && (
<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>
<div className="export-recipes">
<label className="field">
<span>Recipe</span>
<select
value={recipeId}
onChange={(e) => {
const id = e.target.value;
setRecipeId(id);
const recipe = recipes.find((item) => item.id === id);
if (recipe) setOpts({ ...DEFAULT_EXPORT, ...recipe.options });
}}
disabled={busy || !recipes.length}
>
<option value="">Custom settings</option>
{recipes.map((recipe) => (
<option key={recipe.id} value={recipe.id}>
{recipe.name}
</option>
))}
</select>
</label>
<button
className="btn ghost small"
onClick={() => {
const name = window.prompt('Export recipe name', 'Client delivery');
if (name?.trim()) {
onSaveRecipe(name.trim(), opts);
setRecipeId('');
}
}}
disabled={busy}
>
Save recipe
</button>
{recipeId && (
<button
className="icon-btn danger"
title="Delete recipe"
onClick={() => {
onDeleteRecipe(recipeId);
setRecipeId('');
}}
>
🗑
</button>
)}
</div>
<div className="subhead">
<span>Output</span>
</div>
<Slider
label="Output sharpening"
min={0}
max={80}
value={opts.outputSharpen}
onChange={(v) => patch({ outputSharpen: v })}
format={(v) => `${Math.round(v)}`}
def={0}
/>
<label className="check-row">
<input
type="checkbox"
checked={opts.metadata}
onChange={(e) => patch({ metadata: e.target.checked })}
disabled={opts.format !== 'jpeg'}
/>
Embed title, caption, creator, copyright and keywords (JPEG)
</label>
<label className="check-row">
<input
type="checkbox"
checked={opts.embedProfile}
onChange={(e) => patch({ embedProfile: e.target.checked })}
disabled={opts.format === 'webp' || opts.format === 'png'}
/>
Embed sRGB profile (JPEG/TIFF)
</label>
<div className="subhead">
<span>Watermark</span>
<button
className={`chip tiny ${opts.watermark.enabled ? 'on' : ''}`}
disabled={opts.format === 'tiff16'}
onClick={() => patchWatermark({ enabled: !opts.watermark.enabled })}
>
{opts.watermark.enabled ? 'On' : 'Off'}
</button>
</div>
{opts.format === 'tiff16' && (
<p className="muted small">
16-bit TIFF is a delivery master; watermarking and JPEG metadata are not applied.
</p>
)}
{opts.watermark.enabled && (
<>
<label className="field">
<span>Text</span>
<input
value={opts.watermark.text}
onChange={(e) => patchWatermark({ text: e.target.value })}
placeholder="© Your studio"
disabled={busy}
/>
</label>
<div className="field-row">
<label className="field">
<span>Position</span>
<select
value={opts.watermark.position}
onChange={(e) => patchWatermark({ position: e.target.value as WatermarkPosition })}
disabled={busy}
>
<option value="br">Bottom right</option>
<option value="bl">Bottom left</option>
<option value="tr">Top right</option>
<option value="tl">Top left</option>
<option value="center">Centre</option>
</select>
</label>
<label className="field narrow">
<span>Size</span>
<input
type="number"
min={1}
max={20}
value={opts.watermark.size}
onChange={(e) => patchWatermark({ size: Number(e.target.value) || 1 })}
disabled={busy}
/>
</label>
<label className="field narrow">
<span>Opacity</span>
<input
type="number"
min={5}
max={100}
value={opts.watermark.opacity}
onChange={(e) => patchWatermark({ opacity: Number(e.target.value) || 5 })}
disabled={busy}
/>
</label>
</div>
</>
)}
{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">
{stage === 'pack'
? `Packing ${progress.total} photos into a ZIP…`
: `${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
? stage === 'pack'
? 'Packing ZIP…'
: 'Exporting…'
: opts.zip && photos.length > 1
? `Export ${photos.length} as ZIP`
: `Export ${photos.length}`}
</button>
</footer>
</div>
</div>
);
}
+270
View File
@@ -0,0 +1,270 @@
import { COLOR_LABELS, isEdited } from '../lib/edits';
import { usePersistentState } from '../lib/usePersistentState';
import type { ColorLabel, Filters, Flag, PhotoRecord, SortKey } from '../types';
interface Props {
filters: Filters;
setFilters: (next: Filters) => void;
count: number;
total: number;
/** Photos in the current scope before the filter controls are applied. */
scopePhotos: PhotoRecord[];
reviewCounts: { approved: number; changes: number };
sort: SortKey;
setSort: (s: SortKey) => void;
asc: boolean;
setAsc: (v: boolean) => void;
/** photos in this scope that a client has picked */
proofCount: number;
onSaveCollection: () => void;
}
const FLAGS: { value: Flag | 'any'; label: string }[] = [
{ value: 'any', label: 'Any' },
{ value: 'pick', label: 'Picked' },
{ value: 'none', label: 'Unflagged' },
{ value: 'reject', label: 'Rejected' },
];
const EMPTY_FILTERS: Filters = {
minRating: 0,
flag: 'any',
colors: [],
text: '',
editedOnly: false,
unrated: false,
proofed: false,
clientStatus: 'any',
};
export default function FilterBar({
filters,
setFilters,
count,
total,
scopePhotos,
reviewCounts,
sort,
setSort,
asc,
setAsc,
proofCount,
onSaveCollection,
}: Props) {
const [collapsed, setCollapsed] = usePersistentState('library.filters.collapsed', false);
const patch = (p: Partial<Filters>) => setFilters({ ...filters, ...p });
const countWhere = (test: (photo: PhotoRecord) => boolean) =>
scopePhotos.reduce((sum, photo) => sum + (test(photo) ? 1 : 0), 0);
const ratingCounts = [0, 1, 2, 3, 4, 5].map((n) =>
n === 0 ? scopePhotos.length : countWhere((photo) => photo.rating >= n),
);
const unratedCount = countWhere((photo) => photo.rating === 0);
const flagCounts = FLAGS.map((flag) =>
flag.value === 'any'
? scopePhotos.length
: countWhere((photo) => photo.flag === flag.value),
);
const colorCounts = COLOR_LABELS.map((color) =>
countWhere((photo) => photo.color === color.value),
);
const editedCount = countWhere((photo) => isEdited(photo.edits));
const active =
filters.minRating > 0 ||
filters.flag !== 'any' ||
filters.colors.length > 0 ||
!!filters.text ||
filters.editedOnly ||
filters.unrated ||
filters.proofed ||
filters.clientStatus !== 'any';
const toggleColor = (color: ColorLabel) => {
const exists = filters.colors.includes(color);
patch({ colors: exists ? filters.colors.filter((c) => c !== color) : [...filters.colors, color] });
};
const summary = [
filters.minRating > 0 ? `${filters.minRating}★+` : '',
filters.unrated ? 'Unrated' : '',
filters.flag !== 'any' ? FLAGS.find((f) => f.value === filters.flag)?.label ?? '' : '',
filters.colors.length ? `${filters.colors.length} label${filters.colors.length === 1 ? '' : 's'}` : '',
filters.text ? `“${filters.text}”` : '',
filters.editedOnly ? 'Edited' : '',
filters.proofed ? 'Client picks' : '',
filters.clientStatus === 'approved' ? 'Approved' : filters.clientStatus === 'changes' ? 'Changes' : '',
]
.filter(Boolean)
.join(' · ');
return (
<div className={`filterbar ${collapsed ? 'collapsed' : ''}`}>
<button
className="filter-collapse"
onClick={() => setCollapsed((open) => !open)}
aria-expanded={!collapsed}
title={collapsed ? 'Expand filters' : 'Collapse filters'}
>
<span className="chev">{collapsed ? '▸' : '▾'}</span>
<span>Filters</span>
</button>
{collapsed ? (
<>
<span className={`filter-summary ${active ? '' : 'muted'}`}>
{active ? summary : 'No filters applied'}
</span>
{active && (
<button className="chip ghost" onClick={() => setFilters(EMPTY_FILTERS)}>
Clear
</button>
)}
</>
) : (
<>
<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`} · ${ratingCounts[n]} photo${ratingCounts[n] === 1 ? '' : 's'}`}
>
{n === 0 ? 'Any' : `${n}★+`}
<span className="chip-count">{ratingCounts[n]}</span>
</button>
))}
<button
className={`chip ${filters.unrated ? 'on' : ''}`}
onClick={() => patch({ unrated: !filters.unrated, minRating: 0 })}
title={`Only photos with no rating · ${unratedCount} photo${unratedCount === 1 ? '' : 's'}`}
>
Unrated
<span className="chip-count">{unratedCount}</span>
</button>
</div>
</div>
<div className="filter-group">
<span className="filter-label">Flag</span>
<div className="rating-filter">
{FLAGS.map((f, index) => (
<button
key={f.value}
className={`chip ${filters.flag === f.value ? 'on' : ''}`}
onClick={() => patch({ flag: f.value })}
title={`${f.label} · ${flagCounts[index]} photo${flagCounts[index] === 1 ? '' : 's'}`}
>
{f.label}
<span className="chip-count">{flagCounts[index]}</span>
</button>
))}
</div>
</div>
<div className="filter-group">
<span className="filter-label">Label</span>
<div className="color-filter">
{COLOR_LABELS.map((c, index) => (
<button
key={c.value}
className={`swatch ${filters.colors.includes(c.value) ? 'on' : ''}`}
style={{ background: c.hex }}
title={`${c.name} · ${colorCounts[index]} photo${colorCounts[index] === 1 ? '' : 's'}`}
aria-label={`${c.name} label, ${colorCounts[index]} photos`}
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 · ${editedCount}`}
>
Edited
<span className="chip-count">{editedCount}</span>
</button>
{proofCount > 0 && (
<button
className={`chip proof-chip ${filters.proofed ? 'on' : ''}`}
onClick={() => patch({ proofed: !filters.proofed })}
title="Only show photos a client picked in the proofing gallery"
>
♥ Client picks {proofCount}
</button>
)}
<div className="filter-group">
<span className="filter-label">Review</span>
<div className="rating-filter">
<button
className={`chip ${filters.clientStatus === 'approved' ? 'on' : ''}`}
onClick={() => patch({ clientStatus: filters.clientStatus === 'approved' ? 'any' : 'approved' })}
title={`Photos a client approved in the proofing gallery · ${reviewCounts.approved}`}
>
Approved
<span className="chip-count">{reviewCounts.approved}</span>
</button>
<button
className={`chip ${filters.clientStatus === 'changes' ? 'on' : ''}`}
onClick={() => patch({ clientStatus: filters.clientStatus === 'changes' ? 'any' : 'changes' })}
title={`Photos a client marked for changes · ${reviewCounts.changes}`}
>
Changes
<span className="chip-count">{reviewCounts.changes}</span>
</button>
</div>
</div>
<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>
<button className="chip ghost" onClick={onSaveCollection} title="Save the current filters and sort as a smart collection">
Save view
</button>
{active && (
<button className="chip ghost" onClick={() => setFilters(EMPTY_FILTERS)}>
Clear filters
</button>
)}
</>
)}
<div className="filter-count">
{count}
{count !== total ? ` / ${total}` : ''} shown
</div>
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { useEffect, useRef } from 'react';
import type { Histogram as HistogramData } from '../gl/renderer';
export default function Histogram({
data,
version,
clipping,
onClipping,
}: {
data: HistogramData | null;
version: number;
clipping?: 'highlights' | 'shadows' | null;
onClipping?: (next: 'highlights' | 'shadows' | null) => void;
}) {
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 (
<div className="histo-box">
<canvas className="histogram" ref={ref} />
<button
className={`clip-tri shadows ${clipping === 'shadows' ? 'on' : ''}`}
title="Show shadow clipping (Shift+J)"
aria-pressed={clipping === 'shadows'}
onClick={() => onClipping?.(clipping === 'shadows' ? null : 'shadows')}
/>
<button
className={`clip-tri highlights ${clipping === 'highlights' ? 'on' : ''}`}
title="Show highlight clipping (J)"
aria-pressed={clipping === 'highlights'}
onClick={() => onClipping?.(clipping === 'highlights' ? null : 'highlights')}
/>
</div>
);
}
+307
View File
@@ -0,0 +1,307 @@
import { useEffect, useMemo, 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[];
/** Records already in the catalog, used to skip accidental re-imports. */
existing: PhotoRecord[];
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,
existing,
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 [allowDuplicates, setAllowDuplicates] = useState(false);
const [summary, setSummary] = useState<{
imported: number;
failed: number;
skipped: number;
cancelled: boolean;
} | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const abortRef = useRef<AbortController | null>(null);
const rawCount = files.filter(isRawFile).length;
const existingKeys = useMemo(
() => new Set(existing.map((photo) => `${photo.name.toLowerCase()}:${photo.size}`)),
[existing],
);
const duplicateFiles = useMemo(
() => files.filter((file) => existingKeys.has(`${file.name.toLowerCase()}:${file.size}`)),
[existingKeys, files],
);
const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file));
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;
setSummary(null);
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 (!readyFiles.length || busy) return;
setBusy(true);
setFailures([]);
setSummary(null);
const controller = new AbortController();
abortRef.current = controller;
try {
let targetId = eventId;
if (targetId === '__new') {
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
targetId = created.id;
}
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal);
if (result.photos.length) onImported(result.photos, targetId);
const skipped = allowDuplicates ? 0 : duplicateFiles.length;
setSummary({
imported: result.photos.length,
failed: result.failed.length,
skipped,
cancelled: Boolean(result.cancelled),
});
if (result.failed.length) setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`));
} catch (err) {
setFailures([err instanceof Error ? err.message : 'Import failed']);
} finally {
setBusy(false);
setProgress(null);
abortRef.current = null;
}
};
const cancel = () => {
abortRef.current?.abort();
setProgress((current) =>
current ? { ...current, current: 'Cancelling after the files already in progress…' } : current,
);
};
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>
{readyFiles.length} file{readyFiles.length === 1 ? '' : 's'} ready ·{' '}
{(readyFiles.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024)).toFixed(1)} MB
{rawCount > 0 ? ` · ${rawCount} raw` : ''}
</span>
<button className="link-btn" onClick={() => { setFiles([]); setSummary(null); }} disabled={busy}>
Clear
</button>
</div>
)}
{duplicateFiles.length > 0 && !summary && (
<div className="banner info import-duplicates">
<div>
<strong>
{duplicateFiles.length} file{duplicateFiles.length === 1 ? ' is' : 's are'} already in the catalog.
</strong>{' '}
{allowDuplicates
? 'They will be imported again as new copies.'
: 'They will be skipped unless you choose to include them.'}
</div>
<button
className="btn ghost small"
onClick={() => setAllowDuplicates((value) => !value)}
disabled={busy}
>
{allowDuplicates ? 'Skip duplicates' : 'Include anyway'}
</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>
)}
{summary && (
<div className="import-summary">
<strong>
{summary.cancelled ? 'Import cancelled' : 'Import complete'}
</strong>
<span>
{summary.imported} imported
{summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''}
{summary.failed ? ` · ${summary.failed} failed` : ''}
</span>
<p className="muted small">
{summary.cancelled
? 'Files already in progress were allowed to finish. The imported photos are in the catalog.'
: 'New photos are selected in the library and ready to review.'}
</p>
</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">
{summary ? (
<button className="btn primary" onClick={onClose}>
Done
</button>
) : (
<>
<button className="btn ghost" onClick={busy ? cancel : onClose}>
{busy ? 'Cancel import' : 'Cancel'}
</button>
<button
className="btn primary"
onClick={() => void run()}
disabled={busy || !readyFiles.length}
>
{busy ? 'Importing…' : `Import ${readyFiles.length || ''}`}
</button>
</>
)}
</footer>
</div>
</div>
);
}
+193
View File
@@ -0,0 +1,193 @@
import { useEffect, useState } from 'react';
import { ApiError, loadInvite, register } from '../lib/api';
import type { InviteInfo } from '../lib/api';
interface Props {
token: string;
}
const fmtDate = (ms: number | null) =>
ms ? new Date(ms).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '';
const STATUS_COPY: Record<string, { title: string; body: string }> = {
accepted: {
title: 'This invite has already been used',
body: 'Each invite link works once. Sign in if the account is yours, or ask an admin for a fresh link.',
},
expired: {
title: 'This invite has expired',
body: 'Invite links are time-limited. Ask an admin to send you a new one.',
},
revoked: {
title: 'This invite was turned off',
body: 'An admin revoked this link. Ask them for a new invite if you still need access.',
},
};
/** Public signup screen reached from an admin's single-use invite link. */
export default function JoinPage({ token }: Props) {
const [invite, setInvite] = useState<InviteInfo | null>(null);
const [missing, setMissing] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [password, setPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
loadInvite(token)
.then((next) => {
if (!alive) return;
setInvite(next);
setEmail(next.email);
})
.catch((err) => {
if (!alive) return;
if (err instanceof ApiError && err.status === 404) setMissing(true);
else setLoadError(err instanceof Error ? err.message : 'Could not check this invite');
});
return () => {
alive = false;
};
}, [token]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!invite || invite.status !== 'pending' || busy) return;
if (password.length < 8) {
setError('Use at least 8 characters for the password');
return;
}
setBusy(true);
setError(null);
try {
await register({
email: email.trim(),
password,
name: name.trim(),
inviteToken: token,
});
window.location.assign('/');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the account');
setBusy(false);
}
};
const state = missing ? 'missing' : invite?.status;
const lockedEmail = Boolean(invite?.email);
const copy =
state === 'missing'
? {
title: 'This invite link is not valid',
body: 'Check the link you were sent, or ask an admin for a new invite.',
}
: state && STATUS_COPY[state]
? STATUS_COPY[state]
: null;
return (
<div className="join-page">
<div className="join-brand">
<span className="brand-dot" />
LUMINARY
</div>
<main className="join-card">
{!invite && !missing && !loadError && <p className="muted small">Checking your invite…</p>}
{loadError && (
<>
<span className="join-eyebrow">Invite</span>
<h1>Can’t reach the server</h1>
<p className="muted">{loadError}</p>
<a className="btn ghost wide" href="/">
Go to Luminary
</a>
</>
)}
{copy && (
<>
<span className="join-eyebrow">Invite</span>
<h1>{copy.title}</h1>
<p className="muted">{copy.body}</p>
<a className="btn primary wide" href="/">
Go to sign in
</a>
</>
)}
{invite?.status === 'pending' && (
<>
<span className="join-eyebrow">You’re invited</span>
<h1>Join the studio</h1>
<p className="muted join-lead">
{lockedEmail
? `Create your account for ${invite.email}. This link works once.`
: 'Create your account to start editing, proofing and sharing photos. This link works once.'}
</p>
<form className="join-form" onSubmit={submit}>
<label className="field">
<span>Email</span>
<input
type="email"
required
autoComplete="username"
autoFocus={!lockedEmail}
readOnly={lockedEmail}
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@studio.com"
/>
</label>
<label className="field">
<span>Display name</span>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Optional"
autoComplete="name"
/>
</label>
<label className="field">
<span>Password</span>
<input
type="password"
required
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="At least 8 characters"
/>
</label>
{error && <div className="banner error">{error}</div>}
<button
className="btn primary wide"
type="submit"
disabled={busy || !email.trim() || password.length < 8}
>
{busy ? 'Creating account…' : 'Create account'}
</button>
</form>
<p className="join-meta">
You’ll join as a {invite.role === 'admin' ? 'administrator' : 'member'}
{invite.expiresAt ? ` · link expires ${fmtDate(invite.expiresAt)}` : ''}
</p>
<p className="join-foot">
Already have an account? <a href="/">Sign in</a>
</p>
</>
)}
</main>
</div>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { useEffect, useState } from 'react';
import {
loadCameraLensDefaults,
removeCameraLensDefault,
type CameraLensDefault,
} from '../lib/lensDefaults';
interface Props {
onClose: () => void;
/** Called after a saved row is removed so an open Optics panel can refresh. */
onChanged?: () => void;
}
const correctionLabel = (entry: CameraLensDefault) => {
const corrections = entry.profile.corrections;
const enabled = [
corrections.distortion ? 'distortion' : '',
corrections.tca ? 'chromatic aberration' : '',
corrections.vignetting ? 'vignetting' : '',
].filter(Boolean);
return enabled.length ? enabled.join(' · ') : 'no corrections enabled';
};
export default function LensDefaultsModal({ onClose, onChanged }: Props) {
const [defaults, setDefaults] = useState<CameraLensDefault[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
loadCameraLensDefaults()
.then((saved) => alive && setDefaults(saved))
.catch((err) => {
if (!alive) return;
setDefaults([]);
setError(err instanceof Error ? err.message : 'Could not load saved defaults');
});
return () => {
alive = false;
};
}, []);
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 remove = async (entry: CameraLensDefault) => {
const key = `${entry.camera}\u0000${entry.exifLens}`;
if (busy) return;
setBusy(key);
setError(null);
try {
await removeCameraLensDefault({ camera: entry.camera, lens: entry.exifLens });
setDefaults((current) =>
current?.filter(
(saved) => saved.camera !== entry.camera || saved.exifLens !== entry.exifLens,
) ?? [],
);
onChanged?.();
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not remove that default');
} finally {
setBusy(null);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal lens-defaults-modal">
<header className="modal-head">
<div>
<span className="settings-kicker">Settings</span>
<h2>Camera lens defaults</h2>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
✕
</button>
</header>
<div className="modal-body">
<p className="muted small lens-defaults-lead">
These profiles apply automatically on this browser when a new import has the same camera
and EXIF lens. Removing one only affects future imports.
</p>
{defaults === null ? (
<p className="muted small">Loading saved defaults…</p>
) : defaults.length === 0 ? (
<div className="lens-defaults-empty">
<strong>No camera-lens defaults saved</strong>
<p className="muted small">
Open the Optics panel in Develop, choose a lens profile, then use “Set as camera
default”.
</p>
</div>
) : (
<div className="lens-defaults-list">
{defaults.map((entry) => {
const key = `${entry.camera}\u0000${entry.exifLens}`;
return (
<article className="lens-default-item" key={key}>
<div className="lens-default-main">
<div className="lens-default-title">
<strong>
{entry.profile.maker} {entry.profile.model}
</strong>
<span className="muted small">crop {entry.profile.crop}×</span>
</div>
<p className="lens-default-match">
{entry.camera} <span className="muted">+</span> {entry.exifLens}
</p>
<p className="muted small lens-default-meta">
{correctionLabel(entry)} · saved{' '}
{new Date(entry.updatedAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
})}
</p>
</div>
<button
className="btn ghost small"
disabled={busy === key}
onClick={() => void remove(entry)}
>
{busy === key ? 'Removing…' : 'Remove'}
</button>
</article>
);
})}
</div>
)}
{error && <p className="small lens-error">{error}</p>}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}
+520
View File
@@ -0,0 +1,520 @@
import { useEffect, 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;
onCompare: () => void;
onStack: () => void;
onVirtualCopy: () => void;
onMerge: () => void;
onPrint: () => void;
stacks: Map<string, { count: number; expanded: boolean }>;
onToggleStack: (id: string) => 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;
/** client proofing picks per photo, shown as a badge */
proofCounts: Map<string, number>;
proofStatus: Map<string, { approved: number; changes: number; comments: number }>;
}
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,
onCompare,
onStack,
onVirtualCopy,
onMerge,
onPrint,
stacks,
onToggleStack,
onImport,
onDropFiles,
onClearSelection,
onReorder,
onMarqueeSelect,
proofCounts,
proofStatus,
}: 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 virtualize = photos.length > 140;
const [viewWindow, setViewWindow] = useState({
start: 0,
end: Math.min(photos.length, 140),
top: 0,
bottom: 0,
});
const selectedSet = new Set(selected);
useEffect(() => {
if (!virtualize) {
setViewWindow({ start: 0, end: photos.length, top: 0, bottom: 0 });
return;
}
const grid = gridRef.current;
if (!grid) return;
let frame = 0;
const measure = () => {
const card = grid.querySelector<HTMLElement>('.card');
if (!card) {
if (viewWindow.start >= photos.length) {
setViewWindow({ start: 0, end: Math.min(photos.length, 140), top: 0, bottom: 0 });
}
return;
}
const box = card.getBoundingClientRect();
const style = getComputedStyle(grid);
const gapX = Number.parseFloat(style.columnGap) || 12;
const gapY = Number.parseFloat(style.rowGap) || 12;
const horizontalPadding =
(Number.parseFloat(style.paddingLeft) || 0) + (Number.parseFloat(style.paddingRight) || 0);
const columns = Math.max(
1,
Math.round((grid.clientWidth - horizontalPadding + gapX) / (box.width + gapX)),
);
const rowStep = box.height + gapY;
const firstRow = Math.max(0, Math.floor(grid.scrollTop / rowStep) - 2);
const lastRow = Math.ceil((grid.scrollTop + grid.clientHeight) / rowStep) + 2;
const start = Math.min(photos.length, firstRow * columns);
const end = Math.min(photos.length, Math.max(start + columns, lastRow * columns));
const totalRows = Math.ceil(photos.length / columns);
const top = firstRow * rowStep;
const bottom = Math.max(0, totalRows - lastRow) * rowStep;
setViewWindow((current) =>
current.start === start &&
current.end === end &&
current.top === top &&
current.bottom === bottom
? current
: { start, end, top, bottom },
);
};
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(measure);
};
const observer = new ResizeObserver(schedule);
observer.observe(grid);
grid.addEventListener('scroll', schedule, { passive: true });
schedule();
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
grid.removeEventListener('scroll', schedule);
};
}, [photos.length, virtualize, viewWindow.start]);
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>
<ol className="quick-steps">
<li>Import a shoot into an event.</li>
<li>Rate and flag the keepers.</li>
<li>Double-click a photo to open Develop.</li>
<li>Press ? anytime for shortcuts.</li>
</ol>
<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={onCompare}
disabled={selected.length < 2 || selected.length > 4}
title={selected.length > 4 ? 'Select 2–4 photos to compare' : 'Compare selected photos'}
>
Compare
</button>
<button className="btn ghost small" onClick={onStack} disabled={selected.length < 2}>
Stack
</button>
<button className="btn ghost small" onClick={onVirtualCopy} disabled={selected.length !== 1}>
Virtual copy
</button>
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
Merge
</button>
<button className="btn ghost small" onClick={onExport}>
Export
</button>
<button className="btn ghost small" onClick={onPrint}>
Print
</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 }}
/>
)}
{virtualize && viewWindow.top > 0 && (
<div className="grid-gap" style={{ height: viewWindow.top }} aria-hidden="true" />
)}
{photos.slice(viewWindow.start, viewWindow.end).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) => {
if ((e.target as HTMLElement).closest('.badge.stack')) {
e.preventDefault();
return;
}
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>
)}
{p.copyOf && (
<span className="badge copy" title={p.copyName ?? 'Virtual copy'}>
VC
</span>
)}
{stacks.get(p.id) && (
<button
className={`badge stack ${stacks.get(p.id)?.expanded ? 'expanded' : ''}`}
title={
stacks.get(p.id)?.expanded
? 'Collapse stack'
: `Stack of ${stacks.get(p.id)?.count} — click to expand`
}
onClick={(e) => {
e.stopPropagation();
onToggleStack(p.id);
}}
onDoubleClick={(e) => e.stopPropagation()}
>
{stacks.get(p.id)?.expanded ? '▣' : '▤'} {stacks.get(p.id)?.count}
</button>
)}
{(proofCounts.get(p.id) ?? 0) > 0 && (
<span
className="badge proof"
title={`Picked by ${proofCounts.get(p.id)} client${proofCounts.get(p.id) === 1 ? '' : 's'}`}
>
♥ {(proofCounts.get(p.id) ?? 0) > 1 ? proofCounts.get(p.id) : ''}
</span>
)}
{proofStatus.get(p.id)?.approved ? (
<span className="badge review-approved" title="Approved by a client">✓</span>
) : null}
{proofStatus.get(p.id)?.changes ? (
<span className="badge review-changes" title="Client requested changes">!</span>
) : null}
{proofStatus.get(p.id)?.comments ? (
<span className="badge review-comment" title={`${proofStatus.get(p.id)?.comments} client comment(s)`}>
💬 {proofStatus.get(p.id)?.comments}
</span>
) : null}
</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>
);
})}
{virtualize && viewWindow.bottom > 0 && (
<div className="grid-gap" style={{ height: viewWindow.bottom }} aria-hidden="true" />
)}
</div>
</div>
);
}
+130
View File
@@ -0,0 +1,130 @@
import { useState } from 'react';
import type { PhotoRecord } from '../types';
import { mergePhotos, type MergeKind, type MergeResult } from '../lib/merge';
interface Props {
photos: PhotoRecord[];
onClose: () => void;
onDone: (result: MergeResult) => void;
}
const OPTIONS: { kind: MergeKind; title: string; hint: string }[] = [
{
kind: 'hdr',
title: 'HDR merge',
hint: 'Blend bracketed exposures with alignment and mid-tone weighting.',
},
{
kind: 'panorama',
title: 'Panorama',
hint: 'Stitch a horizontal sequence; overlap is detected automatically.',
},
{
kind: 'focus',
title: 'Focus stack',
hint: 'Choose the sharpest source at every pixel for extended depth of field.',
},
];
export default function MergeModal({ photos, onClose, onDone }: Props) {
const [kind, setKind] = useState<MergeKind>('hdr');
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<MergeResult | null>(null);
const run = async () => {
setBusy(true);
setError(null);
setResult(null);
try {
const merged = await mergePhotos(photos, kind, (done, total) => setProgress(Math.round((done / total) * 100)));
setResult(merged);
} catch (err) {
setError(err instanceof Error ? err.message : 'The merge failed');
} finally {
setBusy(false);
}
};
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal merge-modal">
<header className="modal-head">
<div>
<h2>Merge photos</h2>
<p className="muted small">
{photos.length} source{photos.length === 1 ? '' : 's'} selected. The result becomes a new photo;
the originals stay untouched.
</p>
</div>
<button className="icon-btn" onClick={onClose} disabled={busy} aria-label="Close">
✕
</button>
</header>
<div className="modal-body">
<div className="merge-options">
{OPTIONS.map((option) => (
<button
key={option.kind}
className={`merge-option ${kind === option.kind ? 'on' : ''}`}
onClick={() => {
setKind(option.kind);
setResult(null);
}}
disabled={busy}
>
<strong>{option.title}</strong>
<span>{option.hint}</span>
</button>
))}
</div>
<div className="merge-sources">
{photos.map((photo) => (
<figure key={photo.id}>
<img src={photo.thumbUrl ?? photo.thumb} alt={photo.name} />
<figcaption title={photo.name}>{photo.name}</figcaption>
</figure>
))}
</div>
{error && <div className="banner error">{error}</div>}
{busy && (
<div className="progress">
<div className="progress-bar">
<div className="progress-fill" style={{ width: `${progress}%` }} />
</div>
<div className="muted small">Analysing and merging · {progress}%</div>
</div>
)}
{result && (
<div className="merge-result">
<img src={result.thumb} alt="Merged result" />
<div>
<strong>Merge ready</strong>
<p className="muted small">
{result.width} × {result.height} px. Add it to the catalog and continue editing it like any other photo.
</p>
</div>
</div>
)}
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose} disabled={busy}>
Cancel
</button>
{result ? (
<button className="btn primary" onClick={() => onDone(result)}>
Add to catalog
</button>
) : (
<button className="btn primary" onClick={() => void run()} disabled={busy || photos.length < 2}>
{busy ? 'Merging…' : 'Create merge'}
</button>
)}
</footer>
</div>
</div>
);
}
File diff suppressed because it is too large Load Diff
+97
View File
@@ -0,0 +1,97 @@
import { useState } from 'react';
import { defaultSections, EDIT_SECTIONS, type EditSectionId } from '../lib/editSections';
interface Props {
sourceName: string;
targetCount: number;
mode: 'paste' | 'sync';
onApply: (sections: EditSectionId[]) => void;
onClose: () => void;
}
export default function PasteSettingsModal({
sourceName,
targetCount,
mode,
onApply,
onClose,
}: Props) {
const [selected, setSelected] = useState<Set<EditSectionId>>(() => new Set(defaultSections()));
const toggle = (id: EditSectionId) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const all = selected.size === EDIT_SECTIONS.length;
const none = selected.size === 0;
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal paste-modal">
<header className="modal-head">
<h2>{mode === 'sync' ? 'Sync settings' : 'Paste settings'}</h2>
<button className="icon-btn" onClick={onClose} aria-label="Close">
✕
</button>
</header>
<div className="modal-body">
<p className="muted small">
{mode === 'sync' ? 'Sync from' : 'From'} <strong>{sourceName}</strong> to{' '}
<strong>{targetCount}</strong> photo{targetCount === 1 ? '' : 's'}. Choose what travels.
</p>
<div className="paste-actions">
<button
className="chip ghost"
onClick={() => setSelected(new Set(EDIT_SECTIONS.map((section) => section.id)))}
disabled={all}
>
Select all
</button>
<button className="chip ghost" onClick={() => setSelected(new Set())} disabled={none}>
Clear
</button>
<span className="spacer" />
<span className="muted small">{selected.size} of {EDIT_SECTIONS.length}</span>
</div>
<div className="paste-list">
{EDIT_SECTIONS.map((section) => (
<label key={section.id} className={`paste-row ${section.id === 'crop' || section.id === 'local' ? 'caution' : ''}`}>
<input
type="checkbox"
checked={selected.has(section.id)}
onChange={() => toggle(section.id)}
/>
<span>
<strong>{section.label}</strong>
<small>{section.hint}</small>
</span>
{(section.id === 'crop' || section.id === 'local' || section.id === 'healing') && (
<span className="paste-caution">often photo-specific</span>
)}
</label>
))}
</div>
</div>
<footer className="modal-foot">
<button className="btn ghost" onClick={onClose}>
Cancel
</button>
<button
className="btn primary"
disabled={!selected.size}
onClick={() => onApply([...selected])}
>
{mode === 'sync' ? 'Sync to selection' : `Paste to ${targetCount}`}
</button>
</footer>
</div>
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { useEffect, useState } from 'react';
import { normalizeEdits } from '../lib/edits';
import { getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types';
/**
* Preset thumbnails are rendered once per photo/preset pair and cached as small
* JPEG data URLs. One shared Renderer does all of them: a WebGL context per tile
* would exhaust the browser's context limit long before 70 presets.
*/
const cache = new Map<string, string>();
const CACHE_LIMIT = 900;
const THUMB_EDGE = 200;
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({});
// Preset edits never change after creation, so a stable id list is enough to
// avoid re-running for every parent render.
const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
useEffect(() => {
let alive = true;
let renderer: Renderer | null = null;
const canvas = document.createElement('canvas');
const known: Record<string, string> = {};
for (const preset of presets) {
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
if (hit) known[preset.id] = hit;
}
setThumbs(known);
const pending = presets.filter((p) => !known[p.id]);
if (!pending.length) return;
(async () => {
try {
const bitmap = await getBitmap(photo);
if (!alive) return;
renderer = new Renderer(canvas);
// Every tile shows the photo as it is framed now, so a turned photo's
// presets are turned too.
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
const cropW = Math.max(1, frame.w * crop.w);
const cropH = Math.max(1, frame.h * crop.h);
const scale = THUMB_EDGE / Math.max(cropW, cropH);
const width = Math.max(1, Math.round(cropW * scale));
const height = Math.max(1, Math.round(cropH * scale));
renderer.setImage(bitmap);
for (const preset of pending) {
if (!alive) break;
try {
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
width,
height,
upscale: Math.max(width / cropW, height / cropH) > 1.05,
});
const url = canvas.toDataURL('image/jpeg', 0.72);
cache.set(keyOf(photo.id, preset.id, cropKey), url);
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
} catch {
// One bad preset must not stop the rest of the grid.
}
// Yield between tiles so the panel fills in progressively.
await new Promise((resolve) => setTimeout(resolve, 0));
}
if (cache.size > CACHE_LIMIT) {
for (const key of [...cache.keys()].slice(0, cache.size - CACHE_LIMIT)) cache.delete(key);
}
} catch {
// No bitmap yet (raw not synced) or no WebGL: tiles keep their placeholders.
}
})();
return () => {
alive = false;
renderer?.dispose();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [photo.id, presetKey, cropKey]);
return thumbs;
}
+131
View File
@@ -0,0 +1,131 @@
import { useEffect, useMemo, useState } from 'react';
import type { PhotoRecord } from '../types';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
interface Props {
photos: PhotoRecord[];
onClose: () => void;
}
type Paper = 'a4' | 'letter' | '5x7';
const PAPERS: Record<Paper, { label: string; width: string; height: string }> = {
a4: { label: 'A4', width: '210mm', height: '297mm' },
letter: { label: 'US Letter', width: '8.5in', height: '11in' },
'5x7': { label: '5 × 7 in', width: '5in', height: '7in' },
};
/**
* A browser print layout for the current selection. Images are rendered through
* the same develop pipeline as export, then placed on a paper-sized sheet. The
* browser's print dialog supplies the printer, margins and ICC handling.
*/
export default function PrintModal({ photos, onClose }: Props) {
const [paper, setPaper] = useState<Paper>('a4');
const [perPage, setPerPage] = useState(2);
const [captions, setCaptions] = useState(true);
const [urls, setUrls] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
const made: string[] = [];
(async () => {
try {
const next: Record<string, string> = {};
for (const photo of photos) {
const blob = await renderPhotoBlob(photo, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 95,
resize: 'longEdge',
longEdge: 2200,
zip: false,
metadata: false,
outputSharpen: 18,
watermark: { ...DEFAULT_EXPORT.watermark, enabled: false },
});
const url = URL.createObjectURL(blob);
made.push(url);
next[photo.id] = url;
}
if (alive) setUrls(next);
} catch (err) {
if (alive) setError(err instanceof Error ? err.message : 'Could not render the print preview');
} finally {
if (alive) setBusy(false);
}
})();
return () => {
alive = false;
for (const url of made) URL.revokeObjectURL(url);
};
}, [photos]);
const pages = useMemo(() => {
const out: PhotoRecord[][] = [];
for (let i = 0; i < photos.length; i += perPage) out.push(photos.slice(i, i + perPage));
return out;
}, [photos, perPage]);
const width = PAPERS[paper].width;
const height = PAPERS[paper].height;
return (
<div className="modal-backdrop print-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal print-modal">
<header className="modal-head no-print">
<div>
<h2>Print</h2>
<p className="muted small">{photos.length} photo{photos.length === 1 ? '' : 's'} on {pages.length} page{pages.length === 1 ? '' : 's'}. Use your browser print dialog for the printer and ICC profile.</p>
</div>
<button className="icon-btn" onClick={onClose} aria-label="Close">✕</button>
</header>
<div className="print-toolbar no-print">
<label className="field">
<span>Paper</span>
<select value={paper} onChange={(e) => setPaper(e.target.value as Paper)}>
{Object.entries(PAPERS).map(([id, item]) => (
<option key={id} value={id}>{item.label}</option>
))}
</select>
</label>
<label className="field">
<span>Photos per page</span>
<select value={perPage} onChange={(e) => setPerPage(Number(e.target.value))}>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={4}>4</option>
</select>
</label>
<label className="check-row">
<input type="checkbox" checked={captions} onChange={(e) => setCaptions(e.target.checked)} />
File name caption
</label>
<span className="spacer" />
<button className="btn primary" onClick={() => window.print()} disabled={busy || !!error}>
{busy ? 'Rendering…' : 'Print'}
</button>
</div>
{error && <div className="banner error no-print">{error}</div>}
<div className="print-preview">
{pages.map((page, index) => (
<div
key={index}
className={`print-page per-${perPage}`}
style={{ width, height, ['--paper-w' as string]: width, ['--paper-h' as string]: height }}
>
{page.map((photo) => (
<figure key={photo.id} className="print-photo">
{urls[photo.id] ? <img src={urls[photo.id]} alt={photo.name} /> : <div className="print-placeholder" />}
{captions && <figcaption>{photo.title || photo.name}</figcaption>}
</figure>
))}
</div>
))}
</div>
</div>
</div>
);
}
+496
View File
@@ -0,0 +1,496 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
addGalleryComment,
galleryDownloadAllUrl,
galleryDownloadUrl,
loadGallery,
setGalleryPick,
setGalleryReview,
} from '../lib/api';
import type { GalleryPayload, GalleryPhoto } from '../lib/api';
/**
* The page a client opens from a proofing link. It is entirely session-free:
* the token in the URL is the only credential, and the API only ever returns
* the shared event's live photos.
*/
function clientIdentity() {
const key = 'lumenroom.proof.client';
let id = '';
let name = '';
try {
id = localStorage.getItem(`${key}.id`) ?? '';
name = localStorage.getItem(`${key}.name`) ?? '';
} catch {
/* private mode */
}
if (!id) {
id = `c-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
try {
localStorage.setItem(`${key}.id`, id);
} catch {
/* private mode */
}
}
return { id, name };
}
function fmtDate(ms: number | null) {
if (!ms) return '';
return new Date(ms).toLocaleDateString(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}
function Heart({ filled }: { filled: boolean }) {
return (
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
<path
d="M12 20.4l-1.5-1.36C5.4 14.44 2 11.36 2 7.9 2 5.2 4.2 3 6.9 3c1.6 0 3.1.75 4.1 1.95A5.4 5.4 0 0 1 15.1 3C17.8 3 20 5.2 20 7.9c0 3.46-3.4 6.54-8.5 11.14L12 20.4z"
fill={filled ? 'currentColor' : 'none'}
stroke="currentColor"
strokeWidth="1.6"
strokeLinejoin="round"
/>
</svg>
);
}
export default function ProofingGallery({ token }: { token: string }) {
const identity = useRef(clientIdentity());
const nameRef = useRef<HTMLInputElement>(null);
const [clientName, setClientName] = useState(identity.current.name);
const [data, setData] = useState<GalleryPayload | null>(null);
const [loading, setLoading] = useState(true);
const [fatal, setFatal] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [picks, setPicks] = useState<Set<string>>(new Set());
const [counts, setCounts] = useState<Record<string, number>>({});
const [onlyPicks, setOnlyPicks] = useState(false);
const [lightbox, setLightbox] = useState<string | null>(null);
const [saving, setSaving] = useState<Set<string>>(new Set());
const [commentDraft, setCommentDraft] = useState('');
const [feedbackBusy, setFeedbackBusy] = useState(false);
const load = useCallback(async () => {
try {
const payload = await loadGallery(token, identity.current.id);
setData(payload);
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id)));
const next: Record<string, number> = {};
for (const photo of payload.photos) if (photo.pickCount) next[photo.id] = photo.pickCount;
setCounts(next);
setFatal(null);
setError(null);
} catch (err) {
setFatal(err instanceof Error ? err.message : 'Could not open this gallery');
} finally {
setLoading(false);
}
}, [token]);
useEffect(() => {
void load();
}, [load]);
useEffect(() => {
document.title = data ? `${data.event.name} — Proofing` : 'Proofing gallery';
return () => {
document.title = 'Luminary';
};
}, [data]);
const rememberName = (name: string) => {
setClientName(name);
try {
localStorage.setItem('lumenroom.proof.client.name', name);
} catch {
/* private mode */
}
};
const togglePick = useCallback(
async (photo: GalleryPhoto) => {
if (saving.has(photo.id)) return;
if (!clientName.trim()) {
nameRef.current?.focus();
setError('Add your name so the photographer knows whose picks these are.');
return;
}
const picked = !picks.has(photo.id);
// Optimistic: the heart responds immediately, then reconciles with the
// shared count once the server has recorded the pick.
setPicks((prev) => {
const next = new Set(prev);
if (picked) next.add(photo.id);
else next.delete(photo.id);
return next;
});
setCounts((prev) => {
const next = { ...prev };
const value = Math.max(0, (next[photo.id] ?? 0) + (picked ? 1 : -1));
if (value) next[photo.id] = value;
else delete next[photo.id];
return next;
});
setSaving((prev) => new Set(prev).add(photo.id));
try {
await setGalleryPick(token, {
photoId: photo.id,
picked,
clientId: identity.current.id,
clientName: clientName.trim(),
});
} catch {
setPicks((prev) => {
const next = new Set(prev);
if (picked) next.delete(photo.id);
else next.add(photo.id);
return next;
});
setCounts((prev) => {
const next = { ...prev };
const value = Math.max(0, (next[photo.id] ?? 0) + (picked ? -1 : 1));
if (value) next[photo.id] = value;
else delete next[photo.id];
return next;
});
setError('That pick did not save — check the connection and try again.');
setTimeout(() => setError(null), 4000);
} finally {
setSaving((prev) => {
const next = new Set(prev);
next.delete(photo.id);
return next;
});
}
},
[clientName, picks, saving, token],
);
const submitComment = useCallback(
async (photo: GalleryPhoto) => {
const body = commentDraft.trim();
if (!body || feedbackBusy) return;
setFeedbackBusy(true);
try {
await addGalleryComment(token, {
photoId: photo.id,
clientId: identity.current.id,
clientName: clientName.trim(),
body,
});
setCommentDraft('');
await load();
} catch {
setError('That comment did not save — check the connection and try again.');
} finally {
setFeedbackBusy(false);
}
},
[clientName, commentDraft, feedbackBusy, load, token],
);
const submitReview = useCallback(
async (photo: GalleryPhoto, status: 'approved' | 'changes' | 'none') => {
if (feedbackBusy) return;
if (!clientName.trim()) {
nameRef.current?.focus();
setError('Add your name before approving photos or requesting changes.');
return;
}
setFeedbackBusy(true);
try {
await setGalleryReview(token, {
photoId: photo.id,
clientId: identity.current.id,
clientName: clientName.trim(),
status,
});
await load();
} catch {
setError('That review did not save — check the connection and try again.');
} finally {
setFeedbackBusy(false);
}
},
[clientName, feedbackBusy, load, token],
);
const visible = useMemo(() => {
if (!data) return [];
return onlyPicks ? data.photos.filter((p) => picks.has(p.id)) : data.photos;
}, [data, onlyPicks, picks]);
const lightboxIndex = lightbox ? visible.findIndex((p) => p.id === lightbox) : -1;
const lightboxPhoto = lightboxIndex >= 0 ? visible[lightboxIndex] : null;
useEffect(() => {
if (!lightboxPhoto) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
setLightbox(null);
return;
}
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
const next = visible[lightboxIndex + (e.key === 'ArrowRight' ? 1 : -1)];
if (next) setLightbox(next.id);
return;
}
if (e.key === ' ') {
e.preventDefault();
void togglePick(lightboxPhoto);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [lightboxIndex, lightboxPhoto, togglePick, visible]);
if (loading) {
return (
<div className="proof">
<div className="proof-splash">
<div className="logo large">Luminary</div>
<p>Loading your gallery…</p>
</div>
</div>
);
}
if (!data) {
return (
<div className="proof">
<div className="proof-splash">
<div className="logo large">Luminary</div>
<h1>This gallery isn’t available</h1>
<p>{fatal ?? 'The link may have expired, or the photographer turned it off.'}</p>
</div>
</div>
);
}
const pickedCount = picks.size;
return (
<div className="proof">
<header className="proof-head">
<div className="proof-head-main">
<div className="proof-brand">
<span className="dot" /> Luminary
</div>
<h1>{data.event.name}</h1>
<p className="proof-sub">
{fmtDate(data.event.date)}
{data.event.date ? ' · ' : ''}
{data.photos.length} photo{data.photos.length === 1 ? '' : 's'}
{data.event.notes ? ` · ${data.event.notes}` : ''}
</p>
</div>
<div className="proof-head-side">
<label className="proof-name">
<span>Your name</span>
<input
ref={nameRef}
value={clientName}
placeholder="Add your name"
maxLength={60}
onChange={(e) => rememberName(e.target.value)}
/>
</label>
<div className={`proof-count ${pickedCount ? 'on' : ''}`}>
<Heart filled={pickedCount > 0} />
{pickedCount} pick{pickedCount === 1 ? '' : 's'}
</div>
</div>
</header>
<div className="proof-intro">
<p>
Tap the heart on the photos you love. Your picks are saved as you go — no account
needed, and you can come back to this link any time.
</p>
<div className="proof-tools">
<button
className={`chip ${onlyPicks ? 'on' : ''}`}
onClick={() => setOnlyPicks((v) => !v)}
disabled={!pickedCount && !onlyPicks}
>
My picks {pickedCount ? `(${pickedCount})` : ''}
</button>
{pickedCount > 0 && (
<a
className="btn ghost small"
href={galleryDownloadAllUrl(token, identity.current.id)}
download
>
Download picks
</a>
)}
<span className="proof-subtle">
{data.picks.total
? `${data.picks.total} pick${data.picks.total === 1 ? '' : 's'} from ${
data.picks.clients
} client${data.picks.clients === 1 ? '' : 's'} so far`
: 'Be the first to choose'}
</span>
</div>
</div>
{error && <div className="proof-toast">{error}</div>}
{onlyPicks && !visible.length ? (
<div className="proof-empty">
<Heart filled={false} />
<h2>No picks yet</h2>
<p>Tap a heart on any photo and it will show up here.</p>
<button className="btn" onClick={() => setOnlyPicks(false)}>
Back to all photos
</button>
</div>
) : (
<div className="proof-grid">
{visible.map((photo, i) => {
const picked = picks.has(photo.id);
return (
<figure
key={photo.id}
className={`proof-card ${picked ? 'picked' : ''}`}
style={{ animationDelay: `${Math.min(i, 16) * 28}ms` }}
>
<button
className="proof-shot"
onClick={() => setLightbox(photo.id)}
title={photo.name}
>
<img
src={photo.thumbUrl}
alt={photo.name}
loading={i < 12 ? 'eager' : 'lazy'}
draggable={false}
/>
</button>
<button
className={`proof-heart ${picked ? 'on' : ''}`}
onClick={() => void togglePick(photo)}
aria-pressed={picked}
title={picked ? 'Remove from picks' : 'Pick this photo'}
>
<Heart filled={picked} />
{counts[photo.id] ? <span>{counts[photo.id]}</span> : null}
</button>
<div className="proof-feedback-badges">
{photo.reviewStatus === 'approved' && <span className="proof-review approved">✓ Approved</span>}
{photo.reviewStatus === 'changes' && <span className="proof-review changes">! Changes</span>}
{photo.comments.length > 0 && <span className="proof-comment-count">💬 {photo.comments.length}</span>}
</div>
</figure>
);
})}
</div>
)}
<footer className="proof-foot">
<span>Proofing gallery by Luminary</span>
<span>{clientName.trim() ? `Picks saved for ${clientName.trim()}` : 'Your picks save automatically'}</span>
</footer>
{lightboxPhoto && (
<div className="proof-lb" onClick={() => setLightbox(null)}>
<button className="proof-lb-close" onClick={() => setLightbox(null)} title="Close (Esc)">
×
</button>
<button
className="proof-lb-nav prev"
onClick={(e) => {
e.stopPropagation();
const prev = visible[lightboxIndex - 1];
if (prev) setLightbox(prev.id);
}}
disabled={lightboxIndex <= 0}
title="Previous"
>
‹
</button>
<div className="proof-lb-body" onClick={(e) => e.stopPropagation()}>
<img src={lightboxPhoto.previewUrl} alt={lightboxPhoto.name} draggable={false} />
<div className="proof-lb-bar">
<div className="proof-lb-title">
<span className="proof-lb-name">{lightboxPhoto.name}</span>
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
Download
</a>
</div>
<button
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`}
onClick={() => void togglePick(lightboxPhoto)}
>
<Heart filled={picks.has(lightboxPhoto.id)} />
{picks.has(lightboxPhoto.id) ? 'Picked' : 'Pick this photo'}
</button>
</div>
<div className="proof-review-bar">
<span className="muted small">Review</span>
<button
className={`chip ${lightboxPhoto.reviewStatus === 'approved' ? 'on' : ''}`}
onClick={() => void submitReview(lightboxPhoto, lightboxPhoto.reviewStatus === 'approved' ? 'none' : 'approved')}
disabled={feedbackBusy}
>
✓ Approve
</button>
<button
className={`chip ${lightboxPhoto.reviewStatus === 'changes' ? 'on' : ''}`}
onClick={() => void submitReview(lightboxPhoto, lightboxPhoto.reviewStatus === 'changes' ? 'none' : 'changes')}
disabled={feedbackBusy}
>
! Needs changes
</button>
</div>
<div className="proof-comments">
<div className="proof-comments-head">Comments · {lightboxPhoto.comments.length}</div>
{lightboxPhoto.comments.map((comment) => (
<div key={comment.id} className="proof-comment">
<strong>{comment.clientName || 'Client'}</strong>
<span>{comment.body}</span>
</div>
))}
<div className="proof-comment-add">
<input
value={commentDraft}
placeholder={clientName.trim() ? 'Add a note…' : 'Add your name above, then comment'}
maxLength={1200}
onChange={(e) => setCommentDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void submitComment(lightboxPhoto);
}}
disabled={!clientName.trim() || feedbackBusy}
/>
<button
className="btn primary small"
onClick={() => void submitComment(lightboxPhoto)}
disabled={!commentDraft.trim() || !clientName.trim() || feedbackBusy}
>
Send
</button>
</div>
</div>
</div>
<button
className="proof-lb-nav next"
onClick={(e) => {
e.stopPropagation();
const next = visible[lightboxIndex + 1];
if (next) setLightbox(next.id);
}}
disabled={lightboxIndex >= visible.length - 1}
title="Next"
>
›
</button>
</div>
)}
</div>
);
}
+321
View File
@@ -0,0 +1,321 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { createShare, getShare, pushProof, revokeShare } from '../lib/api';
import type { ShareState } from '../lib/api';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
import type { ExportOptions } from '../lib/export';
import type { PhotoRecord } from '../types';
interface Props {
event: { id: string; name: string };
photos: PhotoRecord[];
onClose: () => void;
onToast: (message: string) => void;
/** Update the local record after a rendered proof is accepted by the server. */
onProofPublished?: (photoId: string, thumbUrl: string, proofAt: number) => void;
}
const PROOF_EXPORT: ExportOptions = {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'longEdge',
longEdge: 2800,
zip: false,
metadata: false,
outputSharpen: 8,
watermark: { ...DEFAULT_EXPORT.watermark, enabled: false },
};
function proofBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const value = typeof reader.result === 'string' ? reader.result : '';
resolve(value.includes(',') ? value.slice(value.indexOf(',') + 1) : value);
};
reader.onerror = () => reject(reader.error ?? new Error('Could not read the proof'));
reader.readAsDataURL(blob);
});
}
/**
* Owner-side control for a proofing link: turn it on, copy it, see who has
* picked what, and revoke it. Picks live on the server keyed by the link, so
* anyone with the URL can choose photos without an account.
*/
export default function ShareModal({ event, photos, onClose, onToast, onProofPublished }: Props) {
const [share, setShare] = useState<ShareState | null>(null);
const [busy, setBusy] = useState(false);
const [publishing, setPublishing] = useState(false);
const [published, setPublished] = useState(0);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const refresh = useCallback(async () => {
try {
setShare(await getShare(event.id));
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read the proofing link');
}
}, [event.id]);
useEffect(() => {
void refresh();
}, [refresh]);
useEffect(() => {
if (!share?.token) return;
const timer = setInterval(() => void refresh(), 20000);
return () => clearInterval(timer);
}, [refresh, share?.token]);
const url = useMemo(() => {
if (!share?.token) return '';
return `${window.location.origin}/g/${share.token}`;
}, [share]);
const picksByPhoto = useMemo(() => {
const map = new Map<string, string[]>();
for (const pick of share?.picks ?? []) {
const names = map.get(pick.photoId) ?? [];
names.push(pick.clientName || 'Client');
map.set(pick.photoId, names);
}
return map;
}, [share]);
const names = useMemo(() => {
const set = new Set<string>();
for (const pick of share?.picks ?? []) set.add(pick.clientName || 'Client');
return [...set];
}, [share]);
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
const publishProofs = async () => {
if (!photos.length || publishing) return 0;
setPublishing(true);
setPublished(0);
setError(null);
let done = 0;
try {
for (const photo of photos) {
const blob = await renderPhotoBlob(photo, PROOF_EXPORT);
const result = await pushProof(photo.id, await proofBase64(blob));
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
done += 1;
setPublished(done);
}
onToast(`Published ${done} edited proof${done === 1 ? '' : 's'}`);
return done;
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
return done;
} finally {
setPublishing(false);
}
};
const enable = async () => {
setBusy(true);
setError(null);
try {
await createShare(event.id);
await refresh();
// A gallery without rendered proofs would show the unedited originals.
await publishProofs();
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the link');
} finally {
setBusy(false);
}
};
const copy = async () => {
if (!url) return;
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 1800);
} catch {
// Clipboard needs permission; selecting the text still lets them copy it.
setError('Could not copy automatically — select the link and copy it.');
}
};
const revoke = async () => {
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
return;
}
setBusy(true);
try {
await revokeShare(event.id);
setShare({ token: null, picks: [] });
onToast('Proofing link turned off');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not turn off the link');
} finally {
setBusy(false);
}
};
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}
>
<div className="modal share-modal">
<header className="modal-head">
<div>
<h2>Client proofing</h2>
<p className="muted small">
Share “{event.name}” as a public gallery. Clients pick favourites without an
account, and their choices show up here and in the library.
</p>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
×
</button>
</header>
<div className="modal-body">
{error && <div className="banner error">{error}</div>}
{!share ? (
<p className="muted">Reading the link…</p>
) : share.token ? (
<>
<div className="share-link-row">
<input value={url} readOnly spellCheck={false} onFocus={(e) => e.target.select()} />
<button className="btn primary" onClick={() => void copy()}>
{copied ? 'Copied' : 'Copy link'}
</button>
</div>
<p className="muted small">
Anyone with this link can view the {photos.length} photos in this event and pick
favourites. Links can be turned off at any time.
</p>
<div className="share-stats">
<div>
<strong>{share.picks.length}</strong>
<span>picks</span>
</div>
<div>
<strong>{names.length}</strong>
<span>{names.length === 1 ? 'client' : 'clients'}</span>
</div>
<div>
<strong>{new Set(share.picks.map((p) => p.photoId)).size}</strong>
<span>photos chosen</span>
</div>
</div>
<div className="share-publish">
<div>
<strong>Edited proofs</strong>
<p className="muted small">
Generate the gallery from the current crop, grade and retouching. The
originals and editable proxies stay untouched.
</p>
</div>
<button
className="btn primary small"
disabled={busy || publishing || !photos.length}
onClick={() => void publishProofs()}
>
{publishing ? `Publishing ${published}/${photos.length}…` : 'Publish edited proofs'}
</button>
</div>
{(share.feedback ?? []).length > 0 && (
<div className="share-feedback">
<div className="share-picks-head">
<span>Client feedback</span>
<button className="btn ghost small" onClick={() => void refresh()}>
Refresh
</button>
</div>
<ul>
{(share.feedback ?? []).slice(0, 40).map((item, index) => (
<li key={`${item.kind}:${item.photoId}:${item.createdAt}:${index}`}>
<span className="share-pick-name">
{namesByPhoto.get(item.photoId) ?? 'Photo'}
</span>
<span className={`share-feedback-kind ${item.kind}`}>
{item.kind === 'approved'
? 'Approved'
: item.kind === 'changes'
? 'Changes requested'
: item.clientName || 'Client'}
</span>
{item.body && <p>{item.body}</p>}
{item.kind === 'comment' && (
<span className="muted small">{item.clientName || 'Client'}</span>
)}
</li>
))}
</ul>
</div>
)}
{share.picks.length ? (
<div className="share-picks">
<div className="share-picks-head">
<span>Client picks</span>
<button className="btn ghost small" onClick={() => void refresh()}>
Refresh
</button>
</div>
<ul>
{[...picksByPhoto.entries()]
.sort((a, b) => b[1].length - a[1].length)
.map(([photoId, who]) => (
<li key={photoId}>
<span className="share-pick-name">
{namesByPhoto.get(photoId) ?? 'Photo'}
</span>
<span className="muted small">{who.join(', ')}</span>
</li>
))}
</ul>
</div>
) : (
<p className="muted small share-waiting">
No picks yet. Client hearts appear here as they work through the gallery.
</p>
)}
<div className="share-warning">
<button className="btn ghost small danger" disabled={busy} onClick={() => void revoke()}>
Turn off link
</button>
<span className="muted small">Clears the gallery and its picks.</span>
</div>
</>
) : (
<div className="share-empty">
<p>
This event has no proofing link yet. Creating one lets a client review the shoot
and mark favourites.
</p>
<button className="btn primary" disabled={busy} onClick={() => void enable()}>
{busy ? 'Creating…' : 'Create proofing link'}
</button>
</div>
)}
</div>
<footer className="modal-foot">
<span className="muted small">
Photos in the trash and develop settings stay private.
</span>
<button className="btn" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import { useEffect } from 'react';
const GROUPS: { title: string; rows: [string, string][] }[] = [
{
title: 'Everywhere',
rows: [
['?', 'Show or hide this list'],
['⌘ / Ctrl + K', 'Search photos, events and actions'],
['⌘ / 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'],
['C', 'Compare selected photos'],
['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'],
['Q', 'Spot healing brush'],
['M', 'Edit the selected local mask'],
['Enter', 'Apply the crop'],
['\\ (hold)', 'Before / after'],
['1 – 5', 'Star rating'],
['0', 'Clear rating'],
['6 – 9', 'Red, yellow, green, blue label'],
['P / X / U', 'Pick · reject · unflag'],
['J / Shift + J', 'Highlight · shadow clipping'],
['F', 'Full-screen loupe with rating and flags'],
['← →', 'Previous · next photo'],
['Scroll · drag', 'Zoom · pan'],
['⌘ / Ctrl + Z', 'Undo'],
['⌘ / Ctrl + Shift + Z', 'Redo'],
['⌘ / 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>
))}
<section className="shortcut-start">
<h3>Quick start</h3>
<p>Import a shoot, rate and pick frames in the library, then open Develop for the keepers.</p>
<p>Hover a panel seam to reveal its collapse tab. Press Tab to move focus, or ? for this list.</p>
<p>⌘K / Ctrl+K searches the whole catalog without changing your current filters.</p>
</section>
</div>
</div>
</div>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { useEffect, useState } from 'react';
import { beginClipPreview } from '../lib/clipPreview';
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;
/** Ctrl held during a drag shows the channel clipping overlay */
previewClipping?: 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,
previewClipping,
}: 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))}
onPointerDown={
previewClipping
? (e) => beginClipPreview(e.ctrlKey || e.metaKey)
: undefined
}
onDoubleClick={() => onChange(def)}
/>
<NumberField value={value} onChange={onChange} format={format} />
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
import type { ColorLabel, Flag } from '../types';
interface Props {
value: number;
onChange?: (rating: number) => void;
size?: 'sm' | 'md' | 'lg';
title?: string;
}
export default function Stars({ value, onChange, size = 'sm', title }: Props) {
return (
<div className={`stars ${size}`} title={title}>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
disabled={!onChange}
className={`star ${value >= n ? 'on' : ''}`}
aria-label={`${n} star${n === 1 ? '' : 's'}`}
onClick={(e) => {
e.stopPropagation();
onChange?.(value === n ? 0 : n);
}}
>
★
</button>
))}
</div>
);
}
export function FlagButtons({ value, onChange }: { value: Flag; onChange: (flag: Flag) => void }) {
return (
<div className="flag-buttons">
<button
className={`flag-btn pick ${value === 'pick' ? 'on' : ''}`}
title="Pick (P)"
onClick={() => onChange(value === 'pick' ? 'none' : 'pick')}
>
✓
</button>
<button
className={`flag-btn reject ${value === 'reject' ? 'on' : ''}`}
title="Reject (X)"
onClick={() => onChange(value === 'reject' ? 'none' : 'reject')}
>
✕
</button>
</div>
);
}
export function ColorSwatches({ value, onChange }: { value: ColorLabel; onChange: (color: ColorLabel) => void }) {
return (
<div className="color-filter">
{(
[
{ c: 'red' as ColorLabel, hex: '#e05252' },
{ c: 'yellow' as ColorLabel, hex: '#e0c04a' },
{ c: 'green' as ColorLabel, hex: '#56b268' },
{ c: 'blue' as ColorLabel, hex: '#4f86e0' },
{ c: 'purple' as ColorLabel, hex: '#9b6ede' },
] as const
).map(({ c, hex }) => (
<button
key={c}
className={`swatch ${value === c ? 'on' : ''}`}
style={{ background: hex }}
title={c}
onClick={() => onChange(value === c ? '' : c)}
/>
))}
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
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;
onSearch: () => void;
onCatalog: () => void;
canShare: boolean;
onShare: () => void;
}
export default function TopBar({
view,
eventName,
photoCount,
selectedCount,
cloudLabel,
cloudOn,
onViewChange,
onImport,
onExport,
onCloud,
onHelp,
onSearch,
onCatalog,
canShare,
onShare,
}: Props) {
return (
<header className="topbar">
<div className="brand">
<span className="dot" />
Luminary
</div>
<button
type="button"
className="icon-btn mobile-only catalog-btn"
onClick={onCatalog}
title="Open catalog"
aria-label="Open catalog"
>
▤
</button>
<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>
{canShare && (
<button className="btn ghost" onClick={onShare} title="Share this event for client proofing">
Share
</button>
)}
<button className="btn ghost" onClick={onExport}>
Export
</button>
<button className="icon-btn search-btn" onClick={onSearch} title="Search everything (⌘K / Ctrl+K)" aria-label="Search everything">
⌕
</button>
<button className="icon-btn help-btn" onClick={onHelp} title="Keyboard shortcuts (?)">
?
</button>
<a
className="guide-btn"
href="/luminary-user-guide.pdf"
target="_blank"
rel="noreferrer"
title="User guide (PDF)"
>
Guide
</a>
<button className="btn primary" onClick={onImport}>
Import photos
</button>
</div>
</header>
);
}