feat(editor): bridge the advanced photo editor into the event workflow
CI / build (push) Has been cancelled
CI / build (push) Has been cancelled
Event photos can now be opened in Lumenroom, a WebGL2 develop module, from the photo editor's Advanced button. The dashboard signs a short-lived token scoped to one user and event; Lumenroom exchanges it, imports the event's photo list and proxies bytes on demand, so nothing is copied and the temporary catalog expires with the bridge session. Saving in Lumenroom renders the photo and writes it back as the event's edited JPEG, with the advanced recipe kept in event_photos.advanced_edit_json. Lumenroom is vendored under lumenroom/ and built as a second compose service, so one clone and `docker compose up -d --build` deploys both apps. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
import type { EventRecord, PhotoRecord, Preset } from '../types';
|
||||
|
||||
export interface Health {
|
||||
ok: boolean;
|
||||
app: string;
|
||||
version: string;
|
||||
needsSetup: boolean;
|
||||
registrationOpen: boolean;
|
||||
photos: number;
|
||||
bytes: number;
|
||||
raw: { libraw: boolean; sharp: boolean; formats: string[] };
|
||||
}
|
||||
|
||||
export interface SessionUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export interface UploadResult {
|
||||
raw: boolean;
|
||||
engine?: 'libraw' | 'embedded';
|
||||
width?: number;
|
||||
height?: number;
|
||||
mime?: string;
|
||||
size?: number;
|
||||
previewUrl?: string;
|
||||
thumbUrl?: string;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(path, { credentials: 'same-origin', ...init });
|
||||
} catch {
|
||||
throw new ApiError('Cannot reach the Lumenroom server', 0);
|
||||
}
|
||||
if (!res.ok) {
|
||||
let message = `Request failed (${res.status})`;
|
||||
try {
|
||||
const body = (await res.json()) as { error?: string };
|
||||
if (body?.error) message = body.error;
|
||||
} catch {
|
||||
/* non-JSON error body */
|
||||
}
|
||||
throw new ApiError(message, res.status);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
function jsonBody(payload: unknown): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns null when the app is running without a server (pure browser library). */
|
||||
export async function getHealth(): Promise<Health | null> {
|
||||
try {
|
||||
const res = await fetch('/api/health', { credentials: 'same-origin' });
|
||||
if (!res.ok) return null;
|
||||
const body = (await res.json()) as Health;
|
||||
return body?.ok ? body : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function register(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
name?: string;
|
||||
invite?: string;
|
||||
}): Promise<SessionUser> {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input));
|
||||
return res.user;
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<SessionUser> {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password }));
|
||||
return res.user;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await request('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function currentUser(): Promise<SessionUser | null> {
|
||||
try {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/me');
|
||||
return res.user;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SyncPayload {
|
||||
user: SessionUser;
|
||||
events: EventRecord[];
|
||||
photos: PhotoRecord[];
|
||||
presets: Preset[];
|
||||
}
|
||||
|
||||
export function pullAll(): Promise<SyncPayload> {
|
||||
return request<SyncPayload>('/api/sync');
|
||||
}
|
||||
|
||||
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> {
|
||||
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
|
||||
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
body: file,
|
||||
});
|
||||
}
|
||||
|
||||
export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
|
||||
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(photo),
|
||||
}).then((res) => res.photo);
|
||||
}
|
||||
|
||||
export function deletePhotoRemote(id: string): Promise<void> {
|
||||
return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function pushEvent(event: EventRecord): Promise<EventRecord> {
|
||||
return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(event),
|
||||
}).then((res) => res.event);
|
||||
}
|
||||
|
||||
export function deleteEventRemote(id: string): Promise<void> {
|
||||
return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function pushPresets(presets: Preset[]): Promise<void> {
|
||||
return request('/api/presets', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ presets }),
|
||||
});
|
||||
}
|
||||
@@ -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,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,296 @@
|
||||
import type { BwFilter, ColorLabel, CropState, CurvePoint, Edits, Flag, PhotoRecord, PhotoMeta } from '../types';
|
||||
import { clamp, clamp01, sanitizeCurve } from './curves';
|
||||
|
||||
export interface HueBand {
|
||||
key: string;
|
||||
name: string;
|
||||
center: number;
|
||||
swatch: string;
|
||||
}
|
||||
|
||||
export const HUE_BANDS: HueBand[] = [
|
||||
{ key: 'red', name: 'Red', center: 0, swatch: '#e2453c' },
|
||||
{ key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' },
|
||||
{ key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' },
|
||||
{ key: 'green', name: 'Green', center: 120, swatch: '#57a95a' },
|
||||
{ key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' },
|
||||
{ key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' },
|
||||
{ key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' },
|
||||
{ key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Photographic contrast filters for black & white: transmission per channel.
|
||||
* A red filter passes red and blocks blue, so skies print almost black.
|
||||
*/
|
||||
export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [
|
||||
{ id: 'none', label: 'None', rgb: [1, 1, 1] },
|
||||
{ id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] },
|
||||
{ id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] },
|
||||
{ id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] },
|
||||
{ id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] },
|
||||
{ id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] },
|
||||
];
|
||||
|
||||
export function bwFilterRgb(id: BwFilter): [number, number, number] {
|
||||
return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS transform that shows a grid thumbnail in the photo's *current* orientation.
|
||||
* Uses the same order as the renderer: flips act on the photo, then the quarter
|
||||
* turns and straighten rotate it, and the result is scaled so the rotated image
|
||||
* still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps).
|
||||
*/
|
||||
export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
|
||||
const { quarter, angle, flipH, flipV } = photo.edits.crop;
|
||||
const deg = quarter * 90 + angle;
|
||||
if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none';
|
||||
|
||||
const w = Math.max(1, photo.width || 1);
|
||||
const h = Math.max(1, photo.height || 1);
|
||||
const boxH = 1 / boxAspect;
|
||||
// object-fit: cover — the photo already fills the card before any transform.
|
||||
const cover = Math.max(1 / w, boxH / h);
|
||||
const dw = w * cover;
|
||||
const dh = h * cover;
|
||||
const rad = (Math.abs(deg) * Math.PI) / 180;
|
||||
const c = Math.abs(Math.cos(rad));
|
||||
const s = Math.abs(Math.sin(rad));
|
||||
// A rotated photo has to contain all four corners of the card, not just its
|
||||
// bounding box: after un-rotating a card corner by -deg it sits at
|
||||
// ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide
|
||||
// and tall. Fitting the bounding box instead leaves gaps on angle-only turns.
|
||||
const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh);
|
||||
// A thumbnail's rounded pixel size can differ from the record's ratio by a
|
||||
// fraction of a percent; a hair of slack keeps it from showing a sliver at
|
||||
// the edge. It is invisible at any real card size.
|
||||
const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit;
|
||||
|
||||
const parts = [`rotate(${deg.toFixed(2)}deg)`];
|
||||
// Round up: rounding the scale down would leave a hairline gap at the edge.
|
||||
const rounded = Math.ceil(fit * 1e4) / 1e4;
|
||||
if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`);
|
||||
if (flipH) parts.push('scaleX(-1)');
|
||||
if (flipV) parts.push('scaleY(-1)');
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [
|
||||
{ id: 'original', label: 'Original', ratio: null },
|
||||
{ id: 'free', label: 'Free', ratio: null },
|
||||
{ id: '1:1', label: '1 × 1', ratio: 1 },
|
||||
{ id: '4:5', label: '4 × 5', ratio: 4 / 5 },
|
||||
{ id: '5:4', label: '5 × 4', ratio: 5 / 4 },
|
||||
{ id: '4:3', label: '4 × 3', ratio: 4 / 3 },
|
||||
{ id: '3:2', label: '3 × 2', ratio: 3 / 2 },
|
||||
{ id: '16:9', label: '16 × 9', ratio: 16 / 9 },
|
||||
{ id: '2:1', label: '2 × 1', ratio: 2 },
|
||||
{ id: '9:16', label: '9 × 16', ratio: 9 / 16 },
|
||||
];
|
||||
|
||||
export function defaultCrop(): CropState {
|
||||
return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false };
|
||||
}
|
||||
|
||||
export function identityCurve(): CurvePoint[] {
|
||||
return [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
];
|
||||
}
|
||||
|
||||
export function defaultEdits(): Edits {
|
||||
return {
|
||||
temp: 0,
|
||||
tint: 0,
|
||||
exposure: 0,
|
||||
contrast: 0,
|
||||
highlights: 0,
|
||||
shadows: 0,
|
||||
whites: 0,
|
||||
blacks: 0,
|
||||
texture: 0,
|
||||
clarity: 0,
|
||||
dehaze: 0,
|
||||
vibrance: 0,
|
||||
saturation: 0,
|
||||
bw: false,
|
||||
bwFilter: 'none',
|
||||
bwFilterAmount: 100,
|
||||
curve: {
|
||||
rgb: identityCurve(),
|
||||
red: identityCurve(),
|
||||
green: identityCurve(),
|
||||
blue: identityCurve(),
|
||||
},
|
||||
hsl: {
|
||||
hue: HUE_BANDS.map(() => 0),
|
||||
sat: HUE_BANDS.map(() => 0),
|
||||
lum: HUE_BANDS.map(() => 0),
|
||||
},
|
||||
grading: {
|
||||
shadows: { h: 210, s: 0 },
|
||||
highlights: { h: 45, s: 0 },
|
||||
balance: 0,
|
||||
},
|
||||
sharpen: { amount: 0, radius: 1, detail: 25 },
|
||||
noise: { luminance: 0, detail: 50 },
|
||||
vignette: { amount: 0, midpoint: 50, feather: 50 },
|
||||
grain: { amount: 0, size: 25, roughness: 50 },
|
||||
crop: defaultCrop(),
|
||||
};
|
||||
}
|
||||
|
||||
function bands(input: unknown): number[] {
|
||||
const arr = Array.isArray(input) ? input : [];
|
||||
return HUE_BANDS.map((_, i) => {
|
||||
const v = arr[i];
|
||||
return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0;
|
||||
});
|
||||
}
|
||||
|
||||
function num(value: unknown, fallback: number, lo: number, hi: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback;
|
||||
}
|
||||
|
||||
/** Deep-merge stored edits with the current defaults so older records keep working. */
|
||||
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
|
||||
const d = defaultEdits();
|
||||
if (!input) return d;
|
||||
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
|
||||
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
|
||||
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
|
||||
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
|
||||
const vignette = (input.vignette ?? {}) as Partial<Edits['vignette']>;
|
||||
const grain = (input.grain ?? {}) as Partial<Edits['grain']>;
|
||||
const crop = (input.crop ?? {}) as Partial<CropState>;
|
||||
|
||||
return {
|
||||
...d,
|
||||
...input,
|
||||
temp: num(input.temp, 0, -100, 100),
|
||||
tint: num(input.tint, 0, -100, 100),
|
||||
exposure: num(input.exposure, 0, -5, 5),
|
||||
contrast: num(input.contrast, 0, -100, 100),
|
||||
highlights: num(input.highlights, 0, -100, 100),
|
||||
shadows: num(input.shadows, 0, -100, 100),
|
||||
whites: num(input.whites, 0, -100, 100),
|
||||
blacks: num(input.blacks, 0, -100, 100),
|
||||
texture: num(input.texture, 0, -100, 100),
|
||||
clarity: num(input.clarity, 0, -100, 100),
|
||||
dehaze: num(input.dehaze, 0, -100, 100),
|
||||
vibrance: num(input.vibrance, 0, -100, 100),
|
||||
saturation: num(input.saturation, 0, -100, 100),
|
||||
bw: !!input.bw,
|
||||
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
|
||||
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
|
||||
curve: {
|
||||
rgb: sanitizeCurve(curve.rgb),
|
||||
red: sanitizeCurve(curve.red),
|
||||
green: sanitizeCurve(curve.green),
|
||||
blue: sanitizeCurve(curve.blue),
|
||||
},
|
||||
hsl: {
|
||||
hue: bands(input.hsl?.hue),
|
||||
sat: bands(input.hsl?.sat),
|
||||
lum: bands(input.hsl?.lum),
|
||||
},
|
||||
grading: {
|
||||
shadows: {
|
||||
h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360),
|
||||
s: num(grading.shadows?.s, 0, 0, 100),
|
||||
},
|
||||
highlights: {
|
||||
h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360),
|
||||
s: num(grading.highlights?.s, 0, 0, 100),
|
||||
},
|
||||
balance: num(grading.balance, 0, -100, 100),
|
||||
},
|
||||
sharpen: {
|
||||
amount: num(sharpen.amount, 0, 0, 150),
|
||||
radius: num(sharpen.radius, 1, 0.5, 3),
|
||||
detail: num(sharpen.detail, 25, 0, 100),
|
||||
},
|
||||
noise: {
|
||||
luminance: num(noise.luminance, 0, 0, 100),
|
||||
detail: num(noise.detail, 50, 0, 100),
|
||||
},
|
||||
vignette: {
|
||||
amount: num(vignette.amount, 0, -100, 100),
|
||||
midpoint: num(vignette.midpoint, 50, 0, 100),
|
||||
feather: num(vignette.feather, 50, 0, 100),
|
||||
},
|
||||
grain: {
|
||||
amount: num(grain.amount, 0, 0, 100),
|
||||
size: num(grain.size, 25, 10, 100),
|
||||
roughness: num(grain.roughness, 50, 0, 100),
|
||||
},
|
||||
crop: {
|
||||
x: clamp01(num(crop.x, 0, 0, 1)),
|
||||
y: clamp01(num(crop.y, 0, 0, 1)),
|
||||
w: clamp01(num(crop.w, 1, 0.02, 1)),
|
||||
h: clamp01(num(crop.h, 1, 0.02, 1)),
|
||||
angle: num(crop.angle, 0, -45, 45),
|
||||
quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter)
|
||||
? ((Math.round(crop.quarter) % 4) + 4) % 4
|
||||
: 0,
|
||||
aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original',
|
||||
flipH: !!crop.flipH,
|
||||
flipV: !!crop.flipV,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const editCache = new WeakMap<Edits, boolean>();
|
||||
|
||||
export function isEdited(edits: Edits): boolean {
|
||||
const cached = editCache.get(edits);
|
||||
if (cached !== undefined) return cached;
|
||||
const d = defaultEdits();
|
||||
const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } });
|
||||
const result = strip(edits) !== strip(d);
|
||||
editCache.set(edits, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
|
||||
const edits = normalizeEdits(input.edits);
|
||||
const addedAt = input.addedAt ?? Date.now();
|
||||
const meta: PhotoMeta = input.meta ?? {};
|
||||
return {
|
||||
id: input.id,
|
||||
eventId: input.eventId ?? '',
|
||||
order: typeof input.order === 'number' ? input.order : undefined,
|
||||
raw: !!input.raw,
|
||||
decode: input.decode,
|
||||
previewUrl: input.previewUrl,
|
||||
thumbUrl: input.thumbUrl,
|
||||
name: input.name ?? 'Untitled',
|
||||
width: input.width ?? 0,
|
||||
height: input.height ?? 0,
|
||||
size: input.size ?? 0,
|
||||
mime: input.mime ?? 'image/jpeg',
|
||||
addedAt,
|
||||
takenAt: input.takenAt,
|
||||
meta,
|
||||
thumb: input.thumb ?? '',
|
||||
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
|
||||
flag: (input.flag ?? 'none') as Flag,
|
||||
color: (input.color ?? '') as ColorLabel,
|
||||
keywords: Array.isArray(input.keywords) ? input.keywords : [],
|
||||
edits,
|
||||
history:
|
||||
Array.isArray(input.history) && input.history.length
|
||||
? input.history
|
||||
: [{ label: 'Import', ts: addedAt, edits }],
|
||||
};
|
||||
}
|
||||
|
||||
export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [
|
||||
{ value: 'red', name: 'Red', hex: '#e05252' },
|
||||
{ value: 'yellow', name: 'Yellow', hex: '#e0c04a' },
|
||||
{ value: 'green', name: 'Green', hex: '#56b268' },
|
||||
{ value: 'blue', name: 'Blue', hex: '#4f86e0' },
|
||||
{ value: 'purple', name: 'Purple', hex: '#9b6ede' },
|
||||
];
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { Edits, PhotoRecord } from '../types';
|
||||
import { getBitmap } from './images';
|
||||
import { normalizeEdits } from './edits';
|
||||
import { outputSize, Renderer } from '../gl/renderer';
|
||||
|
||||
export type ExportFormat = 'jpeg' | 'png' | 'webp';
|
||||
export type ResizeMode = 'none' | 'longEdge' | 'percent';
|
||||
|
||||
export interface ExportOptions {
|
||||
format: ExportFormat;
|
||||
quality: number;
|
||||
resize: ResizeMode;
|
||||
longEdge: number;
|
||||
percent: number;
|
||||
nameTemplate: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_EXPORT: ExportOptions = {
|
||||
format: 'jpeg',
|
||||
quality: 92,
|
||||
resize: 'none',
|
||||
longEdge: 3000,
|
||||
percent: 100,
|
||||
nameTemplate: '{name}',
|
||||
};
|
||||
|
||||
const MIME: Record<ExportFormat, string> = {
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
};
|
||||
|
||||
const EXT: Record<ExportFormat, string> = {
|
||||
jpeg: 'jpg',
|
||||
png: 'png',
|
||||
webp: 'webp',
|
||||
};
|
||||
|
||||
function download(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 4000);
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
export function buildFileName(template: string, photo: PhotoRecord, index: number, opts: ExportOptions) {
|
||||
const stamp = new Date(photo.takenAt ?? photo.addedAt);
|
||||
const base = photo.name.replace(/\.[^.]+$/, '') || 'export';
|
||||
const name = (template || '{name}')
|
||||
.replace(/\{name\}/g, base)
|
||||
.replace(/\{date\}/g, `${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}`)
|
||||
.replace(/\{time\}/g, `${pad(stamp.getHours())}${pad(stamp.getMinutes())}`)
|
||||
.replace(/\{index\}/g, String(index + 1).padStart(3, '0'))
|
||||
.replace(/[\\/:*?"<>|]+/g, '-')
|
||||
.trim();
|
||||
return `${name || 'export'}.${EXT[opts.format]}`;
|
||||
}
|
||||
|
||||
function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts: ExportOptions) {
|
||||
const size = outputSize(edits, bitmap.width, bitmap.height);
|
||||
const longEdge = Math.max(size.w, size.h);
|
||||
let scale = 1;
|
||||
if (opts.resize === 'longEdge' && opts.longEdge > 0 && longEdge > opts.longEdge) {
|
||||
scale = opts.longEdge / longEdge;
|
||||
} else if (opts.resize === 'percent') {
|
||||
scale = Math.min(2, Math.max(0.05, opts.percent / 100));
|
||||
}
|
||||
return {
|
||||
w: Math.max(1, Math.round(size.w * scale)),
|
||||
h: Math.max(1, Math.round(size.h * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
|
||||
const bitmap = await getBitmap(photo);
|
||||
const edits = normalizeEdits(photo.edits);
|
||||
const { w, h } = targetSize(photo, edits, bitmap, opts);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
const renderer = new Renderer(canvas);
|
||||
try {
|
||||
renderer.setImage(bitmap);
|
||||
renderer.render(edits, { width: w, height: h });
|
||||
const mime = MIME[opts.format];
|
||||
const blob = await new Promise<Blob | null>((resolve) =>
|
||||
canvas.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
|
||||
);
|
||||
if (!blob) throw new Error('Export failed while encoding the image');
|
||||
return blob;
|
||||
} finally {
|
||||
renderer.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportPhotos(
|
||||
photos: PhotoRecord[],
|
||||
opts: ExportOptions,
|
||||
onProgress?: (done: number, total: number) => void,
|
||||
): Promise<{ count: number; failed: string[] }> {
|
||||
let count = 0;
|
||||
const failed: string[] = [];
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
const photo = photos[i];
|
||||
try {
|
||||
const blob = await renderPhotoBlob(photo, opts);
|
||||
download(blob, buildFileName(opts.nameTemplate, photo, i, opts));
|
||||
count++;
|
||||
} catch (err) {
|
||||
console.error('Export failed for', photo.name, err);
|
||||
failed.push(photo.name);
|
||||
}
|
||||
onProgress?.(i + 1, photos.length);
|
||||
// Give the browser a beat so long batches keep the tab responsive.
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
return { count, failed };
|
||||
}
|
||||
|
||||
/** Backwards compatible single-photo export. */
|
||||
export async function exportPhoto(photo: PhotoRecord, maxLongEdge = 0): Promise<void> {
|
||||
const opts: ExportOptions = {
|
||||
...DEFAULT_EXPORT,
|
||||
resize: maxLongEdge > 0 ? 'longEdge' : 'none',
|
||||
longEdge: maxLongEdge || DEFAULT_EXPORT.longEdge,
|
||||
};
|
||||
const blob = await renderPhotoBlob(photo, opts);
|
||||
download(blob, buildFileName(opts.nameTemplate, photo, 0, opts));
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { getAsset, putAsset } from './db';
|
||||
|
||||
const CACHE_LIMIT = 6;
|
||||
const cache = new Map<string, ImageBitmap>();
|
||||
|
||||
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
|
||||
export function remoteAssetUrl(photo: PhotoRecord): string {
|
||||
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
|
||||
return `/api/photos/${encodeURIComponent(photo.id)}/original`;
|
||||
}
|
||||
|
||||
async function fetchRemote(photo: PhotoRecord): Promise<Blob | null> {
|
||||
try {
|
||||
const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' });
|
||||
if (!res.ok) return null;
|
||||
const blob = await res.blob();
|
||||
// Cache it locally so the photo keeps working offline after the first look.
|
||||
await putAsset(photo.id, blob).catch(() => undefined);
|
||||
return blob;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
|
||||
const hit = cache.get(photo.id);
|
||||
if (hit) {
|
||||
cache.delete(photo.id);
|
||||
cache.set(photo.id, hit);
|
||||
return hit;
|
||||
}
|
||||
|
||||
let blob = await getAsset(photo.id);
|
||||
if (!blob) blob = (await fetchRemote(photo)) ?? undefined;
|
||||
if (!blob) {
|
||||
throw new Error(
|
||||
photo.raw
|
||||
? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.'
|
||||
: 'Original image data is missing from browser storage',
|
||||
);
|
||||
}
|
||||
|
||||
// Apply EXIF orientation so the pixels the editor works on are upright.
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
cache.set(photo.id, bitmap);
|
||||
while (cache.size > CACHE_LIMIT) {
|
||||
const first = cache.keys().next();
|
||||
if (first.done) break;
|
||||
const old = cache.get(first.value);
|
||||
cache.delete(first.value);
|
||||
old?.close();
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
export function evictBitmap(photoId: string) {
|
||||
const bmp = cache.get(photoId);
|
||||
if (!bmp) return;
|
||||
cache.delete(photoId);
|
||||
bmp.close();
|
||||
}
|
||||
|
||||
export function clearBitmapCache() {
|
||||
for (const bmp of cache.values()) bmp.close();
|
||||
cache.clear();
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import exifr from 'exifr';
|
||||
import type { UploadResult } from './api';
|
||||
import type { PhotoMeta, PhotoRecord } from '../types';
|
||||
import { putAsset, putPhoto } from './db';
|
||||
import { defaultEdits, normalizePhoto } from './edits';
|
||||
import { isRawFile, RAW_EXTENSIONS } from './raw';
|
||||
|
||||
export interface ImportProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
current: string;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
photos: PhotoRecord[];
|
||||
failed: { name: string; reason: string }[];
|
||||
}
|
||||
|
||||
/** Provided by the app when a Lumenroom server is connected. */
|
||||
export interface CloudImport {
|
||||
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
|
||||
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
||||
}
|
||||
|
||||
/** Files imported at once; the server bounds how many raws decode in parallel. */
|
||||
const IMPORT_CONCURRENCY = 4;
|
||||
|
||||
export function uid(): string {
|
||||
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
|
||||
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
|
||||
let cursor = 0;
|
||||
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
|
||||
for (;;) {
|
||||
const index = cursor++;
|
||||
if (index >= items.length) return;
|
||||
await fn(items[index], index);
|
||||
}
|
||||
});
|
||||
return Promise.all(runners);
|
||||
}
|
||||
|
||||
function formatShutter(time: unknown): string | undefined {
|
||||
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
|
||||
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
|
||||
return `1/${Math.round(1 / time)}s`;
|
||||
}
|
||||
|
||||
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
|
||||
try {
|
||||
const data = (await exifr.parse(file, {
|
||||
tiff: true,
|
||||
exif: true,
|
||||
gps: false,
|
||||
interop: false,
|
||||
translateValues: false,
|
||||
reviveValues: true,
|
||||
})) as Record<string, unknown> | undefined;
|
||||
if (!data) return { meta: {} };
|
||||
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
|
||||
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
|
||||
const meta: PhotoMeta = {
|
||||
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
|
||||
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
|
||||
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
|
||||
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
|
||||
shutter: formatShutter(data.ExposureTime),
|
||||
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
|
||||
};
|
||||
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
|
||||
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
|
||||
return { meta, takenAt };
|
||||
} catch {
|
||||
return { meta: {} };
|
||||
}
|
||||
}
|
||||
|
||||
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
|
||||
const max = 560;
|
||||
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
|
||||
const w = Math.max(1, Math.round(bitmap.width * scale));
|
||||
const h = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas 2D is unavailable');
|
||||
ctx.imageSmoothingQuality = 'high';
|
||||
ctx.drawImage(bitmap, 0, 0, w, h);
|
||||
return canvas.toDataURL('image/jpeg', 0.82);
|
||||
}
|
||||
|
||||
export function isSupportedFile(file: File): boolean {
|
||||
if (file.type.startsWith('image/')) return true;
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw files cannot be decoded by the browser, so they are sent to the server,
|
||||
* demosaiced there, and represented locally by the returned editable proxy.
|
||||
*/
|
||||
async function importRaw(file: File, eventId: string, keywords: string[], cloud: CloudImport): Promise<PhotoRecord> {
|
||||
const id = uid();
|
||||
const upload = await cloud.uploadOriginal(id, file, file.name);
|
||||
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
|
||||
const res = await fetch(previewUrl, { credentials: 'same-origin' });
|
||||
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
|
||||
const blob = await res.blob();
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
const thumb = await makeThumb(bitmap);
|
||||
const { meta, takenAt } = await readMeta(file);
|
||||
const width = upload.width ?? bitmap.width;
|
||||
const height = upload.height ?? bitmap.height;
|
||||
bitmap.close();
|
||||
|
||||
const record = normalizePhoto({
|
||||
id,
|
||||
eventId,
|
||||
name: file.name,
|
||||
width,
|
||||
height,
|
||||
size: file.size,
|
||||
mime: 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
takenAt: takenAt ?? file.lastModified,
|
||||
meta,
|
||||
thumb,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords,
|
||||
edits: defaultEdits(),
|
||||
history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }],
|
||||
raw: true,
|
||||
decode: upload.engine,
|
||||
previewUrl,
|
||||
});
|
||||
|
||||
await putPhoto(record);
|
||||
// No local blob: the multi-megabyte raw stays on the server.
|
||||
const saved = await cloud.push(record);
|
||||
const merged = normalizePhoto({ ...record, ...saved });
|
||||
await putPhoto(merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
async function importStandard(
|
||||
file: File,
|
||||
eventId: string,
|
||||
keywords: string[],
|
||||
cloud?: CloudImport | null,
|
||||
): Promise<PhotoRecord> {
|
||||
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
|
||||
// the thumbnail and the edited proxy agree with what the camera shot.
|
||||
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
||||
const thumb = await makeThumb(bitmap);
|
||||
const { meta, takenAt } = await readMeta(file);
|
||||
const id = uid();
|
||||
let record = normalizePhoto({
|
||||
id,
|
||||
eventId,
|
||||
name: file.name,
|
||||
width: bitmap.width,
|
||||
height: bitmap.height,
|
||||
size: file.size,
|
||||
mime: file.type || 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
takenAt: takenAt ?? file.lastModified,
|
||||
meta,
|
||||
thumb,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords,
|
||||
edits: defaultEdits(),
|
||||
history: [{ label: 'Import', ts: Date.now(), edits: defaultEdits() }],
|
||||
});
|
||||
await putAsset(id, file);
|
||||
bitmap.close();
|
||||
|
||||
if (cloud) {
|
||||
// Originals are mirrored to the server; failures fall back to a local-only import.
|
||||
try {
|
||||
await cloud.uploadOriginal(id, file, file.name);
|
||||
const saved = await cloud.push(record);
|
||||
record = normalizePhoto({ ...record, ...saved });
|
||||
} catch (err) {
|
||||
console.warn('Could not copy the original to the server', file.name, err);
|
||||
}
|
||||
}
|
||||
|
||||
await putPhoto(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
export async function importFiles(
|
||||
files: File[],
|
||||
eventId: string,
|
||||
keywords: string[] = [],
|
||||
onProgress?: (p: ImportProgress) => void,
|
||||
cloud?: CloudImport | null,
|
||||
): Promise<ImportResult> {
|
||||
const result: ImportResult = { photos: [], failed: [] };
|
||||
const images = files.filter(isSupportedFile);
|
||||
const total = images.length;
|
||||
if (!total) return result;
|
||||
|
||||
const collected: { index: number; photo: PhotoRecord }[] = [];
|
||||
let done = 0;
|
||||
|
||||
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
||||
try {
|
||||
const photo = isRawFile(file)
|
||||
? cloud
|
||||
? await importRaw(file, eventId, keywords, cloud)
|
||||
: (() => {
|
||||
throw new Error('Raw files need the Lumenroom server. Sign in, then import again.');
|
||||
})()
|
||||
: await importStandard(file, eventId, keywords, cloud);
|
||||
collected.push({ index, photo });
|
||||
} catch (err) {
|
||||
result.failed.push({
|
||||
name: file.name,
|
||||
reason: err instanceof Error ? err.message : 'Unsupported image format',
|
||||
});
|
||||
} finally {
|
||||
done += 1;
|
||||
onProgress?.({ done, total, current: file.name });
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the shoot in capture/selection order regardless of which finished first.
|
||||
collected.sort((a, b) => a.index - b.index);
|
||||
result.photos = collected.map((c) => c.photo);
|
||||
onProgress?.({ done: total, total, current: '' });
|
||||
return result;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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(',');
|
||||
Reference in New Issue
Block a user