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:
+2187
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
export interface MenuAction {
|
||||
label: string;
|
||||
shortcut?: string;
|
||||
onSelect: () => void;
|
||||
disabled?: boolean;
|
||||
danger?: boolean;
|
||||
}
|
||||
|
||||
export type MenuEntry = MenuAction | 'separator';
|
||||
|
||||
interface Props {
|
||||
x: number;
|
||||
y: number;
|
||||
entries: MenuEntry[];
|
||||
header?: ReactNode;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Right-click menu anchored to the pointer. Rendered in a portal so the app's
|
||||
* scroll containers and panel overflow cannot clip it, and nudged inside the
|
||||
* window when the cursor is close to an edge.
|
||||
*/
|
||||
export default function ContextMenu({ x, y, entries, header, onClose }: Props) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const margin = 8;
|
||||
setPos({
|
||||
left: Math.max(margin, Math.min(x, window.innerWidth - rect.width - margin)),
|
||||
top: Math.max(margin, Math.min(y, window.innerHeight - rect.height - margin)),
|
||||
});
|
||||
}, [x, y]);
|
||||
|
||||
useEffect(() => {
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
if (ref.current && e.target instanceof Node && ref.current.contains(e.target)) return;
|
||||
onClose();
|
||||
};
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
};
|
||||
window.addEventListener('pointerdown', onPointerDown, true);
|
||||
window.addEventListener('keydown', onKeyDown, true);
|
||||
window.addEventListener('resize', onClose);
|
||||
window.addEventListener('blur', onClose);
|
||||
window.addEventListener('wheel', onClose, { passive: true });
|
||||
return () => {
|
||||
window.removeEventListener('pointerdown', onPointerDown, true);
|
||||
window.removeEventListener('keydown', onKeyDown, true);
|
||||
window.removeEventListener('resize', onClose);
|
||||
window.removeEventListener('blur', onClose);
|
||||
window.removeEventListener('wheel', onClose);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
ref={ref}
|
||||
className="ctx-menu"
|
||||
role="menu"
|
||||
style={{ left: pos?.left ?? x, top: pos?.top ?? y, visibility: pos ? 'visible' : 'hidden' }}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{header && <div className="ctx-header">{header}</div>}
|
||||
{entries.map((entry, i) =>
|
||||
entry === 'separator' ? (
|
||||
<div className="ctx-sep" key={`sep-${i}`} />
|
||||
) : (
|
||||
<button
|
||||
key={`${entry.label}-${i}`}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={`ctx-item ${entry.danger ? 'danger' : ''}`}
|
||||
disabled={entry.disabled}
|
||||
onClick={() => {
|
||||
onClose();
|
||||
entry.onSelect();
|
||||
}}
|
||||
>
|
||||
<span>{entry.label}</span>
|
||||
{entry.shortcut && <span className="ctx-key">{entry.shortcut}</span>}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { useEffect, useRef, useState, type PointerEvent } from 'react';
|
||||
import { clamp } from '../lib/curves';
|
||||
import { grainSampleWindow, Renderer } from '../gl/renderer';
|
||||
import type { CropState, Edits } from '../types';
|
||||
|
||||
type Mode = 'move' | 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
|
||||
|
||||
/**
|
||||
* Point (frame uv) the loupe sits on when dragged to `u`,`v` inside the crop
|
||||
* rectangle, kept a half-box away from its edges so the patch stays inside.
|
||||
*/
|
||||
export function clampLoupe(
|
||||
crop: { x: number; y: number; w: number; h: number },
|
||||
u: number,
|
||||
v: number,
|
||||
halfU: number,
|
||||
halfV: number,
|
||||
) {
|
||||
const cx = Math.min(1 - halfU, Math.max(halfU, Math.min(1, Math.max(0, u))));
|
||||
const cy = Math.min(1 - halfV, Math.max(halfV, Math.min(1, Math.max(0, v))));
|
||||
return { x: crop.x + cx * crop.w, y: crop.y + cy * crop.h };
|
||||
}
|
||||
|
||||
interface Props {
|
||||
crop: CropState;
|
||||
frame: { w: number; h: number };
|
||||
ratio: number | null;
|
||||
bitmap: ImageBitmap | null;
|
||||
edits: Edits;
|
||||
onChange: (rect: Partial<CropState>) => void;
|
||||
/** lets the preview hold the grain still while a handle is moving */
|
||||
onDragChange?: (busy: boolean) => void;
|
||||
}
|
||||
|
||||
const MIN = 0.04;
|
||||
|
||||
function clampRect(r: CropState): CropState {
|
||||
let w = clamp(r.w, MIN, 1);
|
||||
let h = clamp(r.h, MIN, 1);
|
||||
const x = clamp(r.x, 0, 1 - w);
|
||||
const y = clamp(r.y, 0, 1 - h);
|
||||
return { ...r, x, y, w, h };
|
||||
}
|
||||
|
||||
function applyDrag(
|
||||
start: CropState,
|
||||
mode: Mode,
|
||||
dx: number,
|
||||
dy: number,
|
||||
ratio: number | null,
|
||||
frame: { w: number; h: number },
|
||||
): Partial<CropState> {
|
||||
let { x, y, w, h } = start;
|
||||
|
||||
if (mode === 'move') {
|
||||
x = clamp(x + dx, 0, 1 - w);
|
||||
y = clamp(y + dy, 0, 1 - h);
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
if (mode.includes('e')) w = clamp(w + dx, MIN, 1 - x);
|
||||
if (mode.includes('s')) h = clamp(h + dy, MIN, 1 - y);
|
||||
if (mode.includes('w')) {
|
||||
const nx = clamp(x + dx, 0, x + w - MIN);
|
||||
w += x - nx;
|
||||
x = nx;
|
||||
}
|
||||
if (mode.includes('n')) {
|
||||
const ny = clamp(y + dy, 0, y + h - MIN);
|
||||
h += y - ny;
|
||||
y = ny;
|
||||
}
|
||||
|
||||
if (ratio) {
|
||||
const frameRatio = frame.w / frame.h;
|
||||
const dragsWidth = mode.includes('e') || mode.includes('w');
|
||||
if (dragsWidth) {
|
||||
const targetH = (w * frameRatio) / ratio;
|
||||
if (mode.includes('n')) y = y + h - targetH;
|
||||
h = targetH;
|
||||
} else if (mode.includes('n') || mode.includes('s')) {
|
||||
const targetW = (h * ratio) / frameRatio;
|
||||
x += (w - targetW) / 2;
|
||||
w = targetW;
|
||||
}
|
||||
if (w > 1) {
|
||||
const k = 1 / w;
|
||||
w *= k;
|
||||
h *= k;
|
||||
}
|
||||
if (h > 1) {
|
||||
const k = 1 / h;
|
||||
w *= k;
|
||||
h *= k;
|
||||
}
|
||||
if (mode.includes('w')) x = start.x + start.w - w;
|
||||
if (mode.includes('n')) y = start.y + start.h - h;
|
||||
x = clamp(x, 0, 1 - w);
|
||||
y = clamp(y, 0, 1 - h);
|
||||
}
|
||||
|
||||
return clampRect({ ...start, x, y, w, h });
|
||||
}
|
||||
|
||||
export default function CropOverlay({ crop, frame, ratio, bitmap, edits, onChange, onDragChange }: Props) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const start = useRef<{ mode: Mode; x: number; y: number; rect: CropState } | null>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const loupe = useRef<HTMLCanvasElement>(null);
|
||||
const loupeRenderer = useRef<Renderer | null>(null);
|
||||
/** where the patch is sampling, in frame uv; null = centre of the rectangle */
|
||||
const [loupePoint, setLoupePoint] = useState<{ x: number; y: number } | null>(null);
|
||||
/** pointer offset from the patch centre while it is being dragged */
|
||||
const grab = useRef<{ x: number; y: number } | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
loupeRenderer.current?.dispose();
|
||||
loupeRenderer.current = null;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// A live 1:1 grain patch inside the crop rectangle: it samples whatever area the
|
||||
// rectangle frames, so the rectangle can be judged as it is dragged.
|
||||
useEffect(() => {
|
||||
const canvas = loupe.current;
|
||||
if (!canvas || !bitmap) return;
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const cssW = 120;
|
||||
const cropPxW = Math.max(1, frame.w * crop.w);
|
||||
const cropPxH = Math.max(1, frame.h * crop.h);
|
||||
const cssH = Math.round(Math.min(96, Math.max(48, cssW * (cropPxH / cropPxW))));
|
||||
const W = Math.max(1, Math.round(cssW * dpr));
|
||||
const H = Math.max(1, Math.round(cssH * dpr));
|
||||
canvas.style.width = `${cssW}px`;
|
||||
canvas.style.height = `${cssH}px`;
|
||||
if (canvas.width !== W) canvas.width = W;
|
||||
if (canvas.height !== H) canvas.height = H;
|
||||
try {
|
||||
if (!loupeRenderer.current) loupeRenderer.current = new Renderer(canvas);
|
||||
const r = loupeRenderer.current;
|
||||
r.setImage(bitmap);
|
||||
const view = grainSampleWindow(frame, crop, W, H, loupePoint);
|
||||
r.render({ ...edits, crop }, { width: W, height: H, view });
|
||||
} catch {
|
||||
// The overlay still works if the engine cannot start a second context.
|
||||
}
|
||||
}, [bitmap, crop, edits, frame, loupePoint]);
|
||||
|
||||
const dpr = Math.min(typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1, 2);
|
||||
const loupeCssW = 120;
|
||||
const cropPxW = Math.max(1, frame.w * crop.w);
|
||||
const cropPxH = Math.max(1, frame.h * crop.h);
|
||||
const loupeCssH = Math.round(Math.min(96, Math.max(48, loupeCssW * (cropPxH / cropPxW))));
|
||||
const loupeW = Math.max(1, Math.round(loupeCssW * dpr));
|
||||
const loupeH = Math.max(1, Math.round(loupeCssH * dpr));
|
||||
const view = grainSampleWindow(frame, crop, loupeW, loupeH, loupePoint);
|
||||
const fits = crop.w > 0.16 && crop.h > 0.16;
|
||||
const loupeAt = {
|
||||
left: `${((view.x + view.w / 2 - crop.x) / crop.w) * 100}%`,
|
||||
top: `${((view.y + view.h / 2 - crop.y) / crop.h) * 100}%`,
|
||||
width: `${loupeCssW}px`,
|
||||
height: `${loupeCssH}px`,
|
||||
transform: 'translate(-50%, -50%)',
|
||||
display: fits && bitmap ? 'block' : 'none',
|
||||
};
|
||||
|
||||
const startLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
const box = e.currentTarget.parentElement?.getBoundingClientRect();
|
||||
if (!box || !box.width || !box.height) return;
|
||||
const cx = box.left + ((view.x + view.w / 2 - crop.x) / crop.w) * box.width;
|
||||
const cy = box.top + ((view.y + view.h / 2 - crop.y) / crop.h) * box.height;
|
||||
grab.current = { x: e.clientX - cx, y: e.clientY - cy };
|
||||
};
|
||||
|
||||
const moveLoupe = (e: PointerEvent<HTMLCanvasElement>) => {
|
||||
const g = grab.current;
|
||||
if (!g) return;
|
||||
const box = e.currentTarget.parentElement?.getBoundingClientRect();
|
||||
if (!box || !box.width || !box.height) return;
|
||||
const halfU = Math.min(0.5, loupeCssW / 2 / box.width);
|
||||
const halfV = Math.min(0.5, loupeCssH / 2 / box.height);
|
||||
setLoupePoint(
|
||||
clampLoupe(
|
||||
crop,
|
||||
(e.clientX - g.x - box.left) / box.width,
|
||||
(e.clientY - g.y - box.top) / box.height,
|
||||
halfU,
|
||||
halfV,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const endLoupe = () => {
|
||||
grab.current = null;
|
||||
};
|
||||
|
||||
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
const el = e.target as HTMLElement;
|
||||
const mode = (el.dataset.mode ?? 'move') as Mode;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
ref.current?.setPointerCapture(e.pointerId);
|
||||
start.current = { mode, x: e.clientX, y: e.clientY, rect: { ...crop } };
|
||||
setDragging(true);
|
||||
onDragChange?.(true);
|
||||
};
|
||||
|
||||
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
const s = start.current;
|
||||
const el = ref.current;
|
||||
if (!s || !el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) return;
|
||||
const dx = (e.clientX - s.x) / rect.width;
|
||||
const dy = (e.clientY - s.y) / rect.height;
|
||||
onChange(applyDrag(s.rect, s.mode, dx, dy, ratio, frame));
|
||||
};
|
||||
|
||||
const end = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (ref.current?.hasPointerCapture(e.pointerId)) ref.current.releasePointerCapture(e.pointerId);
|
||||
start.current = null;
|
||||
setDragging(false);
|
||||
onDragChange?.(false);
|
||||
};
|
||||
|
||||
const style = {
|
||||
left: `${crop.x * 100}%`,
|
||||
top: `${crop.y * 100}%`,
|
||||
width: `${crop.w * 100}%`,
|
||||
height: `${crop.h * 100}%`,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`crop-overlay ${dragging ? 'dragging' : ''}`}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={end}
|
||||
onPointerCancel={end}
|
||||
>
|
||||
<div className="crop-rect" style={style}>
|
||||
<div className="crop-grid" data-mode="move" />
|
||||
{(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as Mode[]).map((m) => (
|
||||
<span key={m} className={`handle ${m}`} data-mode={m} />
|
||||
))}
|
||||
<canvas
|
||||
ref={loupe}
|
||||
className="crop-loupe"
|
||||
style={loupeAt}
|
||||
title="Grain at 100% · drag to sample any point in the crop"
|
||||
onPointerDown={startLoupe}
|
||||
onPointerMove={moveLoupe}
|
||||
onPointerUp={endLoupe}
|
||||
onPointerCancel={endLoupe}
|
||||
/>
|
||||
<span className="crop-size">
|
||||
{Math.round(crop.w * 100)}% × {Math.round(crop.h * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { buildSampler, clamp01 } from '../lib/curves';
|
||||
import type { CurvePoint } from '../types';
|
||||
|
||||
interface Props {
|
||||
points: CurvePoint[];
|
||||
onChange: (points: CurvePoint[]) => void;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const pointsRef = useRef(points);
|
||||
const [drag, setDrag] = useState<number | null>(null);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
pointsRef.current = points;
|
||||
}, [points]);
|
||||
|
||||
const sampler = useMemo(() => buildSampler(points), [points]);
|
||||
|
||||
const path = useMemo(() => {
|
||||
const segs: string[] = [];
|
||||
for (let i = 0; i <= 80; i++) {
|
||||
const x = i / 80;
|
||||
const y = sampler(x);
|
||||
segs.push(`${i === 0 ? 'M' : 'L'}${(x * 100).toFixed(2)},${((1 - y) * 100).toFixed(2)}`);
|
||||
}
|
||||
return segs.join(' ');
|
||||
}, [sampler]);
|
||||
|
||||
const toNorm = useCallback((clientX: number, clientY: number) => {
|
||||
const svg = svgRef.current;
|
||||
if (!svg) return { x: 0, y: 0 };
|
||||
const rect = svg.getBoundingClientRect();
|
||||
return {
|
||||
x: clamp01((clientX - rect.left) / rect.width),
|
||||
y: clamp01(1 - (clientY - rect.top) / rect.height),
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||
e.preventDefault();
|
||||
const idxAttr = (e.target as Element).getAttribute('data-idx');
|
||||
let idx: number;
|
||||
if (idxAttr !== null) {
|
||||
idx = Number(idxAttr);
|
||||
} else {
|
||||
const p = toNorm(e.clientX, e.clientY);
|
||||
const next = [...points, { x: p.x, y: p.y }].sort((a, b) => a.x - b.x);
|
||||
idx = next.findIndex((pt) => pt.x === p.x && pt.y === p.y);
|
||||
onChange(next);
|
||||
}
|
||||
setDrag(idx);
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
};
|
||||
|
||||
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||
if (drag === null) return;
|
||||
const pts = pointsRef.current;
|
||||
const idx = drag;
|
||||
if (!pts[idx]) return;
|
||||
const p = toNorm(e.clientX, e.clientY);
|
||||
const lo = idx > 0 ? pts[idx - 1].x + 0.01 : 0;
|
||||
const hi = idx < pts.length - 1 ? pts[idx + 1].x - 0.01 : 1;
|
||||
const next = pts.map((pt, i) => (i === idx ? { x: Math.min(hi, Math.max(lo, p.x)), y: p.y } : pt));
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const handleUp = () => setDrag(null);
|
||||
|
||||
const removePoint = (idx: number) => {
|
||||
const pts = pointsRef.current;
|
||||
if (pts.length <= 2) return;
|
||||
onChange(pts.filter((_, i) => i !== idx));
|
||||
setDrag(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="curve-wrap">
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="curve"
|
||||
viewBox="0 0 100 100"
|
||||
preserveAspectRatio="none"
|
||||
onPointerDown={handleDown}
|
||||
onPointerMove={handleMove}
|
||||
onPointerUp={handleUp}
|
||||
onPointerCancel={handleUp}
|
||||
onDoubleClick={(e) => {
|
||||
const idxAttr = (e.target as Element).getAttribute('data-idx');
|
||||
if (idxAttr !== null) removePoint(Number(idxAttr));
|
||||
}}
|
||||
>
|
||||
<rect x="0" y="0" width="100" height="100" className="curve-bg" />
|
||||
{[25, 50, 75].map((v) => (
|
||||
<g key={v}>
|
||||
<line x1={v} y1="0" x2={v} y2="100" className="curve-grid" />
|
||||
<line x1="0" y1={v} x2="100" y2={v} className="curve-grid" />
|
||||
</g>
|
||||
))}
|
||||
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
|
||||
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
|
||||
{points.map((p, i) => (
|
||||
<circle
|
||||
key={`${i}-${p.x.toFixed(3)}`}
|
||||
data-idx={i}
|
||||
cx={p.x * 100}
|
||||
cy={(1 - p.y) * 100}
|
||||
r={hover === i || drag === i ? 3 : 2.1}
|
||||
className="curve-point"
|
||||
fill={color}
|
||||
onPointerEnter={() => setHover(i)}
|
||||
onPointerLeave={() => setHover((h) => (h === i ? null : h))}
|
||||
/>
|
||||
))}
|
||||
</svg>
|
||||
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { normalizeEdits } from '../lib/edits';
|
||||
import { getBitmap } from '../lib/images';
|
||||
import { Renderer, rotatedBounds } from '../gl/renderer';
|
||||
import type { PhotoRecord, Preset } from '../types';
|
||||
|
||||
/**
|
||||
* Preset thumbnails are rendered once per photo/preset pair and cached as small
|
||||
* JPEG data URLs. One shared Renderer does all of them: a WebGL context per tile
|
||||
* would exhaust the browser's context limit long before 70 presets.
|
||||
*/
|
||||
const cache = new Map<string, string>();
|
||||
const CACHE_LIMIT = 900;
|
||||
const THUMB_EDGE = 200;
|
||||
|
||||
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
|
||||
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
|
||||
|
||||
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
|
||||
const [thumbs, setThumbs] = useState<Record<string, string>>({});
|
||||
// Preset edits never change after creation, so a stable id list is enough to
|
||||
// avoid re-running for every parent render.
|
||||
const presetKey = presets.map((p) => p.id).join('|');
|
||||
const crop = photo.edits.crop;
|
||||
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
let renderer: Renderer | null = null;
|
||||
const canvas = document.createElement('canvas');
|
||||
|
||||
const known: Record<string, string> = {};
|
||||
for (const preset of presets) {
|
||||
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
|
||||
if (hit) known[preset.id] = hit;
|
||||
}
|
||||
setThumbs(known);
|
||||
|
||||
const pending = presets.filter((p) => !known[p.id]);
|
||||
if (!pending.length) return;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const bitmap = await getBitmap(photo);
|
||||
if (!alive) return;
|
||||
renderer = new Renderer(canvas);
|
||||
// Every tile shows the photo as it is framed now, so a turned photo's
|
||||
// presets are turned too.
|
||||
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
|
||||
const cropW = Math.max(1, frame.w * crop.w);
|
||||
const cropH = Math.max(1, frame.h * crop.h);
|
||||
const scale = THUMB_EDGE / Math.max(cropW, cropH);
|
||||
const width = Math.max(1, Math.round(cropW * scale));
|
||||
const height = Math.max(1, Math.round(cropH * scale));
|
||||
renderer.setImage(bitmap);
|
||||
|
||||
for (const preset of pending) {
|
||||
if (!alive) break;
|
||||
try {
|
||||
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
|
||||
width,
|
||||
height,
|
||||
upscale: Math.max(width / cropW, height / cropH) > 1.05,
|
||||
});
|
||||
const url = canvas.toDataURL('image/jpeg', 0.72);
|
||||
cache.set(keyOf(photo.id, preset.id, cropKey), url);
|
||||
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
|
||||
} catch {
|
||||
// One bad preset must not stop the rest of the grid.
|
||||
}
|
||||
// Yield between tiles so the panel fills in progressively.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
if (cache.size > CACHE_LIMIT) {
|
||||
for (const key of [...cache.keys()].slice(0, cache.size - CACHE_LIMIT)) cache.delete(key);
|
||||
}
|
||||
} catch {
|
||||
// No bitmap yet (raw not synced) or no WebGL: tiles keep their placeholders.
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
alive = false;
|
||||
renderer?.dispose();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [photo.id, presetKey, cropKey]);
|
||||
|
||||
return thumbs;
|
||||
}
|
||||
@@ -0,0 +1,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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { ColorLabel, Flag } from '../types';
|
||||
|
||||
interface Props {
|
||||
value: number;
|
||||
onChange?: (rating: number) => void;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export default function Stars({ value, onChange, size = 'sm', title }: Props) {
|
||||
return (
|
||||
<div className={`stars ${size}`} title={title}>
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
disabled={!onChange}
|
||||
className={`star ${value >= n ? 'on' : ''}`}
|
||||
aria-label={`${n} star${n === 1 ? '' : 's'}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onChange?.(value === n ? 0 : n);
|
||||
}}
|
||||
>
|
||||
★
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FlagButtons({ value, onChange }: { value: Flag; onChange: (flag: Flag) => void }) {
|
||||
return (
|
||||
<div className="flag-buttons">
|
||||
<button
|
||||
className={`flag-btn pick ${value === 'pick' ? 'on' : ''}`}
|
||||
title="Pick (P)"
|
||||
onClick={() => onChange(value === 'pick' ? 'none' : 'pick')}
|
||||
>
|
||||
✓
|
||||
</button>
|
||||
<button
|
||||
className={`flag-btn reject ${value === 'reject' ? 'on' : ''}`}
|
||||
title="Reject (X)"
|
||||
onClick={() => onChange(value === 'reject' ? 'none' : 'reject')}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorSwatches({ value, onChange }: { value: ColorLabel; onChange: (color: ColorLabel) => void }) {
|
||||
return (
|
||||
<div className="color-filter">
|
||||
{(
|
||||
[
|
||||
{ c: 'red' as ColorLabel, hex: '#e05252' },
|
||||
{ c: 'yellow' as ColorLabel, hex: '#e0c04a' },
|
||||
{ c: 'green' as ColorLabel, hex: '#56b268' },
|
||||
{ c: 'blue' as ColorLabel, hex: '#4f86e0' },
|
||||
{ c: 'purple' as ColorLabel, hex: '#9b6ede' },
|
||||
] as const
|
||||
).map(({ c, hex }) => (
|
||||
<button
|
||||
key={c}
|
||||
className={`swatch ${value === c ? 'on' : ''}`}
|
||||
style={{ background: hex }}
|
||||
title={c}
|
||||
onClick={() => onChange(value === c ? '' : c)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,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>
|
||||
);
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
import type { LocalLayer } from '../types';
|
||||
import { MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||
|
||||
/**
|
||||
* Local masks are baked on the CPU into one RGBA texture, one layer per
|
||||
* channel, so the grade shader can apply up to four adjustments in a single
|
||||
* pass. The mask is source-space, which keeps brushes and gradients attached to
|
||||
* the picture through crops, straightening, zoom and lens correction.
|
||||
*/
|
||||
|
||||
export interface PackedMasks {
|
||||
data: Uint8Array;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
/** Only mask geometry invalidates the baked texture; sliders do not. */
|
||||
export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number) {
|
||||
return JSON.stringify({
|
||||
srcW,
|
||||
srcH,
|
||||
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
|
||||
kind: layer.kind,
|
||||
inverted: layer.inverted,
|
||||
feather: layer.feather,
|
||||
brush: layer.brush,
|
||||
linear: layer.linear,
|
||||
radial: layer.radial,
|
||||
raster: layer.raster
|
||||
? {
|
||||
width: layer.raster.width,
|
||||
height: layer.raster.height,
|
||||
hash: rasterHash(layer.raster.data),
|
||||
}
|
||||
: null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
function rasterHash(data: string) {
|
||||
let hash = 2166136261;
|
||||
for (let i = 0; i < data.length; i += 17) {
|
||||
hash ^= data.charCodeAt(i);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return `${data.length}:${hash >>> 0}`;
|
||||
}
|
||||
|
||||
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
||||
const mask = layer.raster;
|
||||
if (!mask) return;
|
||||
try {
|
||||
const binary = atob(mask.data);
|
||||
const small = makeCanvas(mask.width, mask.height);
|
||||
const sctx = small.getContext('2d');
|
||||
if (!sctx) return;
|
||||
const image = sctx.createImageData(mask.width, mask.height);
|
||||
const count = Math.min(binary.length, mask.width * mask.height);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const value = binary.charCodeAt(i) & 255;
|
||||
image.data[i * 4] = 255;
|
||||
image.data[i * 4 + 1] = 255;
|
||||
image.data[i * 4 + 2] = 255;
|
||||
image.data[i * 4 + 3] = value;
|
||||
}
|
||||
sctx.putImageData(image, 0, 0);
|
||||
ctx.imageSmoothingEnabled = true;
|
||||
ctx.imageSmoothingQuality = 'high';
|
||||
ctx.drawImage(small, 0, 0, w, h);
|
||||
} catch {
|
||||
// A corrupted embedded mask leaves the layer empty rather than failing the render.
|
||||
}
|
||||
}
|
||||
|
||||
function makeCanvas(w: number, h: number) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
||||
const { cx, cy, rx, ry } = layer.radial;
|
||||
ctx.save();
|
||||
ctx.translate(cx * w, cy * h);
|
||||
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
|
||||
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
||||
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100));
|
||||
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
|
||||
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 1, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
||||
const { x1, y1, x2, y2 } = layer.linear;
|
||||
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
|
||||
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
}
|
||||
|
||||
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
for (const stroke of layer.brush.strokes) {
|
||||
if (!stroke.points.length) continue;
|
||||
const width = Math.max(1, stroke.size * 2 * w);
|
||||
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
|
||||
ctx.strokeStyle = 'rgba(255,255,255,1)';
|
||||
ctx.fillStyle = 'rgba(255,255,255,1)';
|
||||
ctx.lineWidth = width;
|
||||
if (stroke.points.length === 1) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(stroke.points[0].x * w, stroke.points[0].y * h, width / 2, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
continue;
|
||||
}
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(stroke.points[0].x * w, stroke.points[0].y * h);
|
||||
for (let i = 1; i < stroke.points.length; i++) {
|
||||
ctx.lineTo(stroke.points[i].x * w, stroke.points[i].y * h);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
}
|
||||
|
||||
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
|
||||
const w = 800;
|
||||
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
|
||||
const out = new Uint8Array(w * h * 4);
|
||||
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
|
||||
if (!count) return { data: out, w, h };
|
||||
|
||||
for (let index = 0; index < count; index++) {
|
||||
const layer = layers[index];
|
||||
const canvas = makeCanvas(w, h);
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) continue;
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
|
||||
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h);
|
||||
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h);
|
||||
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h);
|
||||
else drawBrush(ctx, layer, w, h);
|
||||
|
||||
let source = canvas;
|
||||
if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) {
|
||||
const blur = makeCanvas(w, h);
|
||||
const bctx = blur.getContext('2d');
|
||||
if (bctx) {
|
||||
bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`;
|
||||
bctx.drawImage(canvas, 0, 0);
|
||||
source = blur;
|
||||
}
|
||||
}
|
||||
|
||||
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
||||
if (!pixels) continue;
|
||||
const channel = index;
|
||||
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
|
||||
const alpha = pixels[p + 3];
|
||||
out[o + channel] = layer.inverted ? 255 - alpha : alpha;
|
||||
}
|
||||
}
|
||||
|
||||
return { data: out, w, h };
|
||||
}
|
||||
+1739
File diff suppressed because it is too large
Load Diff
Vendored
+83
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* The published package's `types` entry points at a file that is not shipped in
|
||||
* 0.1.3, so declare the small surface we use here.
|
||||
*/
|
||||
declare module '@neoanaloglabkk/lensfun-wasm' {
|
||||
export interface LensfunInitOptions {
|
||||
moduleFactory?: (options?: Record<string, unknown>) => Promise<unknown>;
|
||||
moduleJsUrl?: string;
|
||||
wasmUrl?: string;
|
||||
dataUrl?: string;
|
||||
dbPath?: string;
|
||||
autoInitDb?: boolean;
|
||||
locateFile?: (path: string, prefix: string) => string;
|
||||
}
|
||||
|
||||
export interface LensMatch {
|
||||
handle: number;
|
||||
maker: string;
|
||||
model: string;
|
||||
score: number;
|
||||
minFocal: number;
|
||||
maxFocal: number;
|
||||
minAperture: number;
|
||||
maxAperture: number;
|
||||
cropFactor: number;
|
||||
}
|
||||
|
||||
export interface CameraMatch {
|
||||
maker: string;
|
||||
model: string;
|
||||
variant: string;
|
||||
mount: string;
|
||||
cropFactor: number;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface SearchLensesInput {
|
||||
lensMaker?: string;
|
||||
lensModel: string;
|
||||
cameraMaker?: string;
|
||||
cameraModel?: string;
|
||||
searchFlags?: number;
|
||||
}
|
||||
|
||||
export interface SearchCamerasInput {
|
||||
maker?: string;
|
||||
model?: string;
|
||||
searchFlags?: number;
|
||||
}
|
||||
|
||||
export interface CorrectionInput {
|
||||
lensHandle: number;
|
||||
width: number;
|
||||
height: number;
|
||||
focal: number;
|
||||
crop: number;
|
||||
step?: number;
|
||||
reverse?: boolean;
|
||||
includeTca?: boolean;
|
||||
includeVignetting?: boolean;
|
||||
aperture?: number;
|
||||
distance?: number;
|
||||
}
|
||||
|
||||
export interface CorrectionMaps {
|
||||
gridWidth: number;
|
||||
gridHeight: number;
|
||||
step: number;
|
||||
geometry: Float32Array;
|
||||
tca?: Float32Array;
|
||||
vignetting?: Float32Array;
|
||||
}
|
||||
|
||||
export interface LensfunClient {
|
||||
dispose(): void;
|
||||
searchLenses(input: SearchLensesInput): LensMatch[];
|
||||
searchCameras(input: SearchCamerasInput): CameraMatch[];
|
||||
getAvailableModifications(lensHandle: number, crop: number): number;
|
||||
buildCorrectionMaps(input: CorrectionInput): CorrectionMaps;
|
||||
}
|
||||
|
||||
export function createLensfun(options?: LensfunInitOptions): Promise<LensfunClient>;
|
||||
}
|
||||
+585
@@ -0,0 +1,585 @@
|
||||
import type { EventRecord, PhotoRecord, Preset } from '../types';
|
||||
|
||||
export interface Health {
|
||||
ok: boolean;
|
||||
app: string;
|
||||
version: string;
|
||||
needsSetup: boolean;
|
||||
registrationOpen: boolean;
|
||||
photos: number;
|
||||
bytes: number;
|
||||
storage?: { root: string; custom: boolean };
|
||||
raw: { libraw: boolean; sharp: boolean; formats: string[] };
|
||||
}
|
||||
|
||||
export interface SessionUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export interface UploadResult {
|
||||
raw: boolean;
|
||||
engine?: 'libraw' | 'embedded';
|
||||
width?: number;
|
||||
height?: number;
|
||||
mime?: string;
|
||||
size?: number;
|
||||
previewUrl?: string;
|
||||
thumbUrl?: string;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(path, { credentials: 'same-origin', ...init });
|
||||
} catch {
|
||||
throw new ApiError('Cannot reach the Luminary server', 0);
|
||||
}
|
||||
if (!res.ok) {
|
||||
let message = `Request failed (${res.status})`;
|
||||
try {
|
||||
const body = (await res.json()) as { error?: string };
|
||||
if (body?.error) message = body.error;
|
||||
} catch {
|
||||
/* non-JSON error body */
|
||||
}
|
||||
throw new ApiError(message, res.status);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
function jsonBody(payload: unknown): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns null when the app is running without a server (pure browser library). */
|
||||
export async function getHealth(): Promise<Health | null> {
|
||||
try {
|
||||
const res = await fetch('/api/health', { credentials: 'same-origin' });
|
||||
if (!res.ok) return null;
|
||||
const body = (await res.json()) as Health;
|
||||
return body?.ok ? body : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function register(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
name?: string;
|
||||
invite?: string;
|
||||
inviteToken?: string;
|
||||
}): Promise<SessionUser> {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input));
|
||||
return res.user;
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<SessionUser> {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password }));
|
||||
return res.user;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await request('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function currentUser(): Promise<SessionUser | null> {
|
||||
try {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/me');
|
||||
return res.user;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProofSummary {
|
||||
photoId: string;
|
||||
eventId: string;
|
||||
count: number;
|
||||
clients: string[];
|
||||
comments?: number;
|
||||
approved?: number;
|
||||
changes?: number;
|
||||
}
|
||||
|
||||
export interface SyncPayload {
|
||||
user: SessionUser;
|
||||
events: EventRecord[];
|
||||
photos: PhotoRecord[];
|
||||
presets: Preset[];
|
||||
proofs?: ProofSummary[];
|
||||
}
|
||||
|
||||
export function pullAll(): Promise<SyncPayload> {
|
||||
return request<SyncPayload>('/api/sync');
|
||||
}
|
||||
|
||||
export function pullProofs(): Promise<ProofSummary[]> {
|
||||
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
|
||||
}
|
||||
|
||||
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> {
|
||||
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
|
||||
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
body: file,
|
||||
});
|
||||
}
|
||||
|
||||
export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
|
||||
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(photo),
|
||||
}).then((res) => res.photo);
|
||||
}
|
||||
|
||||
export interface ProofUpload {
|
||||
proofAt: number;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
thumbUrl: string;
|
||||
}
|
||||
|
||||
/** Upload a rendered (edited) proof for the client gallery and owner grid. */
|
||||
export interface DenoiseJob {
|
||||
id: string;
|
||||
key: string;
|
||||
state: 'running' | 'done' | 'error';
|
||||
ms: number | null;
|
||||
error: string | null;
|
||||
url: string | null;
|
||||
/** Reported by a job that found the render already on disk. */
|
||||
cached?: boolean;
|
||||
stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null;
|
||||
}
|
||||
|
||||
/** Starts a server-side denoise job; the work runs off the request thread. */
|
||||
export function startDenoise(photoId: string): Promise<{ jobId: string }> {
|
||||
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' });
|
||||
}
|
||||
|
||||
/** Drops the rendered files for a photo; the next run renders from scratch. */
|
||||
export function clearDenoised(photoId: string): Promise<void> {
|
||||
return request(`/api/photos/${encodeURIComponent(photoId)}/denoised`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function getDenoiseJob(jobId: string): Promise<DenoiseJob> {
|
||||
return request(`/api/denoise/jobs/${encodeURIComponent(jobId)}`);
|
||||
}
|
||||
|
||||
export function pushProof(id: string, jpegBase64: string): Promise<ProofUpload> {
|
||||
return request<ProofUpload>(`/api/photos/${encodeURIComponent(id)}/proof`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ jpeg: jpegBase64 }),
|
||||
});
|
||||
}
|
||||
|
||||
export function deletePhotoRemote(id: string): Promise<void> {
|
||||
return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function pushEvent(event: EventRecord): Promise<EventRecord> {
|
||||
return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(event),
|
||||
}).then((res) => res.event);
|
||||
}
|
||||
|
||||
export function deleteEventRemote(id: string): Promise<void> {
|
||||
return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ proofing api */
|
||||
|
||||
export interface ShareFeedback {
|
||||
kind: 'comment' | 'approved' | 'changes';
|
||||
photoId: string;
|
||||
clientName: string;
|
||||
body?: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface ShareState {
|
||||
token: string | null;
|
||||
picks: { photoId: string; clientName: string }[];
|
||||
feedback?: ShareFeedback[];
|
||||
}
|
||||
|
||||
export interface GalleryComment {
|
||||
id: string;
|
||||
clientName: string;
|
||||
body: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface GalleryPhoto {
|
||||
id: string;
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
takenAt: number | null;
|
||||
thumbUrl: string;
|
||||
previewUrl: string;
|
||||
pickCount: number;
|
||||
mine: boolean;
|
||||
comments: GalleryComment[];
|
||||
reviewStatus: 'approved' | 'changes' | null;
|
||||
}
|
||||
|
||||
export interface GalleryPayload {
|
||||
event: { name: string; date: number | null; notes: string };
|
||||
photographer: string;
|
||||
photos: GalleryPhoto[];
|
||||
picks: { total: number; clients: number };
|
||||
}
|
||||
|
||||
export function getShare(eventId: string): Promise<ShareState> {
|
||||
return request<ShareState>(`/api/events/${encodeURIComponent(eventId)}/share`);
|
||||
}
|
||||
|
||||
export function createShare(eventId: string): Promise<string> {
|
||||
return request<{ token: string }>(`/api/events/${encodeURIComponent(eventId)}/share`, {
|
||||
method: 'POST',
|
||||
}).then((res) => res.token);
|
||||
}
|
||||
|
||||
export function galleryDownloadUrl(token: string, photoId: string): string {
|
||||
return `/api/galleries/${encodeURIComponent(token)}/photos/${encodeURIComponent(photoId)}/download`;
|
||||
}
|
||||
|
||||
export function galleryDownloadAllUrl(token: string, clientId: string): string {
|
||||
const query = new URLSearchParams({ client: clientId });
|
||||
return `/api/galleries/${encodeURIComponent(token)}/download-all?${query}`;
|
||||
}
|
||||
|
||||
export function revokeShare(eventId: string): Promise<void> {
|
||||
return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/** Public, session-free gallery load. */
|
||||
export function loadGallery(token: string, clientId: string): Promise<GalleryPayload> {
|
||||
const query = new URLSearchParams({ client: clientId });
|
||||
return request<GalleryPayload>(`/api/galleries/${encodeURIComponent(token)}?${query}`);
|
||||
}
|
||||
|
||||
export function setGalleryPick(
|
||||
token: string,
|
||||
input: { photoId: string; picked: boolean; clientId: string; clientName: string },
|
||||
): Promise<void> {
|
||||
return request(`/api/galleries/${encodeURIComponent(token)}/picks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function addGalleryComment(
|
||||
token: string,
|
||||
input: { photoId: string; clientId: string; clientName: string; body: string },
|
||||
): Promise<GalleryComment> {
|
||||
return request<{ comment: GalleryComment }>(`/api/galleries/${encodeURIComponent(token)}/comments`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
}).then((res) => res.comment);
|
||||
}
|
||||
|
||||
export function setGalleryReview(
|
||||
token: string,
|
||||
input: {
|
||||
photoId: string;
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
status: 'approved' | 'changes' | 'none';
|
||||
},
|
||||
): Promise<void> {
|
||||
return request(`/api/galleries/${encodeURIComponent(token)}/reviews`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- admin api */
|
||||
|
||||
export interface AdminUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
disabled: boolean;
|
||||
createdAt: number | null;
|
||||
}
|
||||
|
||||
export interface AdminEvent {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number | null;
|
||||
photos: number;
|
||||
bytes: number;
|
||||
ownerId: string;
|
||||
ownerEmail: string;
|
||||
}
|
||||
|
||||
export interface AdminInvite {
|
||||
token: string;
|
||||
email: string;
|
||||
role: string;
|
||||
status: 'pending' | 'accepted' | 'expired' | 'revoked';
|
||||
createdAt: number | null;
|
||||
expiresAt: number | null;
|
||||
acceptedAt: number | null;
|
||||
acceptedBy: string | null;
|
||||
revokedAt: number | null;
|
||||
}
|
||||
|
||||
export interface InviteInfo {
|
||||
status: AdminInvite['status'];
|
||||
email: string;
|
||||
role: string;
|
||||
expiresAt: number | null;
|
||||
}
|
||||
|
||||
export interface QuotaPlanEvent {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number;
|
||||
photos: string[];
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface QuotaPlanPhoto {
|
||||
id: string;
|
||||
name: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface QuotaPlan {
|
||||
targetBytes: number;
|
||||
usedBytes: number;
|
||||
projectedBytes: number;
|
||||
freedBytes: number;
|
||||
events: QuotaPlanEvent[];
|
||||
photos: QuotaPlanPhoto[];
|
||||
}
|
||||
|
||||
export interface QuotaState {
|
||||
userId: string;
|
||||
limit: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
ratio: number;
|
||||
percent: number;
|
||||
warn: boolean;
|
||||
over: boolean;
|
||||
warnAt: number;
|
||||
pruneAt: number | null;
|
||||
prunePlan: QuotaPlan | null;
|
||||
pruneNotifiedAt: number | null;
|
||||
lastWarningAt: number | null;
|
||||
}
|
||||
|
||||
export interface AdminQuota extends QuotaState {
|
||||
user: AdminUser;
|
||||
plan: QuotaPlan;
|
||||
}
|
||||
|
||||
export interface MailStatus {
|
||||
configured: boolean;
|
||||
source: 'admin' | 'environment' | 'none';
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user: string;
|
||||
from: string;
|
||||
hasPassword: boolean;
|
||||
gmail: boolean;
|
||||
}
|
||||
|
||||
export interface AdminOverview {
|
||||
users: AdminUser[];
|
||||
events: AdminEvent[];
|
||||
invites: AdminInvite[];
|
||||
totals: { users: number; photos: number; bytes: number; pendingInvites: number };
|
||||
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
|
||||
quotas: AdminQuota[];
|
||||
mail: MailStatus;
|
||||
}
|
||||
|
||||
export interface StorageChange {
|
||||
root: string;
|
||||
previous: string;
|
||||
files: number;
|
||||
bytes: number;
|
||||
moved: boolean;
|
||||
photos: number;
|
||||
}
|
||||
|
||||
export function loadInvite(token: string): Promise<InviteInfo> {
|
||||
return request<InviteInfo>(`/api/invites/${encodeURIComponent(token)}`);
|
||||
}
|
||||
|
||||
export function adminCreateInvite(input: {
|
||||
email: string;
|
||||
role: string;
|
||||
days: number;
|
||||
}): Promise<AdminInvite> {
|
||||
return request<{ invite: AdminInvite }>('/api/admin/invites', jsonBody(input)).then(
|
||||
(res) => res.invite,
|
||||
);
|
||||
}
|
||||
|
||||
export function adminRevokeInvite(token: string): Promise<void> {
|
||||
return request(`/api/admin/invites/${encodeURIComponent(token)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function adminOverview(): Promise<AdminOverview> {
|
||||
return request<AdminOverview>('/api/admin/overview');
|
||||
}
|
||||
|
||||
export function adminCreateUser(input: {
|
||||
email: string;
|
||||
name: string;
|
||||
password: string;
|
||||
role: string;
|
||||
}): Promise<AdminUser> {
|
||||
return request<{ user: AdminUser }>('/api/admin/users', jsonBody(input)).then((res) => res.user);
|
||||
}
|
||||
|
||||
export function adminUpdateUser(
|
||||
id: string,
|
||||
patch: { name?: string; role?: string; disabled?: boolean; password?: string },
|
||||
): Promise<AdminUser> {
|
||||
return request<{ user: AdminUser }>(`/api/admin/users/${encodeURIComponent(id)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
}).then((res) => res.user);
|
||||
}
|
||||
|
||||
export function adminDeleteUser(id: string): Promise<void> {
|
||||
return request(`/api/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function adminRenameEvent(id: string, name: string): Promise<void> {
|
||||
return request(`/api/admin/events/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
}
|
||||
|
||||
export function adminDeleteEvent(id: string): Promise<{ photos: number }> {
|
||||
return request<{ photos: number }>(`/api/admin/events/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
export interface CatalogBackup {
|
||||
kind: 'lumenroom-catalog';
|
||||
version: number;
|
||||
generatedAt: number;
|
||||
events: EventRecord[];
|
||||
photos: PhotoRecord[];
|
||||
kv: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function adminRestoreCatalog(
|
||||
catalog: CatalogBackup,
|
||||
): Promise<{ ok: boolean; events: number; photos: number }> {
|
||||
return request('/api/admin/catalog', jsonBody(catalog));
|
||||
}
|
||||
|
||||
export function adminStorage(): Promise<StorageChange & { defaultRoot: string; custom: boolean }> {
|
||||
return request('/api/admin/storage');
|
||||
}
|
||||
|
||||
export function getQuota(): Promise<QuotaState> {
|
||||
return request<QuotaState>('/api/quota');
|
||||
}
|
||||
|
||||
export function adminSetQuota(userId: string, bytes: number): Promise<QuotaState> {
|
||||
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ bytes }),
|
||||
}).then((res) => res.quota);
|
||||
}
|
||||
|
||||
export function adminSchedulePrune(
|
||||
userId: string,
|
||||
): Promise<{ pruneAt: number; plan: QuotaPlan; warningSent: boolean }> {
|
||||
return request(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function adminCancelPrune(userId: string): Promise<QuotaState> {
|
||||
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, {
|
||||
method: 'DELETE',
|
||||
}).then((res) => res.quota);
|
||||
}
|
||||
|
||||
export function adminWarnUser(userId: string): Promise<QuotaState> {
|
||||
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/warn`, {
|
||||
method: 'POST',
|
||||
}).then((res) => res.quota);
|
||||
}
|
||||
|
||||
export function adminGetMail(): Promise<MailStatus> {
|
||||
return request<{ mail: MailStatus }>('/api/admin/mail').then((res) => res.mail);
|
||||
}
|
||||
|
||||
export function adminSaveMail(input: {
|
||||
user: string;
|
||||
appPassword: string;
|
||||
from: string;
|
||||
host?: string;
|
||||
port?: number;
|
||||
}): Promise<MailStatus> {
|
||||
return request<{ mail: MailStatus }>('/api/admin/mail', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
}).then((res) => res.mail);
|
||||
}
|
||||
|
||||
export function adminTestMail(to?: string): Promise<{ ok: boolean; to: string }> {
|
||||
return request('/api/admin/mail/test', jsonBody(to ? { to } : {}));
|
||||
}
|
||||
|
||||
export function adminSetStorage(root: string): Promise<StorageChange> {
|
||||
return request<StorageChange>('/api/admin/storage', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ root }),
|
||||
});
|
||||
}
|
||||
|
||||
export function pushPresets(presets: Preset[]): Promise<void> {
|
||||
return request('/api/presets', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ presets }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Edits } from '../types';
|
||||
import { clamp } from './curves';
|
||||
|
||||
interface Stats {
|
||||
mean: number;
|
||||
p05: number;
|
||||
p95: number;
|
||||
saturation: number;
|
||||
}
|
||||
|
||||
async function analyze(thumb: string): Promise<Stats> {
|
||||
const img = new Image();
|
||||
img.src = thumb;
|
||||
await img.decode();
|
||||
const w = 96;
|
||||
const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas unavailable');
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const { data } = ctx.getImageData(0, 0, w, h);
|
||||
const hist = new Uint32Array(256);
|
||||
let total = 0;
|
||||
let lumaSum = 0;
|
||||
let satSum = 0;
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const r = data[i] / 255;
|
||||
const g = data[i + 1] / 255;
|
||||
const b = data[i + 2] / 255;
|
||||
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
hist[Math.round(l * 255)]++;
|
||||
lumaSum += l;
|
||||
satSum += Math.max(r, g, b) - Math.min(r, g, b);
|
||||
total++;
|
||||
}
|
||||
const percentile = (p: number) => {
|
||||
const target = total * p;
|
||||
let acc = 0;
|
||||
for (let i = 0; i < 256; i++) {
|
||||
acc += hist[i];
|
||||
if (acc >= target) return i / 255;
|
||||
}
|
||||
return 1;
|
||||
};
|
||||
return {
|
||||
mean: lumaSum / total,
|
||||
p05: percentile(0.05),
|
||||
p95: percentile(0.95),
|
||||
saturation: satSum / total,
|
||||
};
|
||||
}
|
||||
|
||||
/** Simple histogram based auto tone, in the spirit of Lightroom's Auto button. */
|
||||
export async function computeAutoEdits(thumb: string): Promise<Partial<Edits>> {
|
||||
try {
|
||||
const s = await analyze(thumb);
|
||||
const mean = clamp(s.mean, 0.03, 0.97);
|
||||
const exposure = clamp(Math.log2(0.46 / mean), -2, 2);
|
||||
return {
|
||||
exposure: Math.round(exposure * 100) / 100,
|
||||
contrast: s.p95 - s.p05 < 0.55 ? 18 : 10,
|
||||
highlights: s.p95 > 0.94 ? -32 : 4,
|
||||
shadows: s.p05 < 0.055 ? 32 : 4,
|
||||
whites: s.p95 > 0.96 ? -8 : 10,
|
||||
blacks: s.p05 < 0.03 ? 6 : -6,
|
||||
vibrance: s.saturation < 0.18 ? 18 : 8,
|
||||
};
|
||||
} catch {
|
||||
return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { RasterMask } from '../types';
|
||||
|
||||
export type AutoMaskKind = 'subject' | 'sky' | 'background';
|
||||
|
||||
/**
|
||||
* On-device mask estimation for the three selections that matter most in an
|
||||
* event edit: the subject, the sky and the background around the subject.
|
||||
*
|
||||
* The estimator works from a downsampled preview. It combines distance from
|
||||
* the border colour (the usual studio/event background) with a centre bias,
|
||||
* saturation and a vertical sky prior. This is intentionally lightweight: it
|
||||
* has no model download and produces a low-resolution raster that the normal
|
||||
* mask pipeline feathers and scales. The output is editable like any brush
|
||||
* mask, so a missed edge can be fixed without another model pass.
|
||||
*/
|
||||
export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Promise<RasterMask> {
|
||||
const width = Math.max(128, Math.min(320, Math.round(bitmap.width / 16)));
|
||||
const height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width)));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new Error('Could not analyse the image for a mask');
|
||||
ctx.drawImage(bitmap, 0, 0, width, height);
|
||||
const image = ctx.getImageData(0, 0, width, height);
|
||||
const data = image.data;
|
||||
const count = width * height;
|
||||
|
||||
const subject = new Float32Array(count);
|
||||
const sky = new Float32Array(count);
|
||||
const border = borderColor(data, width, height);
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
const ny = y / Math.max(1, height - 1);
|
||||
for (let x = 0; x < width; x++) {
|
||||
const i = y * width + x;
|
||||
const o = i * 4;
|
||||
const r = data[o] / 255;
|
||||
const g = data[o + 1] / 255;
|
||||
const b = data[o + 2] / 255;
|
||||
const dist = Math.min(1, Math.sqrt((r - border[0]) ** 2 + (g - border[1]) ** 2 + (b - border[2]) ** 2) / 1.35);
|
||||
const center = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
|
||||
const maxc = Math.max(r, g, b);
|
||||
const minc = Math.min(r, g, b);
|
||||
const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0;
|
||||
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
subject[i] = dist * 0.58 + center * 0.27 + sat * 0.1 + (1 - Math.abs(luma - 0.48)) * 0.05;
|
||||
const blue = Math.max(0, b - (r + g) * 0.5);
|
||||
sky[i] = blue * 2.5 + Math.max(0, luma - 0.4) * 0.5 + (1 - ny) * 0.28 - (1 - sat) * 0.08;
|
||||
}
|
||||
}
|
||||
|
||||
const raw = kind === 'sky' ? sky : subject;
|
||||
const sorted = [...raw].sort((a, b) => a - b);
|
||||
const median = sorted[Math.floor(sorted.length * 0.5)] ?? 0;
|
||||
const high = sorted[Math.floor(sorted.length * 0.82)] ?? 1;
|
||||
const threshold = kind === 'sky' ? Math.max(0.35, median) : Math.max(0.36, median + (high - median) * 0.22);
|
||||
const mask = new Uint8Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const on = raw[i] >= threshold;
|
||||
mask[i] = (kind === 'background' ? !on : on) ? 255 : 0;
|
||||
}
|
||||
smooth(mask, width, height);
|
||||
smooth(mask, width, height);
|
||||
|
||||
return { data: encodeBase64(mask), width, height };
|
||||
}
|
||||
|
||||
function borderColor(data: Uint8ClampedArray, width: number, height: number): [number, number, number] {
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let n = 0;
|
||||
const add = (x: number, y: number) => {
|
||||
const o = (y * width + x) * 4;
|
||||
r += data[o];
|
||||
g += data[o + 1];
|
||||
b += data[o + 2];
|
||||
n++;
|
||||
};
|
||||
for (let x = 0; x < width; x++) {
|
||||
add(x, 0);
|
||||
add(x, height - 1);
|
||||
}
|
||||
for (let y = 1; y < height - 1; y++) {
|
||||
add(0, y);
|
||||
add(width - 1, y);
|
||||
}
|
||||
return [r / n / 255, g / n / 255, b / n / 255];
|
||||
}
|
||||
|
||||
function smooth(mask: Uint8Array, width: number, height: number) {
|
||||
const copy = new Uint8Array(mask);
|
||||
for (let y = 1; y < height - 1; y++) {
|
||||
for (let x = 1; x < width - 1; x++) {
|
||||
const i = y * width + x;
|
||||
let sum = 0;
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) sum += copy[i + dy * width + dx];
|
||||
}
|
||||
mask[i] = sum / 9 >= 128 ? 255 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function encodeBase64(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
const chunk = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Tracks the "hold Ctrl while dragging Exposure" clipping preview.
|
||||
*
|
||||
* The slider starts a session on pointer down; the overlay follows the
|
||||
* modifier key for as long as the drag lasts, so Ctrl can be pressed or
|
||||
* released mid-drag. Kept outside React so the pointer listeners are attached
|
||||
* once and the renderer subscription stays cheap.
|
||||
*/
|
||||
|
||||
type Listener = (active: boolean) => void;
|
||||
|
||||
let dragging = false;
|
||||
let active = false;
|
||||
const listeners = new Set<Listener>();
|
||||
|
||||
function emit() {
|
||||
for (const listener of listeners) listener(active);
|
||||
}
|
||||
|
||||
export function clipPreviewActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
export function subscribeClipPreview(listener: Listener) {
|
||||
listeners.add(listener);
|
||||
listener(active);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function beginClipPreview(ctrlHeld: boolean) {
|
||||
dragging = true;
|
||||
active = Boolean(ctrlHeld);
|
||||
emit();
|
||||
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Control' && e.key !== 'Meta') return;
|
||||
active = dragging && e.type === 'keydown';
|
||||
emit();
|
||||
};
|
||||
|
||||
const stop = () => {
|
||||
dragging = false;
|
||||
active = false;
|
||||
emit();
|
||||
window.removeEventListener('keydown', onKey, true);
|
||||
window.removeEventListener('keyup', onKey, true);
|
||||
window.removeEventListener('pointerup', stop, true);
|
||||
window.removeEventListener('pointercancel', stop, true);
|
||||
window.removeEventListener('blur', stop);
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
window.addEventListener('keyup', onKey, true);
|
||||
window.addEventListener('pointerup', stop, true);
|
||||
window.addEventListener('pointercancel', stop, true);
|
||||
window.addEventListener('blur', stop);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { CurvePoint } from '../types';
|
||||
|
||||
export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
export const clamp01 = (v: number) => clamp(v, 0, 1);
|
||||
export const round2 = (v: number) => Math.round(v * 100) / 100;
|
||||
|
||||
export type CurveSampler = (x: number) => number;
|
||||
|
||||
/** Monotone cubic (Fritsch-Carlson) interpolation through normalized curve points. */
|
||||
export function buildSampler(input: CurvePoint[]): CurveSampler {
|
||||
const pts = [...input].sort((a, b) => a.x - b.x);
|
||||
if (pts.length < 2) return (x: number) => clamp01(x);
|
||||
const xs = pts.map((p) => clamp01(p.x));
|
||||
const ys = pts.map((p) => clamp01(p.y));
|
||||
const n = xs.length;
|
||||
|
||||
const d: number[] = [];
|
||||
for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / Math.max(1e-6, xs[i + 1] - xs[i]));
|
||||
|
||||
const m: number[] = new Array(n);
|
||||
m[0] = d[0];
|
||||
m[n - 1] = d[n - 2];
|
||||
for (let i = 1; i < n - 1; i++) {
|
||||
if (d[i - 1] * d[i] <= 0) m[i] = 0;
|
||||
else m[i] = (d[i - 1] + d[i]) / 2;
|
||||
}
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
if (d[i] === 0) {
|
||||
m[i] = 0;
|
||||
m[i + 1] = 0;
|
||||
continue;
|
||||
}
|
||||
const a = m[i] / d[i];
|
||||
const b = m[i + 1] / d[i];
|
||||
const s = a * a + b * b;
|
||||
if (s > 9) {
|
||||
const t = 3 / Math.sqrt(s);
|
||||
m[i] = t * a * d[i];
|
||||
m[i + 1] = t * b * d[i];
|
||||
}
|
||||
}
|
||||
|
||||
return (x: number) => {
|
||||
if (x <= xs[0]) return clamp01(ys[0] + (x - xs[0]) * m[0]);
|
||||
if (x >= xs[n - 1]) return clamp01(ys[n - 1] + (x - xs[n - 1]) * m[n - 1]);
|
||||
let i = 0;
|
||||
while (i < n - 2 && x > xs[i + 1]) i++;
|
||||
const h = xs[i + 1] - xs[i];
|
||||
const t = (x - xs[i]) / h;
|
||||
const t2 = t * t;
|
||||
const t3 = t2 * t;
|
||||
const h00 = 2 * t3 - 3 * t2 + 1;
|
||||
const h10 = t3 - 2 * t2 + t;
|
||||
const h01 = -2 * t3 + 3 * t2;
|
||||
const h11 = t3 - t2;
|
||||
return clamp01(h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]);
|
||||
};
|
||||
}
|
||||
|
||||
export function sanitizeCurve(input: unknown): CurvePoint[] {
|
||||
const fallback: CurvePoint[] = [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
];
|
||||
if (!Array.isArray(input)) return fallback;
|
||||
const pts = input
|
||||
.filter((p): p is CurvePoint => !!p && typeof p.x === 'number' && typeof p.y === 'number')
|
||||
.map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) }))
|
||||
.sort((a, b) => a.x - b.x);
|
||||
return pts.length >= 2 ? pts : fallback;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { EventRecord, PhotoRecord } from '../types';
|
||||
|
||||
const DB_NAME = 'lumenroom';
|
||||
const DB_VERSION = 1;
|
||||
|
||||
let dbPromise: Promise<IDBDatabase> | null = null;
|
||||
|
||||
export function openDB(): Promise<IDBDatabase> {
|
||||
if (dbPromise) return dbPromise;
|
||||
dbPromise = new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onupgradeneeded = () => {
|
||||
const db = req.result;
|
||||
if (!db.objectStoreNames.contains('photos')) {
|
||||
const store = db.createObjectStore('photos', { keyPath: 'id' });
|
||||
store.createIndex('eventId', 'eventId', { unique: false });
|
||||
}
|
||||
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
|
||||
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
|
||||
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
|
||||
};
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
|
||||
});
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
function wrap<T>(request: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));
|
||||
});
|
||||
}
|
||||
|
||||
async function store(name: string, mode: IDBTransactionMode = 'readonly') {
|
||||
const db = await openDB();
|
||||
return db.transaction(name, mode).objectStore(name);
|
||||
}
|
||||
|
||||
export async function getAllPhotos(): Promise<PhotoRecord[]> {
|
||||
return wrap((await store('photos')).getAll() as IDBRequest<PhotoRecord[]>);
|
||||
}
|
||||
|
||||
export async function putPhoto(photo: PhotoRecord): Promise<void> {
|
||||
await wrap((await store('photos', 'readwrite')).put(photo));
|
||||
}
|
||||
|
||||
export async function deletePhotoRecord(id: string): Promise<void> {
|
||||
const db = await openDB();
|
||||
const tx = db.transaction(['photos', 'assets'], 'readwrite');
|
||||
tx.objectStore('photos').delete(id);
|
||||
tx.objectStore('assets').delete(id);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function putAsset(id: string, blob: Blob): Promise<void> {
|
||||
await wrap((await store('assets', 'readwrite')).put(blob, id));
|
||||
}
|
||||
|
||||
export async function getAsset(id: string): Promise<Blob | undefined> {
|
||||
return wrap((await store('assets')).get(id) as IDBRequest<Blob | undefined>);
|
||||
}
|
||||
|
||||
export async function getAllEvents(): Promise<EventRecord[]> {
|
||||
return wrap((await store('events')).getAll() as IDBRequest<EventRecord[]>);
|
||||
}
|
||||
|
||||
export async function putEvent(event: EventRecord): Promise<void> {
|
||||
await wrap((await store('events', 'readwrite')).put(event));
|
||||
}
|
||||
|
||||
export async function deleteEventRecord(id: string): Promise<void> {
|
||||
await wrap((await store('events', 'readwrite')).delete(id));
|
||||
}
|
||||
|
||||
export async function getKV<T>(key: string): Promise<T | undefined> {
|
||||
return wrap((await store('kv')).get(key) as IDBRequest<T | undefined>);
|
||||
}
|
||||
|
||||
export async function setKV(key: string, value: unknown): Promise<void> {
|
||||
await wrap((await store('kv', 'readwrite')).put(value, key));
|
||||
}
|
||||
|
||||
export async function estimateUsage(): Promise<{ usage: number; quota: number }> {
|
||||
if (!navigator.storage?.estimate) return { usage: 0, quota: 0 };
|
||||
const est = await navigator.storage.estimate();
|
||||
return { usage: est.usage ?? 0, quota: est.quota ?? 0 };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Drag payloads live in a module variable because browsers only expose
|
||||
* `dataTransfer.getData` on drop, not during dragover — and we need to know
|
||||
* whether a photo (rather than an OS file) is being dragged while hovering.
|
||||
*/
|
||||
|
||||
let photoIds: string[] = [];
|
||||
let eventId: string | null = null;
|
||||
|
||||
export const PHOTO_DRAG = 'application/x-lumen-photos';
|
||||
export const EVENT_DRAG = 'application/x-lumen-event';
|
||||
|
||||
export function startPhotoDrag(ids: string[]) {
|
||||
photoIds = ids;
|
||||
eventId = null;
|
||||
}
|
||||
|
||||
export function draggedPhotoIds(): string[] {
|
||||
return photoIds;
|
||||
}
|
||||
|
||||
export function startEventDrag(id: string) {
|
||||
eventId = id;
|
||||
photoIds = [];
|
||||
}
|
||||
|
||||
export function draggedEventId(): string | null {
|
||||
return eventId;
|
||||
}
|
||||
|
||||
export function endDrag() {
|
||||
photoIds = [];
|
||||
eventId = null;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultEdits, defaultLocalLayer } from './edits';
|
||||
import { applyEditSections } from './editSections';
|
||||
import { autoNoiseFor } from './noiseProfile';
|
||||
|
||||
describe('applyEditSections', () => {
|
||||
it('copies only the selected panel groups', () => {
|
||||
const source = defaultEdits();
|
||||
source.exposure = 1.25;
|
||||
source.saturation = 18;
|
||||
source.crop = { ...source.crop, x: 0.1, w: 0.7 };
|
||||
const target = defaultEdits();
|
||||
target.crop = { ...target.crop, x: 0.4, w: 0.2 };
|
||||
|
||||
const next = applyEditSections(source, target, ['light']);
|
||||
|
||||
expect(next.exposure).toBe(1.25);
|
||||
expect(next.saturation).toBe(18);
|
||||
expect(next.crop.x).toBe(0.4);
|
||||
expect(next.crop.w).toBe(0.2);
|
||||
});
|
||||
|
||||
it('does not mutate either edit record', () => {
|
||||
const source = defaultEdits();
|
||||
source.exposure = 2;
|
||||
const target = defaultEdits();
|
||||
applyEditSections(source, target, ['light']);
|
||||
expect(source.exposure).toBe(2);
|
||||
expect(target.exposure).toBe(0);
|
||||
});
|
||||
|
||||
it('can copy crop and local masks separately', () => {
|
||||
const source = defaultEdits();
|
||||
source.crop = { ...source.crop, angle: 4.5 };
|
||||
source.local = [
|
||||
{
|
||||
...defaultLocalLayer('radial', 0),
|
||||
id: 'mask-1',
|
||||
name: 'Face',
|
||||
},
|
||||
];
|
||||
const target = defaultEdits();
|
||||
const cropped = applyEditSections(source, target, ['crop']);
|
||||
expect(cropped.crop.angle).toBe(4.5);
|
||||
expect(cropped.local).toHaveLength(0);
|
||||
|
||||
const masked = applyEditSections(source, target, ['local']);
|
||||
expect(masked.local[0].name).toBe('Face');
|
||||
expect(masked.crop.angle).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('autoNoiseFor', () => {
|
||||
it('raises luminance and chroma smoothing with ISO', () => {
|
||||
const low = autoNoiseFor({ iso: 100 });
|
||||
const high = autoNoiseFor({ iso: 6400 });
|
||||
expect(high.luminance).toBeGreaterThan(low.luminance);
|
||||
expect(high.chroma).toBeGreaterThan(low.chroma);
|
||||
expect(high.detail).toBeLessThanOrEqual(low.detail);
|
||||
});
|
||||
|
||||
it('keeps every slider inside the editor range', () => {
|
||||
const noise = autoNoiseFor({ iso: 204800 });
|
||||
expect(noise.luminance).toBeGreaterThanOrEqual(0);
|
||||
expect(noise.luminance).toBeLessThanOrEqual(100);
|
||||
expect(noise.chroma).toBeGreaterThanOrEqual(0);
|
||||
expect(noise.chroma).toBeLessThanOrEqual(100);
|
||||
expect(noise.detail).toBeGreaterThanOrEqual(0);
|
||||
expect(noise.chromaDetail).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { Edits } from '../types';
|
||||
|
||||
export type EditSectionId =
|
||||
| 'light'
|
||||
| 'color'
|
||||
| 'detail'
|
||||
| 'effects'
|
||||
| 'geometry'
|
||||
| 'lens'
|
||||
| 'crop'
|
||||
| 'healing'
|
||||
| 'local';
|
||||
|
||||
export interface EditSection {
|
||||
id: EditSectionId;
|
||||
label: string;
|
||||
hint: string;
|
||||
/** applied by default when pasting or syncing */
|
||||
defaultOn: boolean;
|
||||
}
|
||||
|
||||
/** The copy/paste contract is deliberately grouped the way the panels are. */
|
||||
export const EDIT_SECTIONS: EditSection[] = [
|
||||
{
|
||||
id: 'light',
|
||||
label: 'Light & tone',
|
||||
hint: 'White balance, exposure, tone, presence',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'color',
|
||||
label: 'Color',
|
||||
hint: 'Curves, HSL, grading, black & white',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'detail',
|
||||
label: 'Detail',
|
||||
hint: 'Sharpening, noise reduction, defringe',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'effects',
|
||||
label: 'Effects',
|
||||
hint: 'Vignette and grain',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'geometry',
|
||||
label: 'Geometry',
|
||||
hint: 'Perspective, rotation and scale',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'lens',
|
||||
label: 'Lens profile',
|
||||
hint: 'Lensfun profile and correction switches',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'crop',
|
||||
label: 'Crop & orientation',
|
||||
hint: 'Crop, straighten, rotation and flips',
|
||||
defaultOn: false,
|
||||
},
|
||||
{
|
||||
id: 'healing',
|
||||
label: 'Spot healing',
|
||||
hint: 'Healing spots and source points',
|
||||
defaultOn: false,
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
label: 'Local masks',
|
||||
hint: 'Brush, gradient and auto-mask layers',
|
||||
defaultOn: false,
|
||||
},
|
||||
];
|
||||
|
||||
const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
|
||||
light: [
|
||||
'temp',
|
||||
'tint',
|
||||
'exposure',
|
||||
'recovery',
|
||||
'contrast',
|
||||
'highlights',
|
||||
'shadows',
|
||||
'whites',
|
||||
'blacks',
|
||||
'texture',
|
||||
'clarity',
|
||||
'dehaze',
|
||||
'vibrance',
|
||||
'saturation',
|
||||
],
|
||||
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'parametric', 'hsl', 'grading'],
|
||||
detail: ['sharpen', 'noise', 'defringe'],
|
||||
effects: ['vignette', 'grain', 'proof'],
|
||||
geometry: ['geometry'],
|
||||
lens: ['lens'],
|
||||
crop: ['crop'],
|
||||
healing: ['heal'],
|
||||
local: ['local'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Merge selected sections of one photo's edits into another.
|
||||
*
|
||||
* The source is never mutated. Nested groups are copied as whole values, which
|
||||
* mirrors the checkboxes: choosing "Color" brings the curves, HSL and grading
|
||||
* together, not half of each.
|
||||
*/
|
||||
export function applyEditSections(source: Edits, target: Edits, sections: EditSectionId[]): Edits {
|
||||
const next: Edits = { ...target };
|
||||
for (const section of sections) {
|
||||
for (const key of GROUPS[section]) {
|
||||
(next as unknown as Record<string, unknown>)[key] = source[key];
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function defaultSections(): EditSectionId[] {
|
||||
return EDIT_SECTIONS.filter((section) => section.defaultOn).map((section) => section.id);
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
import type {
|
||||
BwFilter,
|
||||
ColorLabel,
|
||||
CropState,
|
||||
CurvePoint,
|
||||
Edits,
|
||||
Flag,
|
||||
HealSpot,
|
||||
LocalLayer,
|
||||
LocalMaskKind,
|
||||
LocalPoint,
|
||||
LocalStroke,
|
||||
LensCorrections,
|
||||
LensProfile,
|
||||
RasterMask,
|
||||
PhotoRecord,
|
||||
PhotoMeta,
|
||||
} from '../types';
|
||||
import { clamp, clamp01, sanitizeCurve } from './curves';
|
||||
|
||||
export interface HueBand {
|
||||
key: string;
|
||||
name: string;
|
||||
center: number;
|
||||
swatch: string;
|
||||
}
|
||||
|
||||
export const HUE_BANDS: HueBand[] = [
|
||||
{ key: 'red', name: 'Red', center: 0, swatch: '#e2453c' },
|
||||
{ key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' },
|
||||
{ key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' },
|
||||
{ key: 'green', name: 'Green', center: 120, swatch: '#57a95a' },
|
||||
{ key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' },
|
||||
{ key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' },
|
||||
{ key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' },
|
||||
{ key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Photographic contrast filters for black & white: transmission per channel.
|
||||
* A red filter passes red and blocks blue, so skies print almost black.
|
||||
*/
|
||||
export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [
|
||||
{ id: 'none', label: 'None', rgb: [1, 1, 1] },
|
||||
{ id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] },
|
||||
{ id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] },
|
||||
{ id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] },
|
||||
{ id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] },
|
||||
{ id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] },
|
||||
];
|
||||
|
||||
export function bwFilterRgb(id: BwFilter): [number, number, number] {
|
||||
return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS transform that shows a grid thumbnail in the photo's *current* orientation.
|
||||
* Uses the same order as the renderer: flips act on the photo, then the quarter
|
||||
* turns and straighten rotate it, and the result is scaled so the rotated image
|
||||
* still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps).
|
||||
*/
|
||||
export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
|
||||
const { quarter, angle, flipH, flipV } = photo.edits.crop;
|
||||
const deg = quarter * 90 + angle;
|
||||
if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none';
|
||||
|
||||
const w = Math.max(1, photo.width || 1);
|
||||
const h = Math.max(1, photo.height || 1);
|
||||
const boxH = 1 / boxAspect;
|
||||
// object-fit: cover — the photo already fills the card before any transform.
|
||||
const cover = Math.max(1 / w, boxH / h);
|
||||
const dw = w * cover;
|
||||
const dh = h * cover;
|
||||
const rad = (Math.abs(deg) * Math.PI) / 180;
|
||||
const c = Math.abs(Math.cos(rad));
|
||||
const s = Math.abs(Math.sin(rad));
|
||||
// A rotated photo has to contain all four corners of the card, not just its
|
||||
// bounding box: after un-rotating a card corner by -deg it sits at
|
||||
// ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide
|
||||
// and tall. Fitting the bounding box instead leaves gaps on angle-only turns.
|
||||
const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh);
|
||||
// A thumbnail's rounded pixel size can differ from the record's ratio by a
|
||||
// fraction of a percent; a hair of slack keeps it from showing a sliver at
|
||||
// the edge. It is invisible at any real card size.
|
||||
const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit;
|
||||
|
||||
const parts = [`rotate(${deg.toFixed(2)}deg)`];
|
||||
// Round up: rounding the scale down would leave a hairline gap at the edge.
|
||||
const rounded = Math.ceil(fit * 1e4) / 1e4;
|
||||
if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`);
|
||||
if (flipH) parts.push('scaleX(-1)');
|
||||
if (flipV) parts.push('scaleY(-1)');
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/** The shader carries a fixed spot array; more than this would silently drop. */
|
||||
export const MAX_HEAL_SPOTS = 24;
|
||||
|
||||
/** Four masks are packed into one RGBA texture. */
|
||||
export const MAX_LOCAL_LAYERS = 4;
|
||||
|
||||
export function defaultLocalAdjust(): LocalLayer['adjust'] {
|
||||
return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, temp: 0, tint: 0, saturation: 0 };
|
||||
}
|
||||
|
||||
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
|
||||
return {
|
||||
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
name: `Local ${index + 1}`,
|
||||
kind,
|
||||
inverted: false,
|
||||
feather: 50,
|
||||
brush: { strokes: [] },
|
||||
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
|
||||
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
|
||||
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
|
||||
adjust: defaultLocalAdjust(),
|
||||
};
|
||||
}
|
||||
|
||||
export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [
|
||||
{ id: 'original', label: 'Original', ratio: null },
|
||||
{ id: 'free', label: 'Free', ratio: null },
|
||||
{ id: '1:1', label: '1 × 1', ratio: 1 },
|
||||
{ id: '4:5', label: '4 × 5', ratio: 4 / 5 },
|
||||
{ id: '5:4', label: '5 × 4', ratio: 5 / 4 },
|
||||
{ id: '4:3', label: '4 × 3', ratio: 4 / 3 },
|
||||
{ id: '3:2', label: '3 × 2', ratio: 3 / 2 },
|
||||
{ id: '16:9', label: '16 × 9', ratio: 16 / 9 },
|
||||
{ id: '2:1', label: '2 × 1', ratio: 2 },
|
||||
{ id: '9:16', label: '9 × 16', ratio: 9 / 16 },
|
||||
];
|
||||
|
||||
export function defaultCrop(): CropState {
|
||||
return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false };
|
||||
}
|
||||
|
||||
export function identityCurve(): CurvePoint[] {
|
||||
return [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
];
|
||||
}
|
||||
|
||||
export function defaultEdits(): Edits {
|
||||
return {
|
||||
temp: 0,
|
||||
tint: 0,
|
||||
exposure: 0,
|
||||
recovery: 0,
|
||||
contrast: 0,
|
||||
highlights: 0,
|
||||
shadows: 0,
|
||||
whites: 0,
|
||||
blacks: 0,
|
||||
texture: 0,
|
||||
clarity: 0,
|
||||
dehaze: 0,
|
||||
vibrance: 0,
|
||||
saturation: 0,
|
||||
bw: false,
|
||||
bwFilter: 'none',
|
||||
bwFilterAmount: 100,
|
||||
curve: {
|
||||
rgb: identityCurve(),
|
||||
red: identityCurve(),
|
||||
green: identityCurve(),
|
||||
blue: identityCurve(),
|
||||
},
|
||||
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
|
||||
hsl: {
|
||||
hue: HUE_BANDS.map(() => 0),
|
||||
sat: HUE_BANDS.map(() => 0),
|
||||
lum: HUE_BANDS.map(() => 0),
|
||||
},
|
||||
grading: {
|
||||
shadows: { h: 210, s: 0 },
|
||||
highlights: { h: 45, s: 0 },
|
||||
balance: 0,
|
||||
},
|
||||
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
|
||||
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
|
||||
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
|
||||
aiDenoise: { amount: 100, key: null, model: 'guided' },
|
||||
defringe: { purple: 0, green: 0 },
|
||||
heal: [],
|
||||
local: [],
|
||||
geometry: { distortion: 0, vertical: 0, horizontal: 0, rotate: 0, scale: 100 },
|
||||
vignette: { amount: 0, midpoint: 50, feather: 50 },
|
||||
grain: { amount: 0, size: 25, roughness: 50 },
|
||||
crop: defaultCrop(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Keeps stored spots inside the image and caps the count the shader accepts. */
|
||||
function healSpots(input: unknown): HealSpot[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const spots: HealSpot[] = [];
|
||||
for (const raw of input.slice(0, MAX_HEAL_SPOTS)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const s = raw as Partial<HealSpot>;
|
||||
const x = clamp01(num(s.x, 0.5, 0, 1));
|
||||
const y = clamp01(num(s.y, 0.5, 0, 1));
|
||||
spots.push({
|
||||
x,
|
||||
y,
|
||||
r: num(s.r, 0.02, 0.001, 0.35),
|
||||
feather: num(s.feather, 50, 0, 100),
|
||||
sx: clamp01(num(s.sx, x + 0.05, 0, 1)),
|
||||
sy: clamp01(num(s.sy, y, 0, 1)),
|
||||
});
|
||||
}
|
||||
return spots;
|
||||
}
|
||||
|
||||
function clampPoint(input: unknown, fallback: LocalPoint): LocalPoint {
|
||||
if (!input || typeof input !== 'object') return fallback;
|
||||
const p = input as Partial<LocalPoint>;
|
||||
return { x: clamp01(num(p.x, fallback.x, 0, 1)), y: clamp01(num(p.y, fallback.y, 0, 1)) };
|
||||
}
|
||||
|
||||
function localStrokes(input: unknown): LocalStroke[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const out: LocalStroke[] = [];
|
||||
for (const raw of input.slice(-300)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const stroke = raw as Partial<LocalStroke>;
|
||||
if (!Array.isArray(stroke.points) || !stroke.points.length) continue;
|
||||
const points = stroke.points
|
||||
.slice(-4000)
|
||||
.map((p) => clampPoint(p, { x: 0.5, y: 0.5 }));
|
||||
out.push({
|
||||
points,
|
||||
size: num(stroke.size, 0.04, 0.002, 0.5),
|
||||
erase: !!stroke.erase,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rasterMask(input: unknown): RasterMask | undefined {
|
||||
if (!input || typeof input !== 'object') return undefined;
|
||||
const raw = input as Partial<RasterMask>;
|
||||
if (typeof raw.data !== 'string' || !raw.data || raw.data.length > 2_000_000) return undefined;
|
||||
const width = Math.round(num(raw.width, 0, 1, 1024));
|
||||
const height = Math.round(num(raw.height, 0, 1, 1024));
|
||||
if (!width || !height) return undefined;
|
||||
return { data: raw.data, width, height };
|
||||
}
|
||||
|
||||
function localLayers(input: unknown): LocalLayer[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const out: LocalLayer[] = [];
|
||||
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const layer = raw as Partial<LocalLayer>;
|
||||
const kind: LocalMaskKind =
|
||||
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
|
||||
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
|
||||
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
|
||||
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>;
|
||||
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>;
|
||||
out.push({
|
||||
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
|
||||
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
|
||||
kind,
|
||||
inverted: !!layer.inverted,
|
||||
feather: num(layer.feather, 50, 0, 100),
|
||||
brush: { strokes: localStrokes(layer.brush?.strokes) },
|
||||
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
|
||||
linear: {
|
||||
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
|
||||
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
|
||||
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
|
||||
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
|
||||
},
|
||||
radial: {
|
||||
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
|
||||
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
|
||||
rx: num(radial.rx, 0.25, 0.01, 1.5),
|
||||
ry: num(radial.ry, 0.3, 0.01, 1.5),
|
||||
},
|
||||
range: {
|
||||
enabled: !!range.enabled,
|
||||
lumaMin: num(range.lumaMin, 0, 0, 100),
|
||||
lumaMax: num(range.lumaMax, 100, 0, 100),
|
||||
hue: num(range.hue, 30, 0, 360),
|
||||
hueRange: num(range.hueRange, 180, 0, 180),
|
||||
satMin: num(range.satMin, 0, 0, 100),
|
||||
},
|
||||
adjust: {
|
||||
exposure: num(adjust.exposure, 0, -4, 4),
|
||||
contrast: num(adjust.contrast, 0, -100, 100),
|
||||
highlights: num(adjust.highlights, 0, -100, 100),
|
||||
shadows: num(adjust.shadows, 0, -100, 100),
|
||||
temp: num(adjust.temp, 0, -100, 100),
|
||||
tint: num(adjust.tint, 0, -100, 100),
|
||||
saturation: num(adjust.saturation, 0, -100, 100),
|
||||
},
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function bands(input: unknown): number[] {
|
||||
const arr = Array.isArray(input) ? input : [];
|
||||
return HUE_BANDS.map((_, i) => {
|
||||
const v = arr[i];
|
||||
return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0;
|
||||
});
|
||||
}
|
||||
|
||||
function num(value: unknown, fallback: number, lo: number, hi: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback;
|
||||
}
|
||||
|
||||
/** Deep-merge stored edits with the current defaults so older records keep working. */
|
||||
function lensProfile(input: unknown): LensProfile | undefined {
|
||||
if (!input || typeof input !== 'object') return undefined;
|
||||
const raw = input as Partial<LensProfile>;
|
||||
if (typeof raw.maker !== 'string' || typeof raw.model !== 'string') return undefined;
|
||||
const maker = raw.maker.trim();
|
||||
const model = raw.model.trim();
|
||||
if (!maker || !model) return undefined;
|
||||
const corrections = raw.corrections as Partial<LensCorrections> | undefined;
|
||||
return {
|
||||
maker,
|
||||
model,
|
||||
crop: num(raw.crop, 1, 0.3, 10),
|
||||
cameraMaker: typeof raw.cameraMaker === 'string' ? raw.cameraMaker : undefined,
|
||||
cameraModel: typeof raw.cameraModel === 'string' ? raw.cameraModel : undefined,
|
||||
corrections: {
|
||||
distortion: corrections?.distortion !== false,
|
||||
tca: corrections?.tca !== false,
|
||||
vignetting: corrections?.vignetting !== false,
|
||||
},
|
||||
distance: num(raw.distance, 1000, 0.1, 100000),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
|
||||
const d = defaultEdits();
|
||||
if (!input) return d;
|
||||
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
|
||||
const parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
|
||||
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
|
||||
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
|
||||
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
|
||||
const aiDenoise = (input.aiDenoise ?? {}) as Partial<Edits['aiDenoise']>;
|
||||
const defringe = (input.defringe ?? {}) as Partial<Edits['defringe']>;
|
||||
const vignette = (input.vignette ?? {}) as Partial<Edits['vignette']>;
|
||||
const grain = (input.grain ?? {}) as Partial<Edits['grain']>;
|
||||
const crop = (input.crop ?? {}) as Partial<CropState>;
|
||||
|
||||
return {
|
||||
...d,
|
||||
...input,
|
||||
aiDenoise: {
|
||||
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
|
||||
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
|
||||
model: 'guided',
|
||||
},
|
||||
temp: num(input.temp, 0, -100, 100),
|
||||
tint: num(input.tint, 0, -100, 100),
|
||||
exposure: num(input.exposure, 0, -5, 5),
|
||||
recovery: num(input.recovery, 0, 0, 100),
|
||||
contrast: num(input.contrast, 0, -100, 100),
|
||||
highlights: num(input.highlights, 0, -100, 100),
|
||||
shadows: num(input.shadows, 0, -100, 100),
|
||||
whites: num(input.whites, 0, -100, 100),
|
||||
blacks: num(input.blacks, 0, -100, 100),
|
||||
texture: num(input.texture, 0, -100, 100),
|
||||
clarity: num(input.clarity, 0, -100, 100),
|
||||
dehaze: num(input.dehaze, 0, -100, 100),
|
||||
vibrance: num(input.vibrance, 0, -100, 100),
|
||||
saturation: num(input.saturation, 0, -100, 100),
|
||||
bw: !!input.bw,
|
||||
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
|
||||
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
|
||||
curve: {
|
||||
rgb: sanitizeCurve(curve.rgb),
|
||||
red: sanitizeCurve(curve.red),
|
||||
green: sanitizeCurve(curve.green),
|
||||
blue: sanitizeCurve(curve.blue),
|
||||
},
|
||||
parametric: {
|
||||
highlights: num(parametric.highlights, 0, -100, 100),
|
||||
lights: num(parametric.lights, 0, -100, 100),
|
||||
darks: num(parametric.darks, 0, -100, 100),
|
||||
blacks: num(parametric.blacks, 0, -100, 100),
|
||||
},
|
||||
hsl: {
|
||||
hue: bands(input.hsl?.hue),
|
||||
sat: bands(input.hsl?.sat),
|
||||
lum: bands(input.hsl?.lum),
|
||||
},
|
||||
grading: {
|
||||
shadows: {
|
||||
h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360),
|
||||
s: num(grading.shadows?.s, 0, 0, 100),
|
||||
},
|
||||
highlights: {
|
||||
h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360),
|
||||
s: num(grading.highlights?.s, 0, 0, 100),
|
||||
},
|
||||
balance: num(grading.balance, 0, -100, 100),
|
||||
},
|
||||
sharpen: {
|
||||
amount: num(sharpen.amount, 0, 0, 150),
|
||||
radius: num(sharpen.radius, 1, 0.5, 3),
|
||||
detail: num(sharpen.detail, 25, 0, 100),
|
||||
mask: num(sharpen.mask, 0, 0, 100),
|
||||
lensSoftness: num(sharpen.lensSoftness, 0, 0, 100),
|
||||
},
|
||||
proof: {
|
||||
enabled: !!input.proof?.enabled,
|
||||
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
|
||||
blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
|
||||
gamut: !!input.proof?.gamut,
|
||||
},
|
||||
noise: {
|
||||
luminance: num(noise.luminance, 0, 0, 100),
|
||||
detail: num(noise.detail, 50, 0, 100),
|
||||
chroma: num(noise.chroma, 0, 0, 100),
|
||||
chromaDetail: num(noise.chromaDetail, 50, 0, 100),
|
||||
},
|
||||
defringe: {
|
||||
purple: num(defringe.purple, 0, 0, 100),
|
||||
green: num(defringe.green, 0, 0, 100),
|
||||
},
|
||||
heal: healSpots(input.heal),
|
||||
local: localLayers(input.local),
|
||||
geometry: {
|
||||
distortion: num(input.geometry?.distortion, 0, -100, 100),
|
||||
vertical: num(input.geometry?.vertical, 0, -100, 100),
|
||||
horizontal: num(input.geometry?.horizontal, 0, -100, 100),
|
||||
rotate: num(input.geometry?.rotate, 0, -15, 15),
|
||||
scale: num(input.geometry?.scale, 100, 50, 200),
|
||||
},
|
||||
lens: lensProfile(input.lens),
|
||||
vignette: {
|
||||
amount: num(vignette.amount, 0, -100, 100),
|
||||
midpoint: num(vignette.midpoint, 50, 0, 100),
|
||||
feather: num(vignette.feather, 50, 0, 100),
|
||||
},
|
||||
grain: {
|
||||
amount: num(grain.amount, 0, 0, 100),
|
||||
size: num(grain.size, 25, 10, 100),
|
||||
roughness: num(grain.roughness, 50, 0, 100),
|
||||
},
|
||||
crop: {
|
||||
x: clamp01(num(crop.x, 0, 0, 1)),
|
||||
y: clamp01(num(crop.y, 0, 0, 1)),
|
||||
w: clamp01(num(crop.w, 1, 0.02, 1)),
|
||||
h: clamp01(num(crop.h, 1, 0.02, 1)),
|
||||
angle: num(crop.angle, 0, -45, 45),
|
||||
quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter)
|
||||
? ((Math.round(crop.quarter) % 4) + 4) % 4
|
||||
: 0,
|
||||
aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original',
|
||||
flipH: !!crop.flipH,
|
||||
flipV: !!crop.flipV,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const editCache = new WeakMap<Edits, boolean>();
|
||||
|
||||
export function isEdited(edits: Edits): boolean {
|
||||
const cached = editCache.get(edits);
|
||||
if (cached !== undefined) return cached;
|
||||
const d = defaultEdits();
|
||||
const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } });
|
||||
const result = strip(edits) !== strip(d);
|
||||
editCache.set(edits, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
|
||||
const edits = normalizeEdits(input.edits);
|
||||
const addedAt = input.addedAt ?? Date.now();
|
||||
const meta: PhotoMeta = input.meta ?? {};
|
||||
return {
|
||||
id: input.id,
|
||||
eventId: input.eventId ?? '',
|
||||
order: typeof input.order === 'number' ? input.order : undefined,
|
||||
raw: !!input.raw,
|
||||
workspace: input.workspace,
|
||||
decode: input.decode,
|
||||
previewUrl: input.previewUrl,
|
||||
thumbUrl: input.thumbUrl,
|
||||
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
|
||||
name: input.name ?? 'Untitled',
|
||||
width: input.width ?? 0,
|
||||
height: input.height ?? 0,
|
||||
size: input.size ?? 0,
|
||||
mime: input.mime ?? 'image/jpeg',
|
||||
addedAt,
|
||||
takenAt: input.takenAt,
|
||||
meta,
|
||||
thumb: input.thumb ?? '',
|
||||
title: typeof input.title === 'string' ? input.title.slice(0, 200) : undefined,
|
||||
caption: typeof input.caption === 'string' ? input.caption.slice(0, 4000) : undefined,
|
||||
creator: typeof input.creator === 'string' ? input.creator.slice(0, 200) : undefined,
|
||||
copyright: typeof input.copyright === 'string' ? input.copyright.slice(0, 300) : undefined,
|
||||
copyOf: typeof input.copyOf === 'string' && input.copyOf ? input.copyOf : undefined,
|
||||
copyName: typeof input.copyName === 'string' && input.copyName ? input.copyName.slice(0, 80) : undefined,
|
||||
snapshots: Array.isArray(input.snapshots)
|
||||
? input.snapshots
|
||||
.filter((s) => s && typeof s === 'object' && typeof s.id === 'string' && typeof s.name === 'string')
|
||||
.slice(-30)
|
||||
.map((s) => ({ id: s.id, name: s.name.slice(0, 40), ts: Number(s.ts) || Date.now(), edits: normalizeEdits(s.edits) }))
|
||||
: undefined,
|
||||
merge: input.merge && (input.merge.kind === 'hdr' || input.merge.kind === 'panorama' || input.merge.kind === 'focus')
|
||||
? { kind: input.merge.kind, sourceIds: Array.isArray(input.merge.sourceIds) ? input.merge.sourceIds : [] }
|
||||
: undefined,
|
||||
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
|
||||
deletedAt: typeof input.deletedAt === 'number' ? input.deletedAt : undefined,
|
||||
stackId: typeof input.stackId === 'string' && input.stackId ? input.stackId : undefined,
|
||||
stackIndex: typeof input.stackIndex === 'number' && Number.isFinite(input.stackIndex)
|
||||
? Math.max(0, Math.round(input.stackIndex))
|
||||
: undefined,
|
||||
flag: (input.flag ?? 'none') as Flag,
|
||||
color: (input.color ?? '') as ColorLabel,
|
||||
keywords: Array.isArray(input.keywords) ? input.keywords : [],
|
||||
edits,
|
||||
history:
|
||||
Array.isArray(input.history) && input.history.length
|
||||
? input.history
|
||||
: [{ label: 'Import', ts: addedAt, edits }],
|
||||
};
|
||||
}
|
||||
|
||||
export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [
|
||||
{ value: 'red', name: 'Red', hex: '#e05252' },
|
||||
{ value: 'yellow', name: 'Yellow', hex: '#e0c04a' },
|
||||
{ value: 'green', name: 'Green', hex: '#56b268' },
|
||||
{ value: 'blue', name: 'Blue', hex: '#4f86e0' },
|
||||
{ value: 'purple', name: 'Purple', hex: '#9b6ede' },
|
||||
];
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { outputSize } from '../gl/renderer';
|
||||
import { defaultEdits } from './edits';
|
||||
|
||||
describe('export output dimensions', () => {
|
||||
it('matches the source for an uncropped image', () => {
|
||||
expect(outputSize(defaultEdits(), 6000, 4000)).toEqual({ w: 6000, h: 4000 });
|
||||
});
|
||||
|
||||
it('swaps dimensions for a quarter turn', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.crop.quarter = 1;
|
||||
expect(outputSize(edits, 6000, 4000)).toEqual({ w: 4000, h: 6000 });
|
||||
});
|
||||
|
||||
it('includes the triangular points added by straightening', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.crop.angle = 45;
|
||||
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 });
|
||||
});
|
||||
|
||||
it('applies the crop after the rotated frame is calculated', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.crop.angle = 45;
|
||||
edits.crop.w = 0.5;
|
||||
edits.crop.h = 0.5;
|
||||
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 2475, h: 2475 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,365 @@
|
||||
import type { Edits, PhotoRecord } from '../types';
|
||||
import { getBitmap } from './images';
|
||||
import { normalizeEdits } from './edits';
|
||||
import { buildLensCorrection } from './lensfun';
|
||||
import { outputSize, Renderer } from '../gl/renderer';
|
||||
import { getDenoisedBitmap } from './images';
|
||||
import { createZipBlob, zipFileName } from './zip';
|
||||
import { srgbProfile } from './icc';
|
||||
import { encodeTiff16 } from './tiff';
|
||||
|
||||
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16';
|
||||
export type ResizeMode = 'none' | 'longEdge' | 'percent';
|
||||
|
||||
export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
|
||||
|
||||
export interface ExportOptions {
|
||||
format: ExportFormat;
|
||||
quality: number;
|
||||
resize: ResizeMode;
|
||||
longEdge: number;
|
||||
percent: number;
|
||||
nameTemplate: string;
|
||||
/** Bundle multiple photos into one downloadable archive. */
|
||||
zip: boolean;
|
||||
/** Extra capture sharpening applied only to the exported pixels. */
|
||||
outputSharpen: number;
|
||||
/** Write title/caption/creator/copyright/keywords into the file. */
|
||||
metadata: boolean;
|
||||
/** Embed the generated sRGB ICC profile in JPEG/TIFF files. */
|
||||
embedProfile: boolean;
|
||||
watermark: {
|
||||
enabled: boolean;
|
||||
text: string;
|
||||
position: WatermarkPosition;
|
||||
opacity: number;
|
||||
size: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ExportRecipe {
|
||||
id: string;
|
||||
name: string;
|
||||
options: ExportOptions;
|
||||
}
|
||||
|
||||
export const DEFAULT_EXPORT: ExportOptions = {
|
||||
format: 'jpeg',
|
||||
quality: 92,
|
||||
resize: 'none',
|
||||
longEdge: 3000,
|
||||
percent: 100,
|
||||
nameTemplate: '{name}',
|
||||
zip: true,
|
||||
outputSharpen: 0,
|
||||
metadata: true,
|
||||
embedProfile: true,
|
||||
watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 },
|
||||
};
|
||||
|
||||
const MIME: Record<ExportFormat, string> = {
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
tiff16: 'image/tiff',
|
||||
};
|
||||
|
||||
const EXT: Record<ExportFormat, string> = {
|
||||
jpeg: 'jpg',
|
||||
png: 'png',
|
||||
webp: 'webp',
|
||||
tiff16: 'tif',
|
||||
};
|
||||
|
||||
function download(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 4000);
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
export function buildFileName(template: string, photo: PhotoRecord, index: number, opts: ExportOptions) {
|
||||
const stamp = new Date(photo.takenAt ?? photo.addedAt);
|
||||
const base = photo.name.replace(/\.[^.]+$/, '') || 'export';
|
||||
const name = (template || '{name}')
|
||||
.replace(/\{name\}/g, base)
|
||||
.replace(/\{date\}/g, `${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}`)
|
||||
.replace(/\{time\}/g, `${pad(stamp.getHours())}${pad(stamp.getMinutes())}`)
|
||||
.replace(/\{index\}/g, String(index + 1).padStart(3, '0'))
|
||||
.replace(/[\\/:*?"<>|]+/g, '-')
|
||||
.trim();
|
||||
return `${name || 'export'}.${EXT[opts.format]}`;
|
||||
}
|
||||
|
||||
function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts: ExportOptions) {
|
||||
const size = outputSize(edits, bitmap.width, bitmap.height);
|
||||
const longEdge = Math.max(size.w, size.h);
|
||||
let scale = 1;
|
||||
if (opts.resize === 'longEdge' && opts.longEdge > 0 && longEdge > opts.longEdge) {
|
||||
scale = opts.longEdge / longEdge;
|
||||
} else if (opts.resize === 'percent') {
|
||||
scale = Math.min(2, Math.max(0.05, opts.percent / 100));
|
||||
}
|
||||
return {
|
||||
w: Math.max(1, Math.round(size.w * scale)),
|
||||
h: Math.max(1, Math.round(size.h * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
|
||||
const bitmap = await getBitmap(photo);
|
||||
const base = normalizeEdits(photo.edits);
|
||||
const edits = opts.outputSharpen > 0
|
||||
? { ...base, sharpen: { ...base.sharpen, amount: Math.min(150, base.sharpen.amount + opts.outputSharpen) } }
|
||||
: base;
|
||||
const { w, h } = targetSize(photo, edits, bitmap, opts);
|
||||
const native = outputSize(edits, bitmap.width, bitmap.height);
|
||||
// Let the shader use its Catmull-Rom path when the crop is being enlarged,
|
||||
// so an intentional 150–200% export does not turn into a bilinear blur.
|
||||
const upscale = w > native.w * 1.05 || h > native.h * 1.05;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
const renderer = new Renderer(canvas);
|
||||
try {
|
||||
renderer.setImage(bitmap);
|
||||
// Forgetting this is how denoise silently goes missing from exports: the
|
||||
// preview and the file would be graded from different pixels.
|
||||
if (edits.aiDenoise.key) {
|
||||
const denoised = await getDenoisedBitmap(photo, edits.aiDenoise.key);
|
||||
renderer.setDenoised(denoised, edits.aiDenoise.amount / 100);
|
||||
}
|
||||
const lens = edits.lens
|
||||
? await buildLensCorrection(edits.lens, { width: bitmap.width, height: bitmap.height, meta: photo.meta })
|
||||
: null;
|
||||
|
||||
if (opts.format === 'tiff16') {
|
||||
if (opts.watermark.enabled && opts.watermark.text.trim()) {
|
||||
throw new Error('Watermarking is not available for 16-bit TIFF exports');
|
||||
}
|
||||
const pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
|
||||
if (!pixels) throw new Error('Could not read the 16-bit render');
|
||||
return encodeTiff16({
|
||||
width: w,
|
||||
height: h,
|
||||
pixels,
|
||||
icc: opts.embedProfile ? srgbProfile() : null,
|
||||
});
|
||||
}
|
||||
|
||||
renderer.render(edits, { width: w, height: h, lens, upscale });
|
||||
renderer.finishGpu();
|
||||
|
||||
let output = canvas;
|
||||
if (opts.watermark.enabled && opts.watermark.text.trim()) {
|
||||
output = paintWatermark(canvas, photo, opts);
|
||||
}
|
||||
const mime = MIME[opts.format];
|
||||
let blob = await new Promise<Blob | null>((resolve) =>
|
||||
output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
|
||||
);
|
||||
if (!blob) throw new Error('Export failed while encoding the image');
|
||||
if (opts.format === 'jpeg') {
|
||||
blob = await embedJpegMetadata(
|
||||
blob,
|
||||
opts.metadata ? buildXmp(photo) : '',
|
||||
opts.embedProfile ? srgbProfile() : null,
|
||||
);
|
||||
}
|
||||
return blob;
|
||||
} finally {
|
||||
renderer.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: ExportOptions) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = source.width;
|
||||
canvas.height = source.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return source;
|
||||
ctx.drawImage(source, 0, 0);
|
||||
const longest = Math.max(canvas.width, canvas.height);
|
||||
const size = Math.max(10, Math.round((longest * opts.watermark.size) / 100));
|
||||
ctx.font = `600 ${size}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
|
||||
ctx.textBaseline = 'middle';
|
||||
const text = opts.watermark.text.trim();
|
||||
const metrics = ctx.measureText(text);
|
||||
const pad = Math.round(size * 0.55);
|
||||
const x =
|
||||
opts.watermark.position === 'bl' || opts.watermark.position === 'tl'
|
||||
? pad
|
||||
: opts.watermark.position === 'center'
|
||||
? (canvas.width - metrics.width) / 2
|
||||
: canvas.width - metrics.width - pad;
|
||||
const y =
|
||||
opts.watermark.position === 'tr' || opts.watermark.position === 'tl'
|
||||
? pad + size / 2
|
||||
: opts.watermark.position === 'center'
|
||||
? canvas.height / 2
|
||||
: canvas.height - pad - size / 2;
|
||||
ctx.globalAlpha = Math.min(1, Math.max(0.05, opts.watermark.opacity / 100));
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.shadowColor = 'rgba(0,0,0,.65)';
|
||||
ctx.shadowBlur = Math.max(1, size * 0.12);
|
||||
ctx.shadowOffsetY = Math.max(1, size * 0.03);
|
||||
ctx.fillText(text, x, y);
|
||||
ctx.globalAlpha = 1;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function xmlEscape(value: string) {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function buildXmp(photo: PhotoRecord) {
|
||||
const title = photo.title || photo.name;
|
||||
const keywords = photo.keywords.map((word) => `<rdf:li>${xmlEscape(word)}</rdf:li>`).join('');
|
||||
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(title)}</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.caption ?? '')}</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>${xmlEscape(photo.creator ?? '')}</rdf:li></rdf:Seq></dc:creator><dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.copyright ?? '')}</rdf:li></rdf:Alt></dc:rights><dc:subject><rdf:Bag>${keywords}</rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(0, 65000);
|
||||
}
|
||||
|
||||
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
|
||||
const length = header.length + payload.length + 2;
|
||||
if (length > 65533) return null;
|
||||
const segment = new Uint8Array(length + 2);
|
||||
segment[0] = 0xff;
|
||||
segment[1] = marker;
|
||||
segment[2] = (length >> 8) & 255;
|
||||
segment[3] = length & 255;
|
||||
segment.set(header, 4);
|
||||
segment.set(payload, 4 + header.length);
|
||||
return segment;
|
||||
}
|
||||
|
||||
async function embedJpegMetadata(blob: Blob, xmp: string, icc: Uint8Array | null): Promise<Blob> {
|
||||
try {
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return blob;
|
||||
const chunks: Uint8Array[] = [bytes.subarray(0, 2)];
|
||||
|
||||
// Insert our own metadata immediately after SOI. Existing ICC APP2 blocks
|
||||
// are dropped below: canvas encoders often add one already, and duplicated
|
||||
// profiles can confuse colour-managed viewers.
|
||||
if (icc) {
|
||||
const header = new TextEncoder().encode('ICC_PROFILE\0');
|
||||
const payload = new Uint8Array(2 + icc.length);
|
||||
payload[0] = 1;
|
||||
payload[1] = 1;
|
||||
payload.set(icc, 2);
|
||||
const segment = appSegment(0xe2, header, payload);
|
||||
if (segment) chunks.push(segment);
|
||||
}
|
||||
if (xmp) {
|
||||
const header = new TextEncoder().encode('http://ns.adobe.com/xap/1.0/\0');
|
||||
const segment = appSegment(0xe1, header, new TextEncoder().encode(xmp));
|
||||
if (segment) chunks.push(segment);
|
||||
}
|
||||
|
||||
let at = 2;
|
||||
while (at + 4 <= bytes.length) {
|
||||
if (bytes[at] !== 0xff) {
|
||||
// Not a marker (or malformed); keep the remaining bytes intact.
|
||||
chunks.push(bytes.subarray(at));
|
||||
at = bytes.length;
|
||||
break;
|
||||
}
|
||||
const marker = bytes[at + 1];
|
||||
if (marker === 0xda) {
|
||||
chunks.push(bytes.subarray(at));
|
||||
at = bytes.length;
|
||||
break;
|
||||
}
|
||||
if (marker === 0xd8 || marker === 0xd9) {
|
||||
chunks.push(bytes.subarray(at, at + 2));
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
const length = (bytes[at + 2] << 8) | bytes[at + 3];
|
||||
const end = at + 2 + length;
|
||||
if (end > bytes.length) {
|
||||
chunks.push(bytes.subarray(at));
|
||||
at = bytes.length;
|
||||
break;
|
||||
}
|
||||
const isIcc =
|
||||
marker === 0xe2 &&
|
||||
bytes.subarray(at + 4, at + 16).every((value, index) => value === 'ICC_PROFILE\0'.charCodeAt(index));
|
||||
if (!isIcc) chunks.push(bytes.subarray(at, end));
|
||||
at = end;
|
||||
}
|
||||
if (at < bytes.length) chunks.push(bytes.subarray(at));
|
||||
return new Blob(chunks as BlobPart[], { type: 'image/jpeg' });
|
||||
} catch {
|
||||
return blob;
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportPhotos(
|
||||
photos: PhotoRecord[],
|
||||
opts: ExportOptions,
|
||||
onProgress?: (done: number, total: number) => void,
|
||||
onStage?: (stage: 'render' | 'pack') => void,
|
||||
): Promise<{ count: number; failed: string[] }> {
|
||||
const bundle = opts.zip && photos.length > 1;
|
||||
const entries: { name: string; data: Blob }[] = [];
|
||||
const failed: string[] = [];
|
||||
let count = 0;
|
||||
|
||||
onStage?.('render');
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
const photo = photos[i];
|
||||
try {
|
||||
const blob = await renderPhotoBlob(photo, opts);
|
||||
const name = buildFileName(opts.nameTemplate, photo, i, opts);
|
||||
if (bundle) entries.push({ name, data: blob });
|
||||
else {
|
||||
download(blob, name);
|
||||
count++;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Export failed for', photo.name, err);
|
||||
failed.push(photo.name);
|
||||
}
|
||||
onProgress?.(i + 1, photos.length);
|
||||
// Give the browser a beat so long batches keep the tab responsive.
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
|
||||
if (bundle && entries.length) {
|
||||
// One good file needs no archive; hand it over directly.
|
||||
if (entries.length === 1) {
|
||||
download(entries[0].data, entries[0].name);
|
||||
count = 1;
|
||||
} else {
|
||||
onStage?.('pack');
|
||||
const archive = await createZipBlob(entries);
|
||||
download(archive, zipFileName());
|
||||
count = entries.length;
|
||||
}
|
||||
}
|
||||
|
||||
return { count, failed };
|
||||
}
|
||||
|
||||
/** Backwards compatible single-photo export. */
|
||||
export async function exportPhoto(photo: PhotoRecord, maxLongEdge = 0): Promise<void> {
|
||||
const opts: ExportOptions = {
|
||||
...DEFAULT_EXPORT,
|
||||
resize: maxLongEdge > 0 ? 'longEdge' : 'none',
|
||||
longEdge: maxLongEdge || DEFAULT_EXPORT.longEdge,
|
||||
};
|
||||
const blob = await renderPhotoBlob(photo, opts);
|
||||
download(blob, buildFileName(opts.nameTemplate, photo, 0, opts));
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { srgbProfile } from './icc';
|
||||
|
||||
describe('sRGB ICC profile', () => {
|
||||
it('is a self-consistent v2 RGB display profile', () => {
|
||||
const profile = srgbProfile();
|
||||
const view = new DataView(profile.buffer);
|
||||
expect(profile.length).toBeGreaterThan(2000);
|
||||
expect(view.getUint32(0, false)).toBe(profile.length);
|
||||
expect(String.fromCharCode(...profile.subarray(36, 40))).toBe('acsp');
|
||||
expect(String.fromCharCode(...profile.subarray(16, 20))).toBe('RGB ');
|
||||
expect(String.fromCharCode(...profile.subarray(20, 24))).toBe('XYZ ');
|
||||
expect(view.getUint32(128, false)).toBeGreaterThan(5);
|
||||
});
|
||||
|
||||
it('carries a readable description for colour-managed viewers', () => {
|
||||
const profile = srgbProfile();
|
||||
const view = new DataView(profile.buffer);
|
||||
const count = view.getUint32(128, false);
|
||||
let descriptionAt = -1;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const at = 132 + index * 12;
|
||||
if (String.fromCharCode(...profile.subarray(at, at + 4)) === 'desc') {
|
||||
descriptionAt = view.getUint32(at + 4, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(descriptionAt).toBeGreaterThan(0);
|
||||
expect(String.fromCharCode(...profile.subarray(descriptionAt, descriptionAt + 4))).toBe('desc');
|
||||
});
|
||||
|
||||
it('uses the sampled sRGB transfer curve rather than gamma 2.2', () => {
|
||||
const profile = srgbProfile();
|
||||
const view = new DataView(profile.buffer);
|
||||
const count = view.getUint32(128, false);
|
||||
let curveAt = -1;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const at = 132 + index * 12;
|
||||
if (String.fromCharCode(...profile.subarray(at, at + 4)) === 'rTRC') {
|
||||
curveAt = view.getUint32(at + 4, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(curveAt).toBeGreaterThan(0);
|
||||
expect(String.fromCharCode(...profile.subarray(curveAt, curveAt + 4))).toBe('curv');
|
||||
expect(view.getUint32(curveAt + 8, false)).toBe(1024);
|
||||
expect(view.getUint16(curveAt + 12, false)).toBe(0);
|
||||
expect(view.getUint16(curveAt + 12 + 2 * 1023, false)).toBe(65535);
|
||||
const midpoint = view.getUint16(curveAt + 12 + 2 * 512, false);
|
||||
expect(midpoint).toBeGreaterThan(13000);
|
||||
expect(midpoint).toBeLessThan(15000);
|
||||
});
|
||||
});
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* A small, self-contained ICC v2 sRGB display profile.
|
||||
*
|
||||
* It is generated rather than shipped as a binary so the export pipeline can
|
||||
* tag sRGB files without adding a third-party profile asset. The matrix and
|
||||
* gamma describe the standard sRGB primaries; the browser already converted
|
||||
* the working pixels into sRGB when it decoded the source image.
|
||||
*/
|
||||
|
||||
let cached: Uint8Array | null = null;
|
||||
|
||||
function be32(out: DataView, offset: number, value: number) {
|
||||
out.setUint32(offset, value >>> 0, false);
|
||||
}
|
||||
|
||||
function be16(out: DataView, offset: number, value: number) {
|
||||
out.setUint16(offset, value & 0xffff, false);
|
||||
}
|
||||
|
||||
function s15(value: number) {
|
||||
return Math.round(value * 65536) >>> 0;
|
||||
}
|
||||
|
||||
function ascii(text: string) {
|
||||
return new TextEncoder().encode(text);
|
||||
}
|
||||
|
||||
function pad4(value: number) {
|
||||
return (value + 3) & ~3;
|
||||
}
|
||||
|
||||
function xyzTag(x: number, y: number, z: number) {
|
||||
const data = new Uint8Array(20);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('XYZ '), 0);
|
||||
be32(view, 8, s15(x));
|
||||
be32(view, 12, s15(y));
|
||||
be32(view, 16, s15(z));
|
||||
return data;
|
||||
}
|
||||
|
||||
function curveTag() {
|
||||
// ICC v2 curveType with the piecewise sRGB transfer function sampled at
|
||||
// 1024 points. A gamma-2.2 shortcut is close, but this is exact to the
|
||||
// standard (within 16-bit quantisation) and still readable by old CMMs.
|
||||
const samples = 1024;
|
||||
const data = new Uint8Array(12 + samples * 2);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('curv'), 0);
|
||||
be32(view, 8, samples);
|
||||
for (let index = 0; index < samples; index++) {
|
||||
const linear = index / (samples - 1);
|
||||
const encoded =
|
||||
linear <= 0.04045
|
||||
? linear / 12.92
|
||||
: ((linear + 0.055) / 1.055) ** 2.4;
|
||||
be16(view, 12 + index * 2, Math.round(encoded * 65535));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function descTag(text: string) {
|
||||
const value = new TextEncoder().encode(text);
|
||||
const size = pad4(12 + value.length + 1 + 4 + 4);
|
||||
const data = new Uint8Array(size);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('desc'), 0);
|
||||
be32(view, 8, value.length + 1);
|
||||
data.set(value, 12);
|
||||
data[12 + value.length] = 0;
|
||||
// Unicode language code and count are both zero.
|
||||
return data;
|
||||
}
|
||||
|
||||
function textTag(text: string) {
|
||||
const value = new TextEncoder().encode(text);
|
||||
const size = pad4(8 + value.length + 1);
|
||||
const data = new Uint8Array(size);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('text'), 0);
|
||||
data.set(value, 8);
|
||||
data[8 + value.length] = 0;
|
||||
return data;
|
||||
}
|
||||
|
||||
export function srgbProfile(): Uint8Array {
|
||||
if (cached) return cached;
|
||||
|
||||
// sRGB primaries adapted to the D50 profile connection space.
|
||||
const tags: { sig: string; data: Uint8Array }[] = [
|
||||
{ sig: 'desc', data: descTag('sRGB IEC61966-2.1 (Luminary)') },
|
||||
{ sig: 'cprt', data: textTag('No copyright, use freely') },
|
||||
{ sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) },
|
||||
{ sig: 'rXYZ', data: xyzTag(0.4360747, 0.2225045, 0.0139322) },
|
||||
{ sig: 'gXYZ', data: xyzTag(0.3850649, 0.7168786, 0.0971045) },
|
||||
{ sig: 'bXYZ', data: xyzTag(0.1430804, 0.0606169, 0.7141733) },
|
||||
{ sig: 'rTRC', data: curveTag() },
|
||||
{ sig: 'gTRC', data: curveTag() },
|
||||
{ sig: 'bTRC', data: curveTag() },
|
||||
];
|
||||
|
||||
const tableSize = 4 + tags.length * 12;
|
||||
let offset = 128 + tableSize;
|
||||
const placed = tags.map((tag) => {
|
||||
offset = pad4(offset);
|
||||
const at = offset;
|
||||
offset += tag.data.length;
|
||||
return { ...tag, at };
|
||||
});
|
||||
const total = pad4(offset);
|
||||
const data = new Uint8Array(total);
|
||||
const view = new DataView(data.buffer);
|
||||
|
||||
// Header. Date is fixed so identical exports have identical profile bytes.
|
||||
be32(view, 0, total);
|
||||
data.set(ascii('LNRM'), 4);
|
||||
be32(view, 8, 0x02100000);
|
||||
data.set(ascii('mntr'), 12);
|
||||
data.set(ascii('RGB '), 16);
|
||||
data.set(ascii('XYZ '), 20);
|
||||
be16(view, 24, 2026);
|
||||
be16(view, 26, 1);
|
||||
be16(view, 28, 1);
|
||||
be16(view, 30, 0);
|
||||
be16(view, 32, 0);
|
||||
be16(view, 34, 0);
|
||||
data.set(ascii('acsp'), 36);
|
||||
be32(view, 40, 0);
|
||||
be32(view, 44, 0);
|
||||
be32(view, 48, 0);
|
||||
be32(view, 52, 0);
|
||||
be32(view, 56, 0);
|
||||
be32(view, 60, 0);
|
||||
be32(view, 64, 0); // perceptual rendering intent
|
||||
be32(view, 68, 0x0000f6d6); // D50 X 0.9642
|
||||
be32(view, 72, 0x00010000); // D50 Y 1.0
|
||||
be32(view, 76, 0x0000d32d); // D50 Z 0.8249
|
||||
data.set(ascii('LNRM'), 80);
|
||||
// bytes 84-127 (profile ID and reserved) remain zero.
|
||||
|
||||
be32(view, 128, placed.length);
|
||||
placed.forEach((tag, index) => {
|
||||
const at = 132 + index * 12;
|
||||
data.set(ascii(tag.sig), at);
|
||||
be32(view, at + 4, tag.at);
|
||||
be32(view, at + 8, tag.data.length);
|
||||
data.set(tag.data, tag.at);
|
||||
});
|
||||
|
||||
cached = data;
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { getAsset, putAsset } from './db';
|
||||
|
||||
const CACHE_LIMIT = 6;
|
||||
const cache = new Map<string, ImageBitmap>();
|
||||
|
||||
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
|
||||
export function remoteAssetUrl(photo: PhotoRecord): string {
|
||||
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
|
||||
return `/api/photos/${encodeURIComponent(photo.id)}/original`;
|
||||
}
|
||||
|
||||
/** Virtual copies reuse the master's bytes when no local copy exists. */
|
||||
async function copyAsset(photo: PhotoRecord, id: string): Promise<Blob | undefined> {
|
||||
const own = await getAsset(photo.id);
|
||||
if (own) {
|
||||
if (photo.copyOf) await putAsset(id, own).catch(() => undefined);
|
||||
return own;
|
||||
}
|
||||
if (!photo.copyOf) return undefined;
|
||||
const master = await getAsset(photo.copyOf);
|
||||
if (master) {
|
||||
await putAsset(id, master).catch(() => undefined);
|
||||
return master;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function fetchRemoteCopy(photo: PhotoRecord): Promise<Blob | null> {
|
||||
const direct = await fetchRemote(photo);
|
||||
if (direct || !photo.copyOf) return direct;
|
||||
// A virtual copy has no server file of its own; ask for the master's proxy.
|
||||
try {
|
||||
const master = { ...photo, id: photo.copyOf, copyOf: undefined };
|
||||
const res = await fetch(remoteAssetUrl(master), { credentials: 'same-origin' });
|
||||
if (!res.ok) return null;
|
||||
const blob = await res.blob();
|
||||
await putAsset(photo.id, blob).catch(() => undefined);
|
||||
return blob;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRemote(photo: PhotoRecord): Promise<Blob | null> {
|
||||
try {
|
||||
const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' });
|
||||
if (!res.ok) return null;
|
||||
const blob = await res.blob();
|
||||
// Cache it locally so the photo keeps working offline after the first look.
|
||||
await putAsset(photo.id, blob).catch(() => undefined);
|
||||
return blob;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
|
||||
const hit = cache.get(photo.id);
|
||||
if (hit) {
|
||||
cache.delete(photo.id);
|
||||
cache.set(photo.id, hit);
|
||||
return hit;
|
||||
}
|
||||
|
||||
let blob = await copyAsset(photo, photo.id);
|
||||
if (!blob) blob = (await fetchRemoteCopy(photo)) ?? undefined;
|
||||
if (!blob) {
|
||||
throw new Error(
|
||||
photo.raw
|
||||
? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.'
|
||||
: 'Original image data is missing from browser storage',
|
||||
);
|
||||
}
|
||||
|
||||
// Apply EXIF orientation so the pixels the editor works on are upright.
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
cache.set(photo.id, bitmap);
|
||||
while (cache.size > CACHE_LIMIT) {
|
||||
const first = cache.keys().next();
|
||||
if (first.done) break;
|
||||
const old = cache.get(first.value);
|
||||
cache.delete(first.value);
|
||||
old?.close();
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
export function evictBitmap(photoId: string) {
|
||||
const bmp = cache.get(photoId);
|
||||
if (!bmp) return;
|
||||
cache.delete(photoId);
|
||||
bmp.close();
|
||||
}
|
||||
|
||||
export function clearBitmapCache() {
|
||||
for (const bmp of cache.values()) bmp.close();
|
||||
cache.clear();
|
||||
for (const bmp of denoisedCache.values()) bmp.close();
|
||||
denoisedCache.clear();
|
||||
}
|
||||
|
||||
const denoisedCache = new Map<string, ImageBitmap>();
|
||||
|
||||
/**
|
||||
* The server-rendered denoised proxy for an edit's `aiDenoise.key`.
|
||||
*
|
||||
* These are separate files from the edit and cost a few seconds to produce, so
|
||||
* they are cached by key and never re-fetched while the key stays the same.
|
||||
* Returns null when the asset is gone (cache pruned, storage moved), which the
|
||||
* caller treats as "no denoise".
|
||||
*/
|
||||
export async function getDenoisedBitmap(photo: PhotoRecord, key: string): Promise<ImageBitmap | null> {
|
||||
const sig = `${photo.id}:${key}`;
|
||||
const hit = denoisedCache.get(sig);
|
||||
if (hit) return hit;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/photos/${encodeURIComponent(photo.id)}/denoised?v=${encodeURIComponent(key)}`,
|
||||
{ credentials: 'same-origin' },
|
||||
);
|
||||
if (!res.ok) return null;
|
||||
const bitmap = await createImageBitmap(await res.blob(), { imageOrientation: 'from-image' });
|
||||
denoisedCache.set(sig, bitmap);
|
||||
while (denoisedCache.size > 4) {
|
||||
const first = denoisedCache.keys().next();
|
||||
if (first.done) break;
|
||||
denoisedCache.get(first.value)?.close();
|
||||
denoisedCache.delete(first.value);
|
||||
}
|
||||
return bitmap;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import exifr from 'exifr';
|
||||
import type { UploadResult } from './api';
|
||||
import type { PhotoMeta, PhotoRecord } from '../types';
|
||||
import { putAsset, putPhoto } from './db';
|
||||
import { defaultEdits, normalizePhoto } from './edits';
|
||||
import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults';
|
||||
import { isRawFile, RAW_EXTENSIONS } from './raw';
|
||||
|
||||
export interface ImportProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
current: string;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
photos: PhotoRecord[];
|
||||
failed: { name: string; reason: string }[];
|
||||
cancelled?: boolean;
|
||||
}
|
||||
|
||||
/** Provided by the app when a Luminary server is connected. */
|
||||
export interface CloudImport {
|
||||
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
|
||||
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
||||
}
|
||||
|
||||
/** Files imported at once; the server bounds how many raws decode in parallel. */
|
||||
const IMPORT_CONCURRENCY = 4;
|
||||
|
||||
export function uid(): string {
|
||||
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
|
||||
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
|
||||
let cursor = 0;
|
||||
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
|
||||
for (;;) {
|
||||
const index = cursor++;
|
||||
if (index >= items.length) return;
|
||||
await fn(items[index], index);
|
||||
}
|
||||
});
|
||||
return Promise.all(runners);
|
||||
}
|
||||
|
||||
function formatShutter(time: unknown): string | undefined {
|
||||
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
|
||||
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
|
||||
return `1/${Math.round(1 / time)}s`;
|
||||
}
|
||||
|
||||
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
|
||||
try {
|
||||
const data = (await exifr.parse(file, {
|
||||
tiff: true,
|
||||
exif: true,
|
||||
gps: false,
|
||||
interop: false,
|
||||
translateValues: false,
|
||||
reviveValues: true,
|
||||
})) as Record<string, unknown> | undefined;
|
||||
if (!data) return { meta: {} };
|
||||
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
|
||||
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
|
||||
const meta: PhotoMeta = {
|
||||
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
|
||||
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
|
||||
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
|
||||
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
|
||||
shutter: formatShutter(data.ExposureTime),
|
||||
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
|
||||
};
|
||||
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
|
||||
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
|
||||
return { meta, takenAt };
|
||||
} catch {
|
||||
return { meta: {} };
|
||||
}
|
||||
}
|
||||
|
||||
function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
|
||||
const edits = defaultEdits();
|
||||
const match = defaultForMeta(defaults, meta);
|
||||
if (match) {
|
||||
edits.lens = {
|
||||
...match.profile,
|
||||
corrections: { ...match.profile.corrections },
|
||||
};
|
||||
}
|
||||
return edits;
|
||||
}
|
||||
|
||||
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
|
||||
const max = 560;
|
||||
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
|
||||
const w = Math.max(1, Math.round(bitmap.width * scale));
|
||||
const h = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas 2D is unavailable');
|
||||
ctx.imageSmoothingQuality = 'high';
|
||||
ctx.drawImage(bitmap, 0, 0, w, h);
|
||||
return canvas.toDataURL('image/jpeg', 0.82);
|
||||
}
|
||||
|
||||
export function isSupportedFile(file: File): boolean {
|
||||
if (file.type.startsWith('image/')) return true;
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw files cannot be decoded by the browser, so they are sent to the server,
|
||||
* demosaiced there, and represented locally by the returned editable proxy.
|
||||
*/
|
||||
async function importRaw(
|
||||
file: File,
|
||||
eventId: string,
|
||||
keywords: string[],
|
||||
cloud: CloudImport,
|
||||
defaults: CameraLensDefault[],
|
||||
): Promise<PhotoRecord> {
|
||||
const id = uid();
|
||||
const upload = await cloud.uploadOriginal(id, file, file.name);
|
||||
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
|
||||
const res = await fetch(previewUrl, { credentials: 'same-origin' });
|
||||
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
|
||||
const blob = await res.blob();
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
const thumb = await makeThumb(bitmap);
|
||||
const { meta, takenAt } = await readMeta(file);
|
||||
const width = upload.width ?? bitmap.width;
|
||||
const height = upload.height ?? bitmap.height;
|
||||
const edits = editsForImport(meta, defaults);
|
||||
bitmap.close();
|
||||
|
||||
const record = normalizePhoto({
|
||||
id,
|
||||
eventId,
|
||||
name: file.name,
|
||||
width,
|
||||
height,
|
||||
size: file.size,
|
||||
mime: 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
takenAt: takenAt ?? file.lastModified,
|
||||
meta,
|
||||
thumb,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords,
|
||||
edits,
|
||||
history: [{ label: 'Import', ts: Date.now(), edits }],
|
||||
raw: true,
|
||||
decode: upload.engine,
|
||||
previewUrl,
|
||||
});
|
||||
|
||||
await putPhoto(record);
|
||||
// No local blob: the multi-megabyte raw stays on the server.
|
||||
const saved = await cloud.push(record);
|
||||
const merged = normalizePhoto({ ...record, ...saved });
|
||||
await putPhoto(merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
async function importStandard(
|
||||
file: File,
|
||||
eventId: string,
|
||||
keywords: string[],
|
||||
cloud: CloudImport | null | undefined,
|
||||
defaults: CameraLensDefault[],
|
||||
): Promise<PhotoRecord> {
|
||||
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
|
||||
// the thumbnail and the edited proxy agree with what the camera shot.
|
||||
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
||||
const thumb = await makeThumb(bitmap);
|
||||
const { meta, takenAt } = await readMeta(file);
|
||||
const id = uid();
|
||||
const edits = editsForImport(meta, defaults);
|
||||
let record = normalizePhoto({
|
||||
id,
|
||||
eventId,
|
||||
name: file.name,
|
||||
width: bitmap.width,
|
||||
height: bitmap.height,
|
||||
size: file.size,
|
||||
mime: file.type || 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
takenAt: takenAt ?? file.lastModified,
|
||||
meta,
|
||||
thumb,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords,
|
||||
edits,
|
||||
history: [{ label: 'Import', ts: Date.now(), edits }],
|
||||
});
|
||||
await putAsset(id, file);
|
||||
bitmap.close();
|
||||
|
||||
if (cloud) {
|
||||
// Originals are mirrored to the server; failures fall back to a local-only import.
|
||||
try {
|
||||
await cloud.uploadOriginal(id, file, file.name);
|
||||
const saved = await cloud.push(record);
|
||||
record = normalizePhoto({ ...record, ...saved });
|
||||
} catch (err) {
|
||||
console.warn('Could not copy the original to the server', file.name, err);
|
||||
}
|
||||
}
|
||||
|
||||
await putPhoto(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
export async function importFiles(
|
||||
files: File[],
|
||||
eventId: string,
|
||||
keywords: string[] = [],
|
||||
onProgress?: (p: ImportProgress) => void,
|
||||
cloud?: CloudImport | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ImportResult> {
|
||||
const result: ImportResult = { photos: [], failed: [] };
|
||||
const images = files.filter(isSupportedFile);
|
||||
const total = images.length;
|
||||
if (!total) return result;
|
||||
|
||||
const collected: { index: number; photo: PhotoRecord }[] = [];
|
||||
const defaults = await loadCameraLensDefaults().catch(() => []);
|
||||
let done = 0;
|
||||
|
||||
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
||||
if (signal?.aborted) return;
|
||||
try {
|
||||
const photo = isRawFile(file)
|
||||
? cloud
|
||||
? await importRaw(file, eventId, keywords, cloud, defaults)
|
||||
: (() => {
|
||||
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
|
||||
})()
|
||||
: await importStandard(file, eventId, keywords, cloud, defaults);
|
||||
collected.push({ index, photo });
|
||||
} catch (err) {
|
||||
result.failed.push({
|
||||
name: file.name,
|
||||
reason: err instanceof Error ? err.message : 'Unsupported image format',
|
||||
});
|
||||
} finally {
|
||||
done += 1;
|
||||
onProgress?.({ done, total, current: file.name });
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the shoot in capture/selection order regardless of which finished first.
|
||||
collected.sort((a, b) => a.index - b.index);
|
||||
result.photos = collected.map((c) => c.photo);
|
||||
result.cancelled = Boolean(signal?.aborted);
|
||||
onProgress?.({ done: total, total, current: '' });
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultForMeta, type CameraLensDefault } from './lensDefaults';
|
||||
import type { LensProfile } from '../types';
|
||||
|
||||
const profile = (model: string): LensProfile => ({
|
||||
maker: 'Nikon',
|
||||
model,
|
||||
crop: 1,
|
||||
corrections: { distortion: true, tca: true, vignetting: true },
|
||||
});
|
||||
|
||||
const savedDefault = (
|
||||
camera: string,
|
||||
exifLens: string,
|
||||
model = 'Nikkor AF 50mm f/1.8D',
|
||||
): CameraLensDefault => ({
|
||||
camera,
|
||||
exifLens,
|
||||
profile: profile(model),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
describe('camera-lens default selection', () => {
|
||||
it('matches a camera and lens after normalizing both names', () => {
|
||||
const defaults = [
|
||||
savedDefault('NIKON CORPORATION NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'),
|
||||
];
|
||||
expect(
|
||||
defaultForMeta(defaults, {
|
||||
camera: 'NIKON D700',
|
||||
lens: 'Nikkor AF 50mm 1:1.8D',
|
||||
}),
|
||||
).toBe(defaults[0]);
|
||||
});
|
||||
|
||||
it('does not apply a default to a different lens on the same body', () => {
|
||||
const defaults = [
|
||||
savedDefault('NIKON CORPORATION NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'),
|
||||
];
|
||||
expect(
|
||||
defaultForMeta(defaults, {
|
||||
camera: 'NIKON CORPORATION NIKON D700',
|
||||
lens: 'NIKON AF NIKKOR 85MM F/1.8G',
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('requires both camera and lens metadata', () => {
|
||||
const defaults = [
|
||||
savedDefault('NIKON CORPORATION NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'),
|
||||
];
|
||||
expect(defaultForMeta(defaults, { camera: 'NIKON D700', lens: undefined })).toBeNull();
|
||||
expect(defaultForMeta(defaults, { camera: undefined, lens: 'NIKKOR 50mm f/1.8D' })).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the first row when more than one entry has the same key', () => {
|
||||
const older = { ...savedDefault('NIKON D700', 'NIKKOR 50mm f/1.8D'), updatedAt: 1 };
|
||||
const newer = { ...savedDefault('NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'), updatedAt: 2 };
|
||||
expect(
|
||||
defaultForMeta([newer, older], {
|
||||
camera: 'NIKON CORPORATION NIKON D700',
|
||||
lens: 'Nikkor AF 50mm f/1.8D',
|
||||
}),
|
||||
).toBe(newer);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { getKV, setKV } from './db';
|
||||
import { cameraKey, lensMatchKey } from './lensNames';
|
||||
import type { LensProfile, PhotoMeta } from '../types';
|
||||
|
||||
const DEFAULTS_KEY = 'cameraLensDefaults';
|
||||
const MAX_DEFAULTS = 40;
|
||||
|
||||
/** A profile that should be applied automatically when this body + lens imports. */
|
||||
export interface CameraLensDefault {
|
||||
camera: string;
|
||||
exifLens: string;
|
||||
profile: LensProfile;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
function validProfile(profile: unknown): profile is LensProfile {
|
||||
if (!profile || typeof profile !== 'object') return false;
|
||||
const value = profile as Partial<LensProfile>;
|
||||
return (
|
||||
typeof value.maker === 'string' &&
|
||||
value.maker.trim().length > 0 &&
|
||||
typeof value.model === 'string' &&
|
||||
value.model.trim().length > 0
|
||||
);
|
||||
}
|
||||
|
||||
export async function loadCameraLensDefaults(): Promise<CameraLensDefault[]> {
|
||||
const saved = await getKV<CameraLensDefault[]>(DEFAULTS_KEY);
|
||||
if (!Array.isArray(saved)) return [];
|
||||
return saved.filter(
|
||||
(entry): entry is CameraLensDefault =>
|
||||
Boolean(
|
||||
entry &&
|
||||
typeof entry.camera === 'string' &&
|
||||
entry.camera.trim() &&
|
||||
typeof entry.exifLens === 'string' &&
|
||||
entry.exifLens.trim() &&
|
||||
validProfile(entry.profile),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Default for this exact body and normalized EXIF lens, newest first. */
|
||||
export function defaultForMeta(
|
||||
defaults: CameraLensDefault[],
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): CameraLensDefault | null {
|
||||
if (!meta.camera || !meta.lens) return null;
|
||||
const body = cameraKey(meta.camera);
|
||||
const lens = lensMatchKey(meta.lens);
|
||||
if (!body || !lens) return null;
|
||||
return (
|
||||
defaults.find(
|
||||
(entry) => cameraKey(entry.camera) === body && lensMatchKey(entry.exifLens) === lens,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveCameraLensDefault(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
profile: LensProfile,
|
||||
): Promise<CameraLensDefault | null> {
|
||||
if (!meta.camera || !meta.lens) return null;
|
||||
const entry: CameraLensDefault = {
|
||||
camera: meta.camera,
|
||||
exifLens: meta.lens,
|
||||
profile,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
const defaults = await loadCameraLensDefaults();
|
||||
const body = cameraKey(meta.camera);
|
||||
const lens = lensMatchKey(meta.lens);
|
||||
const next = [
|
||||
entry,
|
||||
...defaults.filter(
|
||||
(old) => !(cameraKey(old.camera) === body && lensMatchKey(old.exifLens) === lens),
|
||||
),
|
||||
].slice(0, MAX_DEFAULTS);
|
||||
await setKV(DEFAULTS_KEY, next);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export async function removeCameraLensDefault(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<void> {
|
||||
if (!meta.camera || !meta.lens) return;
|
||||
const body = cameraKey(meta.camera);
|
||||
const lens = lensMatchKey(meta.lens);
|
||||
const defaults = await loadCameraLensDefaults();
|
||||
await setKV(
|
||||
DEFAULTS_KEY,
|
||||
defaults.filter(
|
||||
(entry) => !(cameraKey(entry.camera) === body && lensMatchKey(entry.exifLens) === lens),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getCameraLensDefault(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<CameraLensDefault | null> {
|
||||
return defaultForMeta(await loadCameraLensDefaults(), meta);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
cameraKey,
|
||||
decodeLensText,
|
||||
lensMatchKey,
|
||||
lensMatchScore,
|
||||
lensSearchVariants,
|
||||
} from './lensNames';
|
||||
|
||||
describe('lens name normalization', () => {
|
||||
it('decodes EXIF entities and collapses whitespace', () => {
|
||||
expect(decodeLensText(' Canon "L" 50mm ')).toBe('Canon "L" 50mm');
|
||||
});
|
||||
|
||||
it('ignores manufacturer prefixes when comparing equivalent lens names', () => {
|
||||
expect(lensMatchKey('NIKON AF NIKKOR 50MM F/1.8D')).toBe(
|
||||
lensMatchKey('Nikkor AF 50mm f/1.8D'),
|
||||
);
|
||||
expect(lensMatchKey('SIGMA 35mm F1.4 DG HSM | Art')).toBe(
|
||||
lensMatchKey('35mm F1.4 DG HSM Art'),
|
||||
);
|
||||
});
|
||||
|
||||
it('normalizes 1: apertures and AF-S aliases', () => {
|
||||
expect(lensMatchKey('NIKON 50mm 1:1.8D')).toBe(lensMatchKey('Nikkor 50mm f/1.8D'));
|
||||
expect(lensMatchKey('AF-S NIKKOR 24-70mm f/2.8E ED VR')).toBe(
|
||||
lensMatchKey('Nikon AF-S NIKKOR 24-70mm f/2.8E ED VR'),
|
||||
);
|
||||
});
|
||||
|
||||
it('builds progressively looser Lensfun search variants', () => {
|
||||
const variants = lensSearchVariants('NIKON AF NIKKOR 50MM F/1.8D');
|
||||
expect(variants).toContain('NIKON AF NIKKOR 50MM F/1.8D');
|
||||
expect(variants).toContain('af 50mm f/1.8');
|
||||
});
|
||||
|
||||
it('collapses a duplicated camera maker', () => {
|
||||
expect(cameraKey('NIKON CORPORATION NIKON D700')).toBe(cameraKey('NIKON D700'));
|
||||
expect(cameraKey('NIKON CORPORATION NIKON D700')).toBe('nikon d700');
|
||||
});
|
||||
});
|
||||
|
||||
describe('lens match scoring', () => {
|
||||
it('gives exact normalized matches the highest score', () => {
|
||||
expect(lensMatchScore('NIKON AF NIKKOR 50MM F/1.8D', 'Nikkor AF 50mm f/1.8D')).toBe(3);
|
||||
});
|
||||
|
||||
it('scores useful partial matches and rejects unrelated lenses', () => {
|
||||
const partial = lensMatchScore('NIKKOR 50mm 1:1.8D', 'Nikkor AF 50mm f/1.8D');
|
||||
expect(partial).toBeGreaterThan(0);
|
||||
expect(partial).toBeLessThan(3);
|
||||
expect(lensMatchScore('NIKKOR 50mm f/1.8D', 'Canon EF 24-70mm f/2.8L')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Camera and lens names arrive in several dialects: bodies repeat the maker
|
||||
* ("NIKON CORPORATION NIKON D700"), lenses carry maker prefixes and feature
|
||||
* suffixes ("NIKON AF NIKKOR 50MM F/1.8D"), and EXIF sometimes uses 1:1.8 for
|
||||
* the aperture. These helpers put those names into one comparable form.
|
||||
*/
|
||||
|
||||
const LENS_MAKERS = [
|
||||
'carl zeiss',
|
||||
'nikon corporation',
|
||||
'fujifilm',
|
||||
'fujinon',
|
||||
'hasselblad',
|
||||
'panasonic',
|
||||
'olympus',
|
||||
'voigtlander',
|
||||
'samsung',
|
||||
'pentax',
|
||||
'ricoh',
|
||||
'sigma',
|
||||
'tamron',
|
||||
'tokina',
|
||||
'samyang',
|
||||
'rokinon',
|
||||
'sony',
|
||||
'canon',
|
||||
'nikon',
|
||||
'nikkor',
|
||||
'leica',
|
||||
'zeiss',
|
||||
];
|
||||
|
||||
const LENS_TOKEN_ALIASES: Record<string, string> = {
|
||||
nikkor: '',
|
||||
nikon: '',
|
||||
canon: '',
|
||||
fujinon: '',
|
||||
fujifilm: '',
|
||||
sony: '',
|
||||
minolta: '',
|
||||
konica: '',
|
||||
olympus: '',
|
||||
panasonic: '',
|
||||
leica: '',
|
||||
pentax: '',
|
||||
sigma: '',
|
||||
tamron: '',
|
||||
tokina: '',
|
||||
samyang: '',
|
||||
rokinon: '',
|
||||
voigtlander: '',
|
||||
hasselblad: '',
|
||||
samsung: '',
|
||||
ricoh: '',
|
||||
zeiss: '',
|
||||
'af-s': 'afs',
|
||||
'af s': 'afs',
|
||||
'af-i': 'afi',
|
||||
'af i': 'afi',
|
||||
'ai-s': 'ais',
|
||||
'ai s': 'ais',
|
||||
'vr-ii': 'vr2',
|
||||
'vr ii': 'vr2',
|
||||
};
|
||||
|
||||
export function decodeLensText(value?: string): string {
|
||||
if (!value) return '';
|
||||
return value
|
||||
.replace(/\0/g, ' ')
|
||||
.replace(/"/gi, '"')
|
||||
.replace(/'|'/gi, "'")
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Lowercase, normalize units/apertures and remove punctuation noise. */
|
||||
function cleanLensName(value?: string): string {
|
||||
let text = decodeLensText(value).toLowerCase();
|
||||
text = text
|
||||
.replace(/[“”„]/g, '"')
|
||||
.replace(/\b(lens model|lens|zoom|camera)\b/g, ' ')
|
||||
.replace(/\b1\s*:\s*/g, 'f/')
|
||||
.replace(/\bf\s*\/?\s*(\d+(?:\.\d+)?)/g, 'f/$1')
|
||||
.replace(/(\d)\s*mm\b/g, '$1mm')
|
||||
.replace(/([a-z]{2,})(\d)/g, '$1 $2')
|
||||
.replace(/f\/(\d+(?:\.\d+)?)([a-z]+)/g, 'f/$1 $2')
|
||||
.replace(/[–—]/g, '-')
|
||||
.replace(/[^a-z0-9./-]+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
return text;
|
||||
}
|
||||
|
||||
function withoutMakerPrefix(value: string): string {
|
||||
let text = value.trim();
|
||||
for (const maker of LENS_MAKERS) {
|
||||
if (text.startsWith(`${maker} `)) {
|
||||
text = text.slice(maker.length + 1).trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return text
|
||||
.split(' ')
|
||||
.map((token) => LENS_TOKEN_ALIASES[token] ?? token)
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Canonical token set; good for deciding whether two EXIF strings mean the same lens. */
|
||||
export function lensMatchKey(value?: string): string {
|
||||
if (!value) return '';
|
||||
return withoutMakerPrefix(cleanLensName(value))
|
||||
.split(/\s+/)
|
||||
.filter((token) => token && token !== 'lens')
|
||||
.sort()
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
/** Text forms worth passing to Lensfun's fuzzy search, loosest last. */
|
||||
export function lensSearchVariants(value?: string): string[] {
|
||||
const raw = decodeLensText(value);
|
||||
if (raw.length < 2) return [];
|
||||
const normalized = cleanLensName(raw);
|
||||
const stripped = withoutMakerPrefix(normalized);
|
||||
const tokens = (stripped || normalized).split(/\s+/).filter(Boolean);
|
||||
const focal = tokens.find((token) => /^\d+(?:\.\d+)?(?:-\d+)?mm$/.test(token));
|
||||
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?$/.test(token));
|
||||
const series = tokens.filter((token) =>
|
||||
/^(afs|afi|ai|ais|ef|efs|rf|fe|e|z|sp|art|sports|dg|dn|hsm|usm|stm|vc|vr|is|ii|iii|iv)$/.test(token),
|
||||
);
|
||||
const compact = [tokens[0], focal, aperture].filter(Boolean).join(' ');
|
||||
const withSeries = [compact, ...series].filter(Boolean).join(' ');
|
||||
const variants = [raw, normalized, stripped, compact, withSeries];
|
||||
return [...new Set(variants.filter((text) => text.length >= 2))];
|
||||
}
|
||||
|
||||
/** Trace a camera body to a stable key, collapsing duplicate maker names. */
|
||||
export function cameraKey(camera?: string): string {
|
||||
if (!camera) return '';
|
||||
const tokens = decodeLensText(camera)
|
||||
.toLowerCase()
|
||||
.replace(/\b(corporation|corp|incorporated|inc|ltd|limited|co)\b/g, ' ')
|
||||
.replace(/[^a-z0-9]+/g, ' ')
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
const out: string[] = [];
|
||||
for (const token of tokens) {
|
||||
if (out[out.length - 1] !== token) out.push(token);
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
/** Token overlap score used to pick the best Lensfun search result. */
|
||||
export function lensMatchScore(left?: string, right?: string): number {
|
||||
const a = lensMatchKey(left);
|
||||
const b = lensMatchKey(right);
|
||||
if (!a || !b) return 0;
|
||||
if (a === b) return 3;
|
||||
const at = new Set(a.split(' '));
|
||||
const bt = new Set(b.split(' '));
|
||||
let shared = 0;
|
||||
for (const token of at) if (bt.has(token)) shared += 1;
|
||||
if (!shared) return 0;
|
||||
return shared / Math.max(at.size, bt.size);
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
import type {
|
||||
CameraMatch,
|
||||
CorrectionMaps,
|
||||
LensMatch,
|
||||
LensfunClient,
|
||||
} from '@neoanaloglabkk/lensfun-wasm';
|
||||
import { lensMatchScore, lensSearchVariants } from './lensNames';
|
||||
import type { LensProfile, PhotoMeta } from '../types';
|
||||
|
||||
/**
|
||||
* Lensfun is loaded on demand from public/lensfun. The database and the
|
||||
* WebAssembly wrapper are third-party assets; see public/lensfun/NOTICE.md.
|
||||
*/
|
||||
export interface LensMap {
|
||||
data: Float32Array;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface LensCorrection {
|
||||
key: string;
|
||||
geometry: LensMap;
|
||||
/** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */
|
||||
tca?: LensMap;
|
||||
/** RGB vignetting gains. */
|
||||
vignette?: LensMap;
|
||||
/** Centre zoom needed to hide transformed corners. */
|
||||
scale: number;
|
||||
}
|
||||
|
||||
const FLAG_TCA = 1;
|
||||
const FLAG_VIGNETTING = 2;
|
||||
const FLAG_DISTORTION = 8;
|
||||
|
||||
let clientPromise: Promise<LensfunClient> | null = null;
|
||||
let client: LensfunClient | null = null;
|
||||
const handleCache = new Map<string, LensMatch>();
|
||||
const cameraCache = new Map<string, CameraMatch | null>();
|
||||
const correctionCache = new Map<string, LensCorrection>();
|
||||
|
||||
async function loadCoreFactory(): Promise<(options?: Record<string, unknown>) => Promise<unknown>> {
|
||||
const response = await fetch('/lensfun/lensfun-core.js');
|
||||
if (!response.ok) throw new Error('Could not load the Lensfun runtime');
|
||||
let source = await response.text();
|
||||
// The 0.1.3 Emscripten build keeps the float heap view in a closure and the
|
||||
// wrapper reads it from `module.HEAPF32`, so expose it after every memory
|
||||
// resize. The asset itself is untouched on disk.
|
||||
if (!source.includes('Module["HEAPF32"]')) {
|
||||
const marker = 'HEAPF32=new Float32Array(b)';
|
||||
if (!source.includes(marker)) throw new Error('Unexpected Lensfun runtime layout');
|
||||
source = source.replace(marker, `${marker};Module["HEAPF32"]=HEAPF32;`);
|
||||
}
|
||||
const scriptUrl = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = scriptUrl;
|
||||
script.onload = () => {
|
||||
script.remove();
|
||||
resolve();
|
||||
};
|
||||
script.onerror = () => {
|
||||
script.remove();
|
||||
reject(new Error('Could not start the Lensfun runtime'));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
} finally {
|
||||
URL.revokeObjectURL(scriptUrl);
|
||||
}
|
||||
const factory = (globalThis as Record<string, unknown>).createLensfunCoreModule;
|
||||
if (typeof factory !== 'function') throw new Error('Lensfun runtime did not initialize');
|
||||
return factory as (options?: Record<string, unknown>) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export async function getLensfun(): Promise<LensfunClient> {
|
||||
if (client) return client;
|
||||
if (!clientPromise) {
|
||||
clientPromise = import('@neoanaloglabkk/lensfun-wasm')
|
||||
.then(async ({ createLensfun }) => {
|
||||
const moduleFactory = await loadCoreFactory();
|
||||
return createLensfun({
|
||||
moduleFactory,
|
||||
wasmUrl: '/lensfun/lensfun-core.wasm',
|
||||
dataUrl: '/lensfun/lensfun-core.data',
|
||||
});
|
||||
})
|
||||
.then((instance) => {
|
||||
client = instance;
|
||||
return instance;
|
||||
})
|
||||
.catch((err) => {
|
||||
clientPromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
return clientPromise;
|
||||
}
|
||||
|
||||
export function profileKey(profile: LensProfile) {
|
||||
return `${profile.maker}\u0000${profile.model}`;
|
||||
}
|
||||
|
||||
export interface LensSearchResult {
|
||||
maker: string;
|
||||
model: string;
|
||||
crop: number;
|
||||
score: number;
|
||||
available: number;
|
||||
}
|
||||
|
||||
function toResult(match: LensMatch, available = 0): LensSearchResult {
|
||||
return {
|
||||
maker: match.maker,
|
||||
model: match.model,
|
||||
crop: match.cropFactor,
|
||||
score: match.score,
|
||||
available,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchLens(
|
||||
query: string,
|
||||
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<LensSearchResult[]> {
|
||||
const variants = lensSearchVariants(query);
|
||||
if (!variants.length) return [];
|
||||
const lf = await getLensfun();
|
||||
const camera = cameraParts(meta?.camera);
|
||||
const cameraFields = {
|
||||
...(camera.maker ? { cameraMaker: camera.maker } : {}),
|
||||
...(camera.model ? { cameraModel: camera.model } : {}),
|
||||
};
|
||||
const byName = new Map<string, LensMatch>();
|
||||
for (const variant of variants) {
|
||||
let matches: LensMatch[] = [];
|
||||
try {
|
||||
matches = lf.searchLenses({ lensModel: variant, ...cameraFields });
|
||||
} catch {
|
||||
matches = [];
|
||||
}
|
||||
if (!matches.length) {
|
||||
try {
|
||||
matches = lf.searchLenses({ lensModel: variant });
|
||||
} catch {
|
||||
matches = [];
|
||||
}
|
||||
}
|
||||
for (const match of matches) {
|
||||
const key = `${match.maker}\u0000${match.model}`;
|
||||
if (!byName.has(key)) byName.set(key, match);
|
||||
}
|
||||
}
|
||||
const crop = (await findCamera(meta?.camera))?.cropFactor || 1;
|
||||
return [...byName.values()].slice(0, 20).map((match) => {
|
||||
handleCache.set(`${match.maker}\u0000${match.model}`, match);
|
||||
return toResult(match, lf.getAvailableModifications(match.handle, crop));
|
||||
});
|
||||
}
|
||||
|
||||
export async function findLensForMeta(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<LensSearchResult | null> {
|
||||
if (!meta.lens) return null;
|
||||
const results = await searchLens(meta.lens, meta);
|
||||
if (!results.length) return null;
|
||||
let best = results[0];
|
||||
let score = lensMatchScore(meta.lens, best.model);
|
||||
for (const candidate of results.slice(1)) {
|
||||
const next = lensMatchScore(meta.lens, candidate.model);
|
||||
if (next > score) {
|
||||
best = candidate;
|
||||
score = next;
|
||||
}
|
||||
}
|
||||
return score > 0 ? best : null;
|
||||
}
|
||||
|
||||
export async function resolveLens(profile: LensProfile): Promise<LensMatch | null> {
|
||||
const key = profileKey(profile);
|
||||
const cached = handleCache.get(key);
|
||||
if (cached) return cached;
|
||||
const lf = await getLensfun();
|
||||
const cam = cameraParts(profile.cameraModel);
|
||||
const cameraFields = {
|
||||
...(profile.cameraMaker || cam.maker ? { cameraMaker: profile.cameraMaker ?? cam.maker } : {}),
|
||||
...(profile.cameraModel || cam.model ? { cameraModel: cam.model ?? profile.cameraModel } : {}),
|
||||
};
|
||||
const tokens = profile.model.split(/\s+/).filter(Boolean);
|
||||
const focal = tokens.find((token) => /^\d+(?:\.\d+)?mm$/i.test(token));
|
||||
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?[a-z]*$/i.test(token));
|
||||
const shortened = tokens
|
||||
.filter((token) => !/^(af|af-s|af-i|ai|ai-s|ais|d|g|ed|vr|if|asp|ld|dx|fx)$/i.test(token))
|
||||
.join(' ');
|
||||
const queries: { lensMaker?: string; lensModel: string; cameraMaker?: string; cameraModel?: string }[] = [
|
||||
{ ...cameraFields, lensMaker: profile.maker, lensModel: profile.model },
|
||||
{ ...cameraFields, lensModel: profile.model },
|
||||
{ ...cameraFields, lensModel: shortened },
|
||||
...(focal
|
||||
? [{ ...cameraFields, lensModel: [tokens[0], focal, aperture].filter(Boolean).join(' ') }]
|
||||
: []),
|
||||
];
|
||||
const attempts: LensMatch[] = [];
|
||||
for (const query of queries) {
|
||||
try {
|
||||
const found = lf.searchLenses(query);
|
||||
if (found.length) {
|
||||
attempts.push(...found);
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
/* try the next, looser query */
|
||||
}
|
||||
}
|
||||
const exact =
|
||||
attempts.find(
|
||||
(match) =>
|
||||
match.maker.toLowerCase() === profile.maker.toLowerCase() &&
|
||||
match.model.toLowerCase() === profile.model.toLowerCase(),
|
||||
) ?? attempts[0];
|
||||
if (exact) handleCache.set(key, exact);
|
||||
return exact ?? null;
|
||||
}
|
||||
|
||||
export async function availableFor(profile: LensProfile): Promise<number> {
|
||||
const match = await resolveLens(profile);
|
||||
if (!match) return 0;
|
||||
const lf = await getLensfun();
|
||||
return lf.getAvailableModifications(match.handle, profile.crop);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- camera search */
|
||||
|
||||
function cameraParts(camera?: string): { maker?: string; model?: string } {
|
||||
if (!camera) return {};
|
||||
const cleaned = camera.replace(/\s+/g, ' ').trim();
|
||||
const lower = cleaned.toLowerCase();
|
||||
const makerNames = [
|
||||
'Nikon Corporation',
|
||||
'Canon',
|
||||
'Sony',
|
||||
'FUJIFILM',
|
||||
'Olympus',
|
||||
'Panasonic',
|
||||
'PENTAX',
|
||||
'Sigma',
|
||||
'Tamron',
|
||||
'Leica',
|
||||
'Hasselblad',
|
||||
'Samsung',
|
||||
'Ricoh',
|
||||
];
|
||||
const maker = makerNames.find((name) => lower.startsWith(name.toLowerCase()));
|
||||
if (maker) {
|
||||
return { maker, model: cleaned.slice(maker.length).trim() || cleaned };
|
||||
}
|
||||
const [first, ...rest] = cleaned.split(' ');
|
||||
return rest.length ? { maker: first, model: rest.join(' ') } : { model: cleaned };
|
||||
}
|
||||
|
||||
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
|
||||
if (!camera) return null;
|
||||
const cached = cameraCache.get(camera);
|
||||
if (cached !== undefined) return cached;
|
||||
const lf = await getLensfun();
|
||||
const parts = cameraParts(camera);
|
||||
let found: CameraMatch[] = [];
|
||||
try {
|
||||
found = lf.searchCameras({ ...parts, searchFlags: 1 });
|
||||
} catch {
|
||||
found = [];
|
||||
}
|
||||
if (!found.length) {
|
||||
try {
|
||||
found = lf.searchCameras({ model: camera, searchFlags: 1 });
|
||||
} catch {
|
||||
found = [];
|
||||
}
|
||||
}
|
||||
const best = found[0] ?? null;
|
||||
cameraCache.set(camera, best);
|
||||
return best;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- correction maps */
|
||||
|
||||
export function autoScaleFor(geometry: LensMap): number {
|
||||
const sample = (x: number, y: number) => {
|
||||
const px = x * (geometry.width - 1);
|
||||
const py = y * (geometry.height - 1);
|
||||
const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px)));
|
||||
const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py)));
|
||||
const x1 = Math.min(geometry.width - 1, x0 + 1);
|
||||
const y1 = Math.min(geometry.height - 1, y0 + 1);
|
||||
const fx = px - x0;
|
||||
const fy = py - y0;
|
||||
const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4;
|
||||
const a = at(x0, y0);
|
||||
const b = at(x1, y0);
|
||||
const c = at(x0, y1);
|
||||
const d = at(x1, y1);
|
||||
return {
|
||||
x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) +
|
||||
(geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy,
|
||||
y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) +
|
||||
(geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy,
|
||||
};
|
||||
};
|
||||
const inside = (scale: number) => {
|
||||
for (let iy = 0; iy <= 24; iy++) {
|
||||
for (let ix = 0; ix <= 24; ix++) {
|
||||
const x = 0.5 + (ix / 24 - 0.5) / scale;
|
||||
const y = 0.5 + (iy / 24 - 0.5) / scale;
|
||||
const p = sample(x, y);
|
||||
if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (inside(1)) return 1;
|
||||
let lo = 1;
|
||||
let hi = 2.5;
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const mid = (lo + hi) / 2;
|
||||
if (inside(mid)) hi = mid;
|
||||
else lo = mid;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
|
||||
function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) {
|
||||
const px = Math.max(0, Math.min(w - 1, x * (w - 1)));
|
||||
const py = Math.max(0, Math.min(h - 1, y * (h - 1)));
|
||||
const x0 = Math.floor(px);
|
||||
const y0 = Math.floor(py);
|
||||
const x1 = Math.min(w - 1, x0 + 1);
|
||||
const y1 = Math.min(h - 1, y0 + 1);
|
||||
const fx = px - x0;
|
||||
const fy = py - y0;
|
||||
const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset;
|
||||
const a = values[at(x0, y0)];
|
||||
const b = values[at(x1, y0)];
|
||||
const c = values[at(x0, y1)];
|
||||
const d = values[at(x1, y1)];
|
||||
return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
|
||||
}
|
||||
|
||||
export async function buildLensCorrection(
|
||||
profile: LensProfile,
|
||||
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
|
||||
): Promise<LensCorrection> {
|
||||
const key = `${profileKey(profile)}|${profile.crop}|${photo.width}x${photo.height}|${photo.meta.focal ?? 0}|${
|
||||
photo.meta.aperture ?? 0
|
||||
}|${profile.corrections.distortion ? 1 : 0}${profile.corrections.tca ? 1 : 0}${
|
||||
profile.corrections.vignetting ? 1 : 0
|
||||
}|${profile.distance ?? 1000}`;
|
||||
const cached = correctionCache.get(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const match = await resolveLens(profile);
|
||||
if (!match) throw new Error('Lens profile not found in the Lensfun database');
|
||||
const focal = Number(photo.meta.focal) || 0;
|
||||
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
|
||||
const lf = await getLensfun();
|
||||
const available = lf.getAvailableModifications(match.handle, profile.crop);
|
||||
const useDistortion =
|
||||
profile.corrections.distortion && (available & FLAG_DISTORTION) !== 0;
|
||||
const useTca = profile.corrections.tca && (available & FLAG_TCA) !== 0;
|
||||
const useVignetting =
|
||||
profile.corrections.vignetting &&
|
||||
(available & FLAG_VIGNETTING) !== 0 &&
|
||||
Number(photo.meta.aperture) > 0;
|
||||
const long = 640;
|
||||
const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height));
|
||||
const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect));
|
||||
const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long;
|
||||
|
||||
const maps: CorrectionMaps = lf.buildCorrectionMaps({
|
||||
lensHandle: match.handle,
|
||||
width: mapW,
|
||||
height: mapH,
|
||||
focal,
|
||||
crop: profile.crop,
|
||||
step: 1,
|
||||
includeTca: useTca,
|
||||
includeVignetting: useVignetting,
|
||||
aperture: Number(photo.meta.aperture) || 1,
|
||||
distance: profile.distance ?? 1000,
|
||||
});
|
||||
|
||||
// Textures are RGBA32F so the renderer can use one upload path for all three
|
||||
// maps. Geometry and TCA only need the first channels, but keeping four
|
||||
// channels also means the texture is always fully specified.
|
||||
const geometry = new Float32Array(mapW * mapH * 4);
|
||||
for (let i = 0; i < mapW * mapH; i++) {
|
||||
if (useDistortion) {
|
||||
geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1);
|
||||
geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1);
|
||||
} else {
|
||||
geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1);
|
||||
geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
||||
}
|
||||
geometry[i * 4 + 3] = 1;
|
||||
}
|
||||
const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH };
|
||||
let tca: LensMap | undefined;
|
||||
if (useTca && maps.tca) {
|
||||
tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
||||
for (let i = 0; i < mapW * mapH; i++) {
|
||||
const x = (i % mapW) / Math.max(1, mapW - 1);
|
||||
const y = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
||||
const gx = useDistortion ? geometry[i * 4] : x;
|
||||
const gy = useDistortion ? geometry[i * 4 + 1] : y;
|
||||
const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1);
|
||||
const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1);
|
||||
const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1);
|
||||
const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1);
|
||||
tca.data[i * 4] = rx - gx;
|
||||
tca.data[i * 4 + 1] = ry - gy;
|
||||
tca.data[i * 4 + 2] = bx - gx;
|
||||
tca.data[i * 4 + 3] = by - gy;
|
||||
}
|
||||
}
|
||||
let vignette: LensMap | undefined;
|
||||
if (useVignetting && maps.vignetting) {
|
||||
vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
||||
for (let i = 0; i < mapW * mapH; i++) {
|
||||
vignette.data[i * 4] = maps.vignetting[i * 3];
|
||||
vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1];
|
||||
vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2];
|
||||
vignette.data[i * 4 + 3] = 1;
|
||||
}
|
||||
}
|
||||
const correction: LensCorrection = {
|
||||
key,
|
||||
geometry: geometryMap,
|
||||
tca,
|
||||
vignette,
|
||||
scale: useDistortion ? autoScaleFor(geometryMap) : 1,
|
||||
};
|
||||
correctionCache.set(key, correction);
|
||||
return correction;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- CPU map math */
|
||||
|
||||
export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } {
|
||||
return {
|
||||
x: bilinear(map.data, map.width, map.height, x, y, 4, 0),
|
||||
y: bilinear(map.data, map.width, map.height, x, y, 4, 1),
|
||||
};
|
||||
}
|
||||
|
||||
export function correctLensPoint(
|
||||
correction: LensCorrection | null,
|
||||
x: number,
|
||||
y: number,
|
||||
): { x: number; y: number } {
|
||||
if (!correction) return { x, y };
|
||||
const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale);
|
||||
const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale);
|
||||
return sampleLensMap(correction.geometry, sx, sy);
|
||||
}
|
||||
|
||||
export function uncorrectLensPoint(
|
||||
correction: LensCorrection | null,
|
||||
x: number,
|
||||
y: number,
|
||||
): { x: number; y: number } {
|
||||
if (!correction) return { x, y };
|
||||
let px = x;
|
||||
let py = y;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const mapped = correctLensPoint(correction, px, py);
|
||||
px += x - mapped.x;
|
||||
py += y - mapped.y;
|
||||
}
|
||||
return { x: px, y: py };
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { getBitmap } from './images';
|
||||
|
||||
export type MergeKind = 'hdr' | 'panorama' | 'focus';
|
||||
|
||||
export interface MergeResult {
|
||||
blob: Blob;
|
||||
width: number;
|
||||
height: number;
|
||||
thumb: string;
|
||||
kind: MergeKind;
|
||||
sourceIds: string[];
|
||||
}
|
||||
|
||||
interface Layer {
|
||||
canvas: HTMLCanvasElement;
|
||||
pixels: Uint8ClampedArray;
|
||||
gray: Uint8Array;
|
||||
grayW: number;
|
||||
grayH: number;
|
||||
dx: number;
|
||||
dy: number;
|
||||
}
|
||||
|
||||
const MAX_EDGE = 2600;
|
||||
|
||||
function scaledCanvas(bitmap: ImageBitmap): HTMLCanvasElement {
|
||||
const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new Error('Could not create a merge canvas');
|
||||
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function readPixels(canvas: HTMLCanvasElement) {
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new Error('Could not read the merge pixels');
|
||||
return ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
}
|
||||
|
||||
function grayFrom(pixels: Uint8ClampedArray, width: number, height: number, maxW = 360) {
|
||||
const scale = Math.min(1, maxW / width);
|
||||
const w = Math.max(1, Math.round(width * scale));
|
||||
const h = Math.max(1, Math.round(height * scale));
|
||||
const out = new Uint8Array(w * h);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const sy = Math.min(height - 1, Math.round((y / h) * height));
|
||||
for (let x = 0; x < w; x++) {
|
||||
const sx = Math.min(width - 1, Math.round((x / w) * width));
|
||||
const o = (sy * width + sx) * 4;
|
||||
out[y * w + x] = Math.round(0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]);
|
||||
}
|
||||
}
|
||||
return { data: out, w, h };
|
||||
}
|
||||
|
||||
/** Translation-only alignment is enough for bracketed and focus-stacked frames. */
|
||||
function align(ref: Layer, layer: Layer, maxShift = 36) {
|
||||
const { data: a, w, h } = { data: ref.gray, w: ref.grayW, h: ref.grayH };
|
||||
let best = { dx: 0, dy: 0, score: Number.POSITIVE_INFINITY };
|
||||
for (let dy = -maxShift; dy <= maxShift; dy += 2) {
|
||||
for (let dx = -maxShift; dx <= maxShift; dx += 2) {
|
||||
let score = 0;
|
||||
let n = 0;
|
||||
for (let y = maxShift; y < h - maxShift; y += 4) {
|
||||
for (let x = maxShift; x < w - maxShift; x += 4) {
|
||||
const bx = x + Math.round((dx / maxShift) * maxShift);
|
||||
const by = y + Math.round((dy / maxShift) * maxShift);
|
||||
if (bx < 0 || by < 0 || bx >= w || by >= h) continue;
|
||||
score += Math.abs(a[y * w + x] - layer.gray[by * w + bx]);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n && score / n < best.score) best = { dx, dy, score: score / n };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function luma(pixels: Uint8ClampedArray, o: number) {
|
||||
return (0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]) / 255;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exposure blending. Each frame contributes more where it is mid-toned, so a
|
||||
* blown highlight in the bright frame does not wash out the dark frame, and a
|
||||
* noisy shadow does not dominate the final image.
|
||||
*/
|
||||
function mergeHdr(layers: Layer[]) {
|
||||
const width = Math.min(...layers.map((l) => l.canvas.width));
|
||||
const height = Math.min(...layers.map((l) => l.canvas.height));
|
||||
const out = new Uint8ClampedArray(width * height * 4);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let total = 0;
|
||||
for (const layer of layers) {
|
||||
const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx));
|
||||
const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy));
|
||||
const o = (sy * layer.canvas.width + sx) * 4;
|
||||
const l = luma(layer.pixels, o);
|
||||
const weight = Math.max(0.03, 1 - Math.abs(l - 0.46) * 1.75);
|
||||
r += layer.pixels[o] * weight;
|
||||
g += layer.pixels[o + 1] * weight;
|
||||
b += layer.pixels[o + 2] * weight;
|
||||
total += weight;
|
||||
}
|
||||
const o = (y * width + x) * 4;
|
||||
out[o] = r / total;
|
||||
out[o + 1] = g / total;
|
||||
out[o + 2] = b / total;
|
||||
out[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sharpness(pixels: Uint8ClampedArray, width: number, x: number, y: number) {
|
||||
if (x < 1 || y < 1 || x >= width - 1) return 0;
|
||||
const o = (y * width + x) * 4;
|
||||
const l = luma(pixels, o);
|
||||
const lx = luma(pixels, o - 4);
|
||||
const rx = luma(pixels, o + 4);
|
||||
const ty = luma(pixels, o - width * 4);
|
||||
const by = luma(pixels, o + width * 4);
|
||||
return Math.abs(l * 4 - lx - rx - ty - by);
|
||||
}
|
||||
|
||||
/** Pick the locally sharpest source pixel, then feather the decision with a 3×3 vote. */
|
||||
function mergeFocus(layers: Layer[]) {
|
||||
const width = Math.min(...layers.map((l) => l.canvas.width));
|
||||
const height = Math.min(...layers.map((l) => l.canvas.height));
|
||||
const out = new Uint8ClampedArray(width * height * 4);
|
||||
const picks = new Uint8Array(width * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
let best = 0;
|
||||
let bestScore = -1;
|
||||
for (let i = 0; i < layers.length; i++) {
|
||||
const layer = layers[i];
|
||||
const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx));
|
||||
const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy));
|
||||
const score = sharpness(layer.pixels, layer.canvas.width, sx, sy);
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
picks[y * width + x] = best;
|
||||
}
|
||||
}
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const votes = new Map<number, number>();
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
const px = Math.min(width - 1, Math.max(0, x + dx));
|
||||
const py = Math.min(height - 1, Math.max(0, y + dy));
|
||||
const pick = picks[py * width + px];
|
||||
votes.set(pick, (votes.get(pick) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
let best = picks[y * width + x];
|
||||
let bestVotes = 0;
|
||||
for (const [pick, count] of votes) {
|
||||
if (count > bestVotes) {
|
||||
best = pick;
|
||||
bestVotes = count;
|
||||
}
|
||||
}
|
||||
const layer = layers[best];
|
||||
const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx));
|
||||
const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy));
|
||||
const so = (sy * layer.canvas.width + sx) * 4;
|
||||
const o = (y * width + x) * 4;
|
||||
out[o] = layer.pixels[so];
|
||||
out[o + 1] = layer.pixels[so + 1];
|
||||
out[o + 2] = layer.pixels[so + 2];
|
||||
out[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function panoramaOffset(left: Layer, right: Layer) {
|
||||
const w = Math.min(left.grayW, right.grayW);
|
||||
const h = Math.min(left.grayH, right.grayH);
|
||||
const minOverlap = Math.round(w * 0.12);
|
||||
const maxOverlap = Math.round(w * 0.72);
|
||||
let best = { overlap: Math.round(w * 0.35), dy: 0, score: Number.POSITIVE_INFINITY };
|
||||
for (let dy = -8; dy <= 8; dy += 2) {
|
||||
for (let overlap = minOverlap; overlap <= maxOverlap; overlap += 3) {
|
||||
let score = 0;
|
||||
let n = 0;
|
||||
for (let y = 6; y < h - 6; y += 5) {
|
||||
for (let x = w - overlap; x < w - 2; x += 4) {
|
||||
const ry = y + dy;
|
||||
if (ry < 0 || ry >= h) continue;
|
||||
score += Math.abs(left.gray[y * w + x] - right.gray[ry * w + (x - (w - overlap))]);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n && score / n < best.score) best = { overlap, dy, score: score / n };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function mergePanorama(layers: Layer[]) {
|
||||
const overlaps: number[] = [];
|
||||
const dys: number[] = [];
|
||||
for (let i = 1; i < layers.length; i++) {
|
||||
const match = panoramaOffset(layers[i - 1], layers[i]);
|
||||
overlaps.push(Math.round((match.overlap / Math.max(1, layers[i - 1].grayW)) * layers[i - 1].canvas.width));
|
||||
dys.push(Math.round((match.dy / Math.max(1, layers[i - 1].grayH)) * layers[i - 1].canvas.height));
|
||||
}
|
||||
const xs = [0];
|
||||
for (let i = 1; i < layers.length; i++) xs.push(xs[i - 1] + layers[i - 1].canvas.width - overlaps[i - 1]);
|
||||
const width = Math.max(...xs.map((x, i) => x + layers[i].canvas.width));
|
||||
const height = Math.max(...layers.map((l) => l.canvas.height));
|
||||
const acc = new Float32Array(width * height * 3);
|
||||
const weight = new Float32Array(width * height);
|
||||
|
||||
layers.forEach((layer, i) => {
|
||||
const x0 = xs[i];
|
||||
const y0 = Math.round((height - layer.canvas.height) / 2 + (i ? dys[i - 1] : 0));
|
||||
for (let y = 0; y < layer.canvas.height; y++) {
|
||||
const oy = y + y0;
|
||||
if (oy < 0 || oy >= height) continue;
|
||||
for (let x = 0; x < layer.canvas.width; x++) {
|
||||
const ox = x + x0;
|
||||
if (ox < 0 || ox >= width) continue;
|
||||
const o = (y * layer.canvas.width + x) * 4;
|
||||
const target = oy * width + ox;
|
||||
const edge = Math.min(1, Math.min(x, layer.canvas.width - 1 - x) / Math.max(1, layer.canvas.width * 0.08));
|
||||
const w = 0.15 + edge * 0.85;
|
||||
acc[target * 3] += layer.pixels[o] * w;
|
||||
acc[target * 3 + 1] += layer.pixels[o + 1] * w;
|
||||
acc[target * 3 + 2] += layer.pixels[o + 2] * w;
|
||||
weight[target] += w;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const out = new Uint8ClampedArray(width * height * 4);
|
||||
for (let i = 0; i < width * height; i++) {
|
||||
const w = weight[i] || 1;
|
||||
out[i * 4] = acc[i * 3] / w;
|
||||
out[i * 4 + 1] = acc[i * 3 + 1] / w;
|
||||
out[i * 4 + 2] = acc[i * 3 + 2] / w;
|
||||
out[i * 4 + 3] = 255;
|
||||
}
|
||||
return { pixels: out, width, height };
|
||||
}
|
||||
|
||||
function canvasFromPixels(pixels: Uint8ClampedArray, width: number, height: number) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Could not build the merged image');
|
||||
const image = ctx.createImageData(width, height);
|
||||
image.data.set(pixels);
|
||||
ctx.putImageData(image, 0, 0);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function thumbFrom(canvas: HTMLCanvasElement) {
|
||||
const thumb = document.createElement('canvas');
|
||||
const scale = 480 / Math.max(canvas.width, canvas.height);
|
||||
thumb.width = Math.max(1, Math.round(canvas.width * scale));
|
||||
thumb.height = Math.max(1, Math.round(canvas.height * scale));
|
||||
thumb.getContext('2d')?.drawImage(canvas, 0, 0, thumb.width, thumb.height);
|
||||
return thumb.toDataURL('image/jpeg', 0.82);
|
||||
}
|
||||
|
||||
export async function mergePhotos(
|
||||
photos: PhotoRecord[],
|
||||
kind: MergeKind,
|
||||
onProgress?: (done: number, total: number) => void,
|
||||
): Promise<MergeResult> {
|
||||
if (photos.length < 2) throw new Error('Select at least two photos to merge');
|
||||
const layers: Layer[] = [];
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
onProgress?.(i, photos.length);
|
||||
const bitmap = await getBitmap(photos[i]);
|
||||
const canvas = scaledCanvas(bitmap);
|
||||
const image = readPixels(canvas);
|
||||
const gray = grayFrom(image.data, canvas.width, canvas.height);
|
||||
layers.push({
|
||||
canvas,
|
||||
pixels: image.data,
|
||||
gray: gray.data,
|
||||
grayW: gray.w,
|
||||
grayH: gray.h,
|
||||
dx: 0,
|
||||
dy: 0,
|
||||
});
|
||||
}
|
||||
onProgress?.(photos.length, photos.length);
|
||||
|
||||
if (kind === 'panorama') {
|
||||
const merged = mergePanorama(layers);
|
||||
const canvas = canvasFromPixels(merged.pixels, merged.width, merged.height);
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.94));
|
||||
if (!blob) throw new Error('Could not encode the panorama');
|
||||
return { blob, width: merged.width, height: merged.height, thumb: thumbFrom(canvas), kind, sourceIds: photos.map((p) => p.id) };
|
||||
}
|
||||
|
||||
const progress = (n: number) => onProgress?.(Math.min(photos.length, photos.length - 1 + n / 10), photos.length);
|
||||
const ref = layers[0];
|
||||
for (let i = 1; i < layers.length; i++) {
|
||||
const match = align(ref, layers[i]);
|
||||
layers[i].dx = Math.round((match.dx / Math.max(1, ref.grayW)) * ref.canvas.width);
|
||||
layers[i].dy = Math.round((match.dy / Math.max(1, ref.grayH)) * ref.canvas.height);
|
||||
progress(i);
|
||||
}
|
||||
|
||||
const width = Math.min(...layers.map((l) => l.canvas.width));
|
||||
const height = Math.min(...layers.map((l) => l.canvas.height));
|
||||
const pixels = kind === 'hdr' ? mergeHdr(layers) : mergeFocus(layers);
|
||||
const canvas = canvasFromPixels(pixels, width, height);
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.94));
|
||||
if (!blob) throw new Error('Could not encode the merged image');
|
||||
return { blob, width, height, thumb: thumbFrom(canvas), kind, sourceIds: photos.map((p) => p.id) };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Edits, PhotoMeta } from '../types';
|
||||
|
||||
/**
|
||||
* A camera/ISO-aware starting point for the existing denoise sliders.
|
||||
*
|
||||
* This is a deterministic profile curve, not a learned denoiser: it scales the
|
||||
* luminance and chroma smoothing with the ISO the file was shot at and keeps
|
||||
* more detail at low ISOs. The user can still tune every value afterwards.
|
||||
*/
|
||||
export function autoNoiseFor(meta: PhotoMeta): Edits['noise'] {
|
||||
const iso = Math.max(50, Number(meta.iso) || 100);
|
||||
const stops = Math.max(0, Math.log2(iso / 100));
|
||||
const luminance = Math.round(Math.min(78, stops * 11));
|
||||
const chroma = Math.round(Math.min(88, 6 + stops * 12));
|
||||
const detail = Math.round(Math.max(18, 52 - stops * 3));
|
||||
const chromaDetail = Math.round(Math.max(22, 54 - stops * 4));
|
||||
// Cameras with a known strong high-ISO reputation get a small nudge; the
|
||||
// number is deliberately modest so this never becomes a hidden "look".
|
||||
const camera = (meta.camera ?? '').toLowerCase();
|
||||
const nudge = /a7s|a7s ii|a7s iii|fx3|r6|r5|z6|z7|d5|d6/.test(camera) ? -4 : 0;
|
||||
return {
|
||||
luminance: Math.max(0, luminance + nudge),
|
||||
detail,
|
||||
chroma: Math.max(0, chroma + nudge),
|
||||
chromaDetail,
|
||||
};
|
||||
}
|
||||
+1171
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
/** Raw containers the server can demosaic (LibRaw) or fall back to previews for. */
|
||||
export const RAW_EXTENSIONS = new Set([
|
||||
'cr2', 'cr3', 'crw',
|
||||
'nef', 'nrw',
|
||||
'arw', 'srf', 'sr2',
|
||||
'orf',
|
||||
'rw2', 'raw', 'rwl',
|
||||
'raf',
|
||||
'pef', 'dng',
|
||||
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef',
|
||||
]);
|
||||
|
||||
export function isRawFile(file: File): boolean {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(',');
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { encodeTiff16 } from './tiff';
|
||||
|
||||
function entries(bytes: Uint8Array) {
|
||||
const view = new DataView(bytes.buffer);
|
||||
const ifd = view.getUint32(4, true);
|
||||
const count = view.getUint16(ifd, true);
|
||||
const tags = new Map<number, { type: number; count: number; value: number }>();
|
||||
for (let index = 0; index < count; index++) {
|
||||
const at = ifd + 2 + index * 12;
|
||||
tags.set(view.getUint16(at, true), {
|
||||
type: view.getUint16(at + 2, true),
|
||||
count: view.getUint32(at + 4, true),
|
||||
value: view.getUint32(at + 8, true),
|
||||
});
|
||||
}
|
||||
return { tags, view };
|
||||
}
|
||||
|
||||
describe('16-bit TIFF export', () => {
|
||||
it('writes a little-endian RGB TIFF with top-down rows', async () => {
|
||||
const pixels = new Float32Array([
|
||||
// readPixels order is bottom-left first: bottom blue, top red.
|
||||
0, 0, 1, 1, 1, 0, 0, 1,
|
||||
]);
|
||||
const blob = encodeTiff16({ width: 1, height: 2, pixels });
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const { tags, view } = entries(bytes);
|
||||
expect(bytes[0]).toBe(0x49);
|
||||
expect(bytes[1]).toBe(0x49);
|
||||
expect(tags.get(256)?.value).toBe(1);
|
||||
expect(tags.get(257)?.value).toBe(2);
|
||||
expect(tags.get(258)?.count).toBe(3);
|
||||
expect(tags.get(259)?.value).toBe(1);
|
||||
expect(tags.get(279)?.value).toBe(12);
|
||||
const dataAt = tags.get(273)?.value ?? 0;
|
||||
expect(view.getUint16(dataAt, true)).toBe(65535);
|
||||
expect(view.getUint16(dataAt + 2, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 4, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 6, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 8, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 10, true)).toBe(65535);
|
||||
});
|
||||
|
||||
it('stores an ICC profile and exposes it through tag 34675', async () => {
|
||||
const icc = new Uint8Array([1, 2, 3, 4, 5]);
|
||||
const blob = encodeTiff16({
|
||||
width: 1,
|
||||
height: 1,
|
||||
pixels: new Float32Array([1, 1, 1, 1]),
|
||||
icc,
|
||||
});
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const { tags } = entries(bytes);
|
||||
expect(tags.get(34675)?.type).toBe(7);
|
||||
expect(tags.get(34675)?.count).toBe(icc.length);
|
||||
const at = tags.get(34675)?.value ?? 0;
|
||||
expect([...bytes.subarray(at, at + icc.length)]).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
});
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
export interface Tiff16Options {
|
||||
width: number;
|
||||
height: number;
|
||||
/** RGB samples, top-to-bottom, already in output colour space. */
|
||||
pixels: Float32Array;
|
||||
/** Optional embedded ICC profile. */
|
||||
icc?: Uint8Array | null;
|
||||
}
|
||||
|
||||
const LE = (() => {
|
||||
const probe = new Uint8Array(new Uint16Array([1]).buffer);
|
||||
return probe[0] === 1;
|
||||
})();
|
||||
|
||||
function set16(view: DataView, at: number, value: number) {
|
||||
view.setUint16(at, value & 0xffff, true);
|
||||
}
|
||||
|
||||
function set32(view: DataView, at: number, value: number) {
|
||||
view.setUint32(at, value >>> 0, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal uncompressed little-endian 16-bit RGB TIFF.
|
||||
*
|
||||
* The profile tag (34675) is included when supplied. Uncompressed keeps the
|
||||
* encoder dependency-free and lossless; the files are larger than JPEG but are
|
||||
* intended as delivery masters rather than web files.
|
||||
*/
|
||||
export function encodeTiff16({ width, height, pixels, icc }: Tiff16Options): Blob {
|
||||
const w = Math.max(1, Math.round(width));
|
||||
const h = Math.max(1, Math.round(height));
|
||||
const pixelBytes = w * h * 3 * 2;
|
||||
const profileLength = icc?.length ?? 0;
|
||||
const entries = profileLength ? 14 : 13;
|
||||
|
||||
// IFD starts after the 8-byte header. Extras follow the IFD and are aligned.
|
||||
const ifdAt = 8;
|
||||
const ifdBytes = 2 + entries * 12 + 4;
|
||||
let extraAt = ifdAt + ifdBytes;
|
||||
const align4 = (n: number) => (n + 3) & ~3;
|
||||
extraAt = align4(extraAt);
|
||||
|
||||
const bitsAt = extraAt;
|
||||
const xResAt = bitsAt + 8;
|
||||
const yResAt = xResAt + 8;
|
||||
const profileAt = yResAt + 8;
|
||||
const dataAt = align4(profileAt + profileLength);
|
||||
const total = dataAt + pixelBytes;
|
||||
const out = new Uint8Array(total);
|
||||
const view = new DataView(out.buffer);
|
||||
|
||||
// TIFF header.
|
||||
out[0] = 0x49;
|
||||
out[1] = 0x49;
|
||||
set16(view, 2, 42);
|
||||
set32(view, 4, ifdAt);
|
||||
|
||||
// IFD entries must be sorted by tag.
|
||||
set16(view, ifdAt, entries);
|
||||
let at = ifdAt + 2;
|
||||
const entry = (tag: number, type: number, count: number, value: number, inline = true) => {
|
||||
set16(view, at, tag);
|
||||
set16(view, at + 2, type);
|
||||
set32(view, at + 4, count);
|
||||
if (inline) set32(view, at + 8, value);
|
||||
else {
|
||||
set16(view, at + 8, value & 0xffff);
|
||||
set16(view, at + 10, value >>> 16);
|
||||
}
|
||||
at += 12;
|
||||
};
|
||||
|
||||
entry(256, 4, 1, w);
|
||||
entry(257, 4, 1, h);
|
||||
entry(258, 3, 3, bitsAt, false);
|
||||
entry(259, 3, 1, 1);
|
||||
entry(262, 3, 1, 2);
|
||||
entry(273, 4, 1, dataAt);
|
||||
entry(277, 3, 1, 3);
|
||||
entry(278, 4, 1, h);
|
||||
entry(279, 4, 1, pixelBytes);
|
||||
entry(282, 5, 1, xResAt, false);
|
||||
entry(283, 5, 1, yResAt, false);
|
||||
entry(284, 3, 1, 1);
|
||||
entry(296, 3, 1, 2);
|
||||
if (profileLength) entry(34675, 7, profileLength, profileAt, false);
|
||||
set32(view, at, 0); // next IFD
|
||||
|
||||
// BitsPerSample = 16,16,16; rational resolution = 300/1.
|
||||
set16(view, bitsAt, 16);
|
||||
set16(view, bitsAt + 2, 16);
|
||||
set16(view, bitsAt + 4, 16);
|
||||
set32(view, xResAt, 300);
|
||||
set32(view, xResAt + 4, 1);
|
||||
set32(view, yResAt, 300);
|
||||
set32(view, yResAt + 4, 1);
|
||||
if (icc && profileLength) out.set(icc, profileAt);
|
||||
|
||||
// WebGL's readPixels starts at the bottom-left; TIFF rows run top-to-bottom.
|
||||
if (LE) {
|
||||
const words = new Uint16Array(out.buffer, dataAt, w * h * 3);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const srcY = h - 1 - y;
|
||||
for (let x = 0; x < w; x++) {
|
||||
const src = (srcY * w + x) * 4;
|
||||
const dst = (y * w + x) * 3;
|
||||
words[dst] = Math.round(Math.max(0, Math.min(1, pixels[src])) * 65535);
|
||||
words[dst + 1] = Math.round(Math.max(0, Math.min(1, pixels[src + 1])) * 65535);
|
||||
words[dst + 2] = Math.round(Math.max(0, Math.min(1, pixels[src + 2])) * 65535);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Rare big-endian browser: keep the file little-endian explicitly.
|
||||
for (let y = 0; y < h; y++) {
|
||||
const srcY = h - 1 - y;
|
||||
for (let x = 0; x < w; x++) {
|
||||
const src = (srcY * w + x) * 4;
|
||||
const dst = dataAt + (y * w + x) * 6;
|
||||
set16(view, dst, Math.round(Math.max(0, Math.min(1, pixels[src])) * 65535));
|
||||
set16(view, dst + 2, Math.round(Math.max(0, Math.min(1, pixels[src + 1])) * 65535));
|
||||
set16(view, dst + 4, Math.round(Math.max(0, Math.min(1, pixels[src + 2])) * 65535));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new Blob([out], { type: 'image/tiff' });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return false;
|
||||
return window.matchMedia(query).matches;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return;
|
||||
const media = window.matchMedia(query);
|
||||
const update = () => setMatches(media.matches);
|
||||
update();
|
||||
media.addEventListener?.('change', update);
|
||||
return () => media.removeEventListener?.('change', update);
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
|
||||
const PREFIX = 'lumenroom.ui.';
|
||||
|
||||
/**
|
||||
* UI state that should survive a reload without becoming catalog data.
|
||||
* Storage failures (private mode, full disk) silently fall back to memory.
|
||||
*/
|
||||
export function usePersistentState<T>(
|
||||
key: string,
|
||||
initial: T | (() => T),
|
||||
): [T, Dispatch<SetStateAction<T>>] {
|
||||
const storageKey = `${PREFIX}${key}`;
|
||||
const [value, setValue] = useState<T>(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(storageKey);
|
||||
if (raw !== null) return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
/* private mode or malformed old state */
|
||||
}
|
||||
return typeof initial === 'function' ? (initial as () => T)() : initial;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem(storageKey, JSON.stringify(value));
|
||||
} catch {
|
||||
/* storage is optional for UI preferences */
|
||||
}
|
||||
}, [storageKey, value]);
|
||||
|
||||
return [value, setValue];
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* White balance eyedropper maths.
|
||||
*
|
||||
* The grade shader applies these gains in linear light:
|
||||
* r × (1 + 0.30t + 0.06i)
|
||||
* g × (1 − 0.16i)
|
||||
* b × (1 − 0.26t + 0.06i)
|
||||
* where t = temp / 100 and i = tint / 100 (a shared luma normalisation cancels
|
||||
* out of the neutrality condition, so it is ignored here).
|
||||
*
|
||||
* Solving r·wr = g·wg and b·wb = g·wg for t and i is linear in i, which gives a
|
||||
* closed-form answer: no iteration and no drift as the sliders move.
|
||||
*/
|
||||
|
||||
const T_R = 0.3;
|
||||
const T_B = 0.26;
|
||||
const T_TINT = 0.16;
|
||||
const TINT_CROSS = 0.06;
|
||||
|
||||
function toLinear(v: number): number {
|
||||
const c = Math.min(1, Math.max(0, v));
|
||||
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
const clampRange = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
|
||||
/**
|
||||
* Temperature and tint that make a sampled source colour neutral.
|
||||
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
|
||||
* Returns null for samples too dark to carry a reliable colour cast.
|
||||
*/
|
||||
export function solveWhiteBalance(
|
||||
sample: readonly [number, number, number],
|
||||
): { temp: number; tint: number } | null {
|
||||
const r = toLinear(sample[0]);
|
||||
const g = toLinear(sample[1]);
|
||||
const b = toLinear(sample[2]);
|
||||
if (![r, g, b].every(Number.isFinite)) return null;
|
||||
if (Math.max(r, g, b) < 0.004) return null;
|
||||
|
||||
// Ratios stay finite for very saturated or very dark picks; clamping them only
|
||||
// caps how extreme the result can get, it does not affect ordinary neutrals.
|
||||
const gr = clampRange(g / Math.max(1e-4, r), 0.02, 40);
|
||||
const gb = clampRange(g / Math.max(1e-4, b), 0.02, 40);
|
||||
|
||||
const denom =
|
||||
T_R * (TINT_CROSS + T_TINT * gb) + T_B * (T_TINT * gr + TINT_CROSS);
|
||||
if (Math.abs(denom) < 1e-6) return null;
|
||||
|
||||
const ti = (T_B * (gr - 1) - T_R * (1 - gb)) / denom;
|
||||
const t = ((1 - T_TINT * ti) * gr - 1 - TINT_CROSS * ti) / T_R;
|
||||
if (!Number.isFinite(t) || !Number.isFinite(ti)) return null;
|
||||
|
||||
return {
|
||||
temp: Math.round(clampRange(t * 100, -100, 100)),
|
||||
tint: Math.round(clampRange(ti * 100, -100, 100)),
|
||||
};
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Minimal ZIP writer for photo exports. Images are already compressed, so every
|
||||
* entry is stored (method 0) instead of deflated: no CPU spent re-packing JPEGs,
|
||||
* and no extra copy of each file in memory.
|
||||
*
|
||||
* Supports UTF-8 names, up to 65535 files and up to 4 GB of total output. Larger
|
||||
* batches need ZIP64, which browsers have no business producing from a tab.
|
||||
*/
|
||||
|
||||
export interface ZipEntry {
|
||||
name: string;
|
||||
data: Blob;
|
||||
}
|
||||
|
||||
const MAX_ENTRIES = 0xffff;
|
||||
const MAX_SIZE = 0xffffffff;
|
||||
const MAX_TOTAL = MAX_SIZE - 1024 * 1024; // room for headers and the central directory
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let i = 0; i < 256; i++) {
|
||||
let c = i;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[i] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crcUpdate(crc: number, bytes: Uint8Array) {
|
||||
let c = crc;
|
||||
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
||||
return c >>> 0;
|
||||
}
|
||||
|
||||
async function blobCrc32(blob: Blob) {
|
||||
const reader = blob.stream().getReader();
|
||||
let crc = 0xffffffff;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) crc = crcUpdate(crc, value);
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function dosStamp(date: Date) {
|
||||
const year = Math.min(2107, Math.max(1980, date.getFullYear()));
|
||||
const time = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
|
||||
const day = ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
|
||||
return { time, day };
|
||||
}
|
||||
|
||||
/** Keep the entry a flat file name and make collisions predictable. */
|
||||
function safeEntryName(name: string, used: Set<string>) {
|
||||
const clean = (name || 'photo.jpg').replace(/[\\/]+/g, '-').replace(/[\u0000-\u001f]/g, '').trim();
|
||||
const base = clean || 'photo.jpg';
|
||||
if (!used.has(base.toLowerCase())) {
|
||||
used.add(base.toLowerCase());
|
||||
return base;
|
||||
}
|
||||
const dot = base.lastIndexOf('.');
|
||||
const stem = dot > 0 ? base.slice(0, dot) : base;
|
||||
const ext = dot > 0 ? base.slice(dot) : '';
|
||||
let n = 2;
|
||||
while (used.has(`${stem} (${n})${ext}`.toLowerCase())) n++;
|
||||
const unique = `${stem} (${n})${ext}`;
|
||||
used.add(unique.toLowerCase());
|
||||
return unique;
|
||||
}
|
||||
|
||||
function header(size: number, write: (view: DataView, offset: number) => void) {
|
||||
const bytes = new Uint8Array(new ArrayBuffer(size));
|
||||
write(new DataView(bytes.buffer), 0);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export async function createZipBlob(entries: ZipEntry[]): Promise<Blob> {
|
||||
if (!entries.length) throw new Error('Nothing to archive');
|
||||
if (entries.length > MAX_ENTRIES) {
|
||||
throw new Error('Too many photos for one ZIP file. Export them in smaller groups.');
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const { time, day } = dosStamp(new Date());
|
||||
const used = new Set<string>();
|
||||
const parts: BlobPart[] = [];
|
||||
const central: { name: ArrayBuffer; crc: number; size: number; offset: number }[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const name = encoder.encode(safeEntryName(entry.name, used)).buffer as ArrayBuffer;
|
||||
const size = entry.data.size;
|
||||
if (size > MAX_SIZE) throw new Error(`${entry.name} is too large for a ZIP file`);
|
||||
const crc = await blobCrc32(entry.data);
|
||||
const start = offset;
|
||||
|
||||
const local = header(30, (view, at) => {
|
||||
view.setUint32(at, 0x04034b50, true);
|
||||
view.setUint16(at + 4, 20, true); // version needed
|
||||
view.setUint16(at + 6, 0x0800, true); // UTF-8 names
|
||||
view.setUint16(at + 8, 0, true); // stored
|
||||
view.setUint16(at + 10, time, true);
|
||||
view.setUint16(at + 12, day, true);
|
||||
view.setUint32(at + 14, crc, true);
|
||||
view.setUint32(at + 18, size, true);
|
||||
view.setUint32(at + 22, size, true);
|
||||
view.setUint16(at + 26, name.byteLength, true);
|
||||
view.setUint16(at + 28, 0, true);
|
||||
});
|
||||
parts.push(local, name, entry.data);
|
||||
offset += local.length + name.byteLength + size;
|
||||
|
||||
central.push({ name, crc, size, offset: start });
|
||||
if (offset > MAX_TOTAL) {
|
||||
throw new Error('This batch is too large for one ZIP file. Export it in smaller groups.');
|
||||
}
|
||||
}
|
||||
|
||||
const centralStart = offset;
|
||||
let centralSize = 0;
|
||||
for (const file of central) {
|
||||
const record = header(46, (view, at) => {
|
||||
view.setUint32(at, 0x02014b50, true);
|
||||
view.setUint16(at + 4, 20, true); // made by
|
||||
view.setUint16(at + 6, 20, true); // needed
|
||||
view.setUint16(at + 8, 0x0800, true);
|
||||
view.setUint16(at + 10, 0, true); // stored
|
||||
view.setUint16(at + 12, time, true);
|
||||
view.setUint16(at + 14, day, true);
|
||||
view.setUint32(at + 16, file.crc, true);
|
||||
view.setUint32(at + 20, file.size, true);
|
||||
view.setUint32(at + 24, file.size, true);
|
||||
view.setUint16(at + 28, file.name.byteLength, true);
|
||||
view.setUint16(at + 30, 0, true); // extra
|
||||
view.setUint16(at + 32, 0, true); // comment
|
||||
view.setUint16(at + 34, 0, true); // disk
|
||||
view.setUint16(at + 36, 0, true); // internal attrs
|
||||
view.setUint32(at + 38, 0, true); // external attrs
|
||||
view.setUint32(at + 42, file.offset, true);
|
||||
});
|
||||
parts.push(record, file.name);
|
||||
centralSize += record.length + file.name.byteLength;
|
||||
}
|
||||
|
||||
const end = header(22, (view, at) => {
|
||||
view.setUint32(at, 0x06054b50, true);
|
||||
view.setUint16(at + 4, 0, true);
|
||||
view.setUint16(at + 6, 0, true);
|
||||
view.setUint16(at + 8, central.length, true);
|
||||
view.setUint16(at + 10, central.length, true);
|
||||
view.setUint32(at + 12, centralSize, true);
|
||||
view.setUint32(at + 16, centralStart, true);
|
||||
view.setUint16(at + 20, 0, true);
|
||||
});
|
||||
parts.push(end);
|
||||
|
||||
return new Blob(parts, { type: 'application/zip' });
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
export function zipFileName(date = new Date()) {
|
||||
return `luminary-${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}.zip`;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './App';
|
||||
import ProofingGallery from './components/ProofingGallery';
|
||||
import JoinPage from './components/JoinPage';
|
||||
import './styles.css';
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (!root) throw new Error('root element missing');
|
||||
|
||||
// Proofing links are public: /g/<token> renders the gallery straight away and
|
||||
// never mounts the editor or asks for a session.
|
||||
const galleryMatch = /^\/g\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname);
|
||||
// Invite links are public too: the token decides whether signup is allowed.
|
||||
const joinMatch = /^\/join\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname);
|
||||
|
||||
createRoot(root).render(
|
||||
galleryMatch ? (
|
||||
<ProofingGallery token={galleryMatch[1]} />
|
||||
) : joinMatch ? (
|
||||
<JoinPage token={joinMatch[1]} />
|
||||
) : (
|
||||
<App />
|
||||
),
|
||||
);
|
||||
+5434
File diff suppressed because it is too large
Load Diff
+323
@@ -0,0 +1,323 @@
|
||||
export type ViewMode = 'grid' | 'develop';
|
||||
export type Flag = 'none' | 'pick' | 'reject';
|
||||
export type ColorLabel = '' | 'red' | 'yellow' | 'green' | 'blue' | 'purple';
|
||||
/** Contrast filter placed over the lens when shooting black & white film. */
|
||||
export type BwFilter = 'none' | 'yellow' | 'orange' | 'red' | 'green' | 'blue';
|
||||
export type CurveChannel = 'rgb' | 'red' | 'green' | 'blue';
|
||||
|
||||
export interface CurvePoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface CropState {
|
||||
/** normalized crop rect inside the straightened frame, origin top-left */
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
/** straighten angle in degrees */
|
||||
angle: number;
|
||||
/** extra 90° turns applied before the straighten angle, 0–3 */
|
||||
quarter: number;
|
||||
/** locked aspect preset id, "free" or "original" */
|
||||
aspect: string;
|
||||
flipH: boolean;
|
||||
flipV: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* One spot-heal patch. Coordinates are normalized source-image uv (y down),
|
||||
* r is a fraction of the source width, and sx/sy mark the area sampled to cover
|
||||
* the spot.
|
||||
*/
|
||||
export interface HealSpot {
|
||||
x: number;
|
||||
y: number;
|
||||
r: number;
|
||||
/** edge softness 0–100 */
|
||||
feather: number;
|
||||
sx: number;
|
||||
sy: number;
|
||||
}
|
||||
|
||||
export type LocalMaskKind = 'brush' | 'linear' | 'radial' | 'raster';
|
||||
|
||||
/** A generated, low-resolution raster mask (auto subject / sky / background). */
|
||||
export interface RasterMask {
|
||||
/** base64-encoded 8-bit coverage, width × height */
|
||||
data: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface LocalPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface LocalStroke {
|
||||
points: LocalPoint[];
|
||||
/** brush radius as a fraction of the source width */
|
||||
size: number;
|
||||
erase?: boolean;
|
||||
}
|
||||
|
||||
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */
|
||||
export interface LocalLayer {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: LocalMaskKind;
|
||||
inverted: boolean;
|
||||
/** softness of the mask edge, 0–100 */
|
||||
feather: number;
|
||||
brush: { strokes: LocalStroke[] };
|
||||
linear: { x1: number; y1: number; x2: number; y2: number };
|
||||
radial: { cx: number; cy: number; rx: number; ry: number };
|
||||
raster?: RasterMask;
|
||||
/** luminance and colour limits applied on top of the shape */
|
||||
range: {
|
||||
enabled: boolean;
|
||||
lumaMin: number;
|
||||
lumaMax: number;
|
||||
hue: number;
|
||||
hueRange: number;
|
||||
satMin: number;
|
||||
};
|
||||
adjust: {
|
||||
exposure: number;
|
||||
contrast: number;
|
||||
highlights: number;
|
||||
shadows: number;
|
||||
temp: number;
|
||||
tint: number;
|
||||
saturation: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Manual perspective and lens corrections. */
|
||||
export interface LensCorrections {
|
||||
distortion: boolean;
|
||||
tca: boolean;
|
||||
vignetting: boolean;
|
||||
}
|
||||
|
||||
export interface LensProfile {
|
||||
/** Lensfun maker/model and the sensor crop used for calibration. */
|
||||
maker: string;
|
||||
model: string;
|
||||
crop: number;
|
||||
cameraMaker?: string;
|
||||
cameraModel?: string;
|
||||
corrections: LensCorrections;
|
||||
distance?: number;
|
||||
}
|
||||
|
||||
export interface GeometryEdits {
|
||||
/** barrel/pincushion, -100–100 */
|
||||
distortion: number;
|
||||
/** vertical keystone, -100–100 */
|
||||
vertical: number;
|
||||
/** horizontal keystone, -100–100 */
|
||||
horizontal: number;
|
||||
/** fine rotation in degrees, -15–15 */
|
||||
rotate: number;
|
||||
/** scale in percent, 50–200; hides transformed edges */
|
||||
scale: number;
|
||||
}
|
||||
|
||||
export interface Edits {
|
||||
temp: number;
|
||||
tint: number;
|
||||
exposure: number;
|
||||
/** pulls clipped highlights back into range without shifting hue */
|
||||
recovery: number;
|
||||
contrast: number;
|
||||
highlights: number;
|
||||
shadows: number;
|
||||
whites: number;
|
||||
blacks: number;
|
||||
texture: number;
|
||||
clarity: number;
|
||||
dehaze: number;
|
||||
vibrance: number;
|
||||
saturation: number;
|
||||
bw: boolean;
|
||||
/** colored filter simulated in black & white mode */
|
||||
bwFilter: BwFilter;
|
||||
/** how strongly that filter acts, 0–100 */
|
||||
bwFilterAmount: number;
|
||||
curve: Record<CurveChannel, CurvePoint[]>;
|
||||
/** region tone shaping applied on top of the point curve */
|
||||
parametric: { highlights: number; lights: number; darks: number; blacks: number };
|
||||
hsl: { hue: number[]; sat: number[]; lum: number[] };
|
||||
grading: {
|
||||
shadows: { h: number; s: number };
|
||||
highlights: { h: number; s: number };
|
||||
balance: number;
|
||||
};
|
||||
/** lensSoftness compensates for edge softness, 0–100 */
|
||||
sharpen: { amount: number; radius: number; detail: number; mask: number; lensSoftness: number };
|
||||
/** paper/output simulation for soft proofing */
|
||||
proof: { enabled: boolean; paper: 'matte' | 'gloss' | 'newsprint'; blackPoint: number; gamut: boolean };
|
||||
/** chroma is the colour-noise amount; chromaDetail trades smoothing for fine colour */
|
||||
noise: { luminance: number; detail: number; chroma: number; chromaDetail: number };
|
||||
/**
|
||||
* Server-rendered, detail-preserving denoise. `key` is the parameter hash of a
|
||||
* generated asset and is null until one exists; `amount` blends it over the
|
||||
* source. Separate from `noise`, which is a small GPU-side filter.
|
||||
*/
|
||||
aiDenoise: { amount: number; key: string | null; model: string };
|
||||
/** fringe removal amounts for the two casts lens CA produces */
|
||||
defringe: { purple: number; green: number };
|
||||
/** spot healing, applied to the source before grading */
|
||||
heal: HealSpot[];
|
||||
/** local adjustment layers, composited after the global grade */
|
||||
local: LocalLayer[];
|
||||
/** lens distortion and perspective correction, applied while sampling */
|
||||
geometry: GeometryEdits;
|
||||
/** optional Lensfun calibration profile; focal/aperture come from the photo */
|
||||
lens?: LensProfile;
|
||||
vignette: { amount: number; midpoint: number; feather: number };
|
||||
/** roughness leans from creamy clumps (0) to crisp per-pixel bite (100) */
|
||||
grain: { amount: number; size: number; roughness: number };
|
||||
crop: CropState;
|
||||
}
|
||||
|
||||
export interface PhotoMeta {
|
||||
camera?: string;
|
||||
lens?: string;
|
||||
iso?: number;
|
||||
aperture?: number;
|
||||
shutter?: string;
|
||||
focal?: number;
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
label: string;
|
||||
ts: number;
|
||||
edits: Edits;
|
||||
}
|
||||
|
||||
export interface Snapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
ts: number;
|
||||
edits: Edits;
|
||||
}
|
||||
|
||||
export interface MetadataPreset {
|
||||
id: string;
|
||||
name: string;
|
||||
creator?: string;
|
||||
copyright?: string;
|
||||
keywords: string[];
|
||||
}
|
||||
|
||||
export interface SmartCollection {
|
||||
id: string;
|
||||
name: string;
|
||||
filters: Filters;
|
||||
eventId?: string;
|
||||
sort: SortKey;
|
||||
asc: boolean;
|
||||
}
|
||||
|
||||
export interface MergeInfo {
|
||||
kind: 'hdr' | 'panorama' | 'focus';
|
||||
sourceIds: string[];
|
||||
}
|
||||
|
||||
export interface PhotoRecord {
|
||||
id: string;
|
||||
eventId: string;
|
||||
/** manual sort position inside the event */
|
||||
order?: number;
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
size: number;
|
||||
mime: string;
|
||||
addedAt: number;
|
||||
takenAt?: number;
|
||||
meta: PhotoMeta;
|
||||
thumb: string;
|
||||
rating: number;
|
||||
/** set when the photo sits in the trash; cleared on restore */
|
||||
deletedAt?: number;
|
||||
flag: Flag;
|
||||
color: ColorLabel;
|
||||
keywords: string[];
|
||||
title?: string;
|
||||
caption?: string;
|
||||
creator?: string;
|
||||
copyright?: string;
|
||||
/** virtual copies point at the master but keep their own edits */
|
||||
copyOf?: string;
|
||||
copyName?: string;
|
||||
snapshots?: Snapshot[];
|
||||
/** set on files generated by HDR / panorama / focus merge */
|
||||
merge?: MergeInfo;
|
||||
edits: Edits;
|
||||
history: HistoryEntry[];
|
||||
/** true when the original is a camera raw decoded by the server */
|
||||
raw?: boolean;
|
||||
/** how the editable proxy was produced */
|
||||
decode?: 'libraw' | 'embedded';
|
||||
/** server URL for the editable proxy (raw only) */
|
||||
previewUrl?: string;
|
||||
/** server URL for the grid thumbnail */
|
||||
thumbUrl?: string;
|
||||
/** timestamp of the last rendered client proof published to the server */
|
||||
proofAt?: number;
|
||||
/** Account this cached record belongs to (server workspaces). */
|
||||
workspace?: string;
|
||||
/** Set when the photo is proxied from a dashboard bridge session. */
|
||||
bridgeSource?: { sessionId: string; sourceId: string };
|
||||
/** Photos sharing a stack id collapse to their lowest-index member. */
|
||||
stackId?: string;
|
||||
stackIndex?: number;
|
||||
}
|
||||
|
||||
export interface EventRecord {
|
||||
id: string;
|
||||
name: string;
|
||||
date?: number;
|
||||
createdAt: number;
|
||||
notes?: string;
|
||||
/** sidebar position */
|
||||
order?: number;
|
||||
/** Account this cached record belongs to (server workspaces). */
|
||||
workspace?: string;
|
||||
/** Set when this event is a temporary import from the dashboard bridge. */
|
||||
bridge?: {
|
||||
sessionId: string;
|
||||
sourceEventId: string;
|
||||
/** Where "Back to dashboard" goes. */
|
||||
dashboardUrl: string;
|
||||
expiresAt: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Filters {
|
||||
minRating: number;
|
||||
flag: Flag | 'any';
|
||||
colors: ColorLabel[];
|
||||
text: string;
|
||||
editedOnly: boolean;
|
||||
unrated: boolean;
|
||||
/** only photos picked by a client in a proofing gallery */
|
||||
proofed: boolean;
|
||||
/** client approval state from the proofing gallery */
|
||||
clientStatus: 'any' | 'approved' | 'changes';
|
||||
}
|
||||
|
||||
export type SortKey = 'taken' | 'added' | 'name' | 'rating' | 'custom';
|
||||
|
||||
export interface Preset {
|
||||
id: string;
|
||||
name: string;
|
||||
group: string;
|
||||
edits: Partial<Omit<Edits, 'crop'>>;
|
||||
custom?: boolean;
|
||||
}
|
||||
Reference in New Issue
Block a user