Files
luminary/src/App.tsx
T
bhursey 0525e496e0 Say local engine in the import dialog and the offline errors
A tester saw "raw files are demosaiced by the server" and read it as an upload
to someone else's machine. In desktop mode the decoder runs in the bundle on
this PC, so the import dialog, the join page and the "cannot reach" error now
say local engine, while team-server installs keep the server wording.
2026-12-01 12:45:04 +00:00

2895 lines
101 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import AboutModal from './components/AboutModal';
import CloudPanel from './components/CloudPanel';
import CommandPalette from './components/CommandPalette';
import ContextMenu, { type MenuEntry } from './components/ContextMenu';
import Develop from './components/Develop';
import EventSidebar from './components/EventSidebar';
import ExportModal from './components/ExportModal';
import FilterBar from './components/FilterBar';
import ImportModal from './components/ImportModal';
import LibraryGrid from './components/LibraryGrid';
import PasteSettingsModal from './components/PasteSettingsModal';
import RawReprocessModal, {
type RawReprocessFailure,
type RawReprocessJob,
} from './components/RawReprocessModal';
import CullAssistModal from './components/CullAssistModal';
import TetherPanel from './components/TetherPanel';
import Shortcuts from './components/Shortcuts';
import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
import TopBar from './components/TopBar';
import { usePersistentState } from './lib/usePersistentState';
// Only mounted when the user opens them, so they are separate chunks: the grid
// and the editor are what the first paint needs.
const AdminPanel = lazy(() => import('./components/AdminPanel'));
const CompareView = lazy(() => import('./components/CompareView'));
const ImmichPanel = lazy(() => import('./components/ImmichPanel'));
const MergeModal = lazy(() => import('./components/MergeModal'));
const PrintModal = lazy(() => import('./components/PrintModal'));
const ShareModal = lazy(() => import('./components/ShareModal'));
import {
currentUser,
deleteEventRemote,
deletePhotoRemote,
createImmichEventAlbum,
getHealth,
getImmichStatus,
getQuota,
immichEventQueue,
login as apiLogin,
logout as apiLogout,
pullAll,
pullProofs,
pushEvent,
publishImmichOriginal,
pushImmichPhoto,
pushPhoto,
register as apiRegister,
reprocessRawPhoto,
uploadOriginal,
} from './lib/api';
import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api';
import {
deleteEventRecord,
deletePhotoRecord,
getAllEvents,
getAllPhotos,
getAsset,
getKV,
putAsset,
putEvent,
putPhoto,
setKV,
} from './lib/db';
import type { ExportOptions, ExportRecipe } from './lib/export';
import { DEFAULT_EXPORT, renderPhotoBlob } from './lib/export';
import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edits';
import { applyEditSections, type EditSectionId } from './lib/editSections';
import type { MergeResult } from './lib/merge';
import { evictBitmap } from './lib/images';
import { importFiles, uid } from './lib/import';
import { PRESETS } from './lib/presets';
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp';
import type {
Edits,
EventRecord,
Filters,
LocalLayer,
MetadataPreset,
PhotoRecord,
Preset,
SmartCollection,
Snapshot,
SortKey,
ViewMode,
} from './types';
const EMPTY_FILTERS: Filters = {
minRating: 0,
flag: 'any',
colors: [],
text: '',
editedOnly: false,
unrated: false,
proofed: false,
clientStatus: 'any',
};
async function blobToBase64(blob: Blob): Promise<string> {
const bytes = new Uint8Array(await blob.arrayBuffer());
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);
}
const byOrder = (a: EventRecord, b: EventRecord) =>
(a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.createdAt - b.createdAt;
export default function App() {
const [events, setEvents] = useState<EventRecord[]>([]);
const [photos, setPhotos] = useState<PhotoRecord[]>([]);
const [loaded, setLoaded] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [eventId, setEventId] = useState('all');
const [view, setView] = useState<ViewMode>('grid');
const [sidebarOpen, setSidebarOpen] = usePersistentState('library.sidebar.open', true);
const [catalogOpen, setCatalogOpen] = useState(false);
const [trashOpen, setTrashOpen] = useState(false);
const [activeId, setActiveId] = useState<string | null>(null);
const [selected, setSelected] = useState<string[]>([]);
const [anchorId, setAnchorId] = useState<string | null>(null);
const [expandedStacks, setExpandedStacks] = useState<Set<string>>(() => new Set());
const [compareOpen, setCompareOpen] = useState(false);
const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS);
const [sort, setSort] = useState<SortKey>('taken');
const [asc, setAsc] = useState(false);
const [importOpen, setImportOpen] = useState(false);
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
const [clipboard, setClipboard] = useState<Edits | null>(null);
const [clipboardSource, setClipboardSource] = useState<{ id: string; name: string } | null>(null);
const [pasteRequest, setPasteRequest] = useState<{ targets: string[]; source: Edits; sourceName: string; mode: 'paste' | 'sync' } | null>(null);
const [localClipboard, setLocalClipboard] = useState<LocalLayer | null>(null);
const [metadataPresets, setMetadataPresets] = useState<MetadataPreset[]>([]);
const [smartCollections, setSmartCollections] = useState<SmartCollection[]>([]);
const [activeCollection, setActiveCollection] = useState<string | null>(null);
const [customPresets, setCustomPresets] = useState<Preset[]>([]);
const [toast, setToast] = useState<string | null>(null);
const [undoAction, setUndoAction] = useState<{ message: string; run: () => void } | null>(null);
const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);
const [helpOpen, setHelpOpen] = useState(false);
const [aboutOpen, setAboutOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [shareEventId, setShareEventId] = useState<string | null>(null);
/** Client proofing picks, keyed to the photos they chose. */
const [proofs, setProofs] = useState<ProofSummary[]>([]);
const [quota, setQuota] = useState<QuotaState | null>(null);
const [dropActive, setDropActive] = useState(false);
const [bridgeBusy, setBridgeBusy] = useState(false);
const [cloudHealth, setCloudHealth] = useState<Health | null>(null);
const [cloudUser, setCloudUser] = useState<SessionUser | null>(null);
const [cloudOpen, setCloudOpen] = useState(false);
const [adminOpen, setAdminOpen] = useState(false);
const [immichOpen, setImmichOpen] = useState(false);
const [immichStatus, setImmichStatus] = useState<ImmichStatus | null>(null);
const [immichProgress, setImmichProgress] = useState<{
done: number;
total: number;
current: string;
} | null>(null);
const immichStatusRef = useRef<ImmichStatus | null>(null);
immichStatusRef.current = immichStatus;
const immichBusyRef = useRef(false);
// The Immich entry points only appear when this account has opted in.
useEffect(() => {
if (!cloudUser) {
setImmichStatus(null);
return;
}
let alive = true;
getImmichStatus()
.then((status) => {
if (alive) setImmichStatus(status);
})
.catch(() => {
if (alive) setImmichStatus(null);
});
return () => {
alive = false;
};
}, [cloudUser]);
useEffect(
() => () => {
},
[],
);
const [cloudBusy, setCloudBusy] = useState(false);
const [cloudError, setCloudError] = useState<string | null>(null);
const [cloudNote, setCloudNote] = useState<string | null>(null);
const [exportOpen, setExportOpen] = useState(false);
const [exportOptions, setExportOptions] = useState<ExportOptions>(DEFAULT_EXPORT);
const [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]);
const [mergeOpen, setMergeOpen] = useState(false);
const [rawJob, setRawJob] = useState<RawReprocessJob | null>(null);
const [cullOpen, setCullOpen] = useState(false);
const [tetherEventId, setTetherEventId] = useState<string | null>(null);
const rawBusyRef = useRef(false);
const rawCancelRef = useRef(false);
const rawBusy = Boolean(rawJob?.running);
const [printOpen, setPrintOpen] = useState(false);
const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
const photosRef = useRef<PhotoRecord[]>([]);
const eventsRef = useRef<EventRecord[]>([]);
const userRef = useRef<SessionUser | null>(null);
photosRef.current = photos;
eventsRef.current = events;
userRef.current = cloudUser;
const refreshQuota = useCallback(async () => {
if (!userRef.current) {
setQuota(null);
return;
}
try {
setQuota(await getQuota());
} catch {
setQuota(null);
}
}, []);
useEffect(() => {
if (!cloudUser) {
setQuota(null);
return;
}
void refreshQuota();
const timer = window.setInterval(() => void refreshQuota(), 5 * 60 * 1000);
return () => window.clearInterval(timer);
}, [cloudUser, refreshQuota]);
useEffect(() => {
let alive = true;
(async () => {
try {
const [loadedEvents, loadedPhotos, presets, metaPresets, collections, recipes] = await Promise.all([
getAllEvents(),
getAllPhotos(),
getKV<Preset[]>('customPresets'),
getKV<MetadataPreset[]>('metadataPresets'),
getKV<SmartCollection[]>('smartCollections'),
getKV<ExportRecipe[]>('exportRecipes'),
]);
if (!alive) return;
setEvents([...loadedEvents].sort(byOrder));
setPhotos(loadedPhotos.map((p) => normalizePhoto(p)));
if (Array.isArray(presets)) setCustomPresets(presets);
if (Array.isArray(metaPresets)) setMetadataPresets(metaPresets);
if (Array.isArray(collections)) setSmartCollections(collections);
if (Array.isArray(recipes)) setExportRecipes(recipes);
} catch (err) {
setLoadError(err instanceof Error ? err.message : 'Could not read local storage');
} finally {
if (alive) setLoaded(true);
}
})();
return () => {
alive = false;
};
}, []);
// Detect the team server; a missing one simply means a browser-only library.
useEffect(() => {
let alive = true;
(async () => {
const health = await getHealth();
if (!alive) return;
setCloudHealth(health);
if (health) {
const user = await currentUser();
if (alive) {
setCloudUser(user);
if (user) {
void pullProofs()
.then((next) => alive && setProofs(next))
.catch(() => undefined);
}
if (!user) {
// Account workspaces need a session (their images are private);
// photos created on this device stay visible.
setPhotos((prev) => prev.filter((p) => !p.workspace));
setEvents((prev) => prev.filter((e) => !e.workspace));
}
}
}
})();
return () => {
alive = false;
};
}, []);
useEffect(() => {
if (!toast) return;
const t = setTimeout(
() => {
setToast(null);
setUndoAction(null);
},
undoAction && toast === undoAction.message ? 7000 : 2800,
);
return () => clearTimeout(t);
}, [toast, undoAction]);
const handleProofPublished = useCallback((photoId: string, thumbUrl: string, proofAt: number) => {
setPhotos((prev) =>
prev.map((photo) => {
if (photo.id !== photoId) return photo;
const next = { ...photo, thumbUrl, proofAt };
putPhoto(next).catch((err) => console.warn('Could not cache the edited proof', err));
return next;
}),
);
}, []);
const queueSave = useCallback((photo: PhotoRecord) => {
const existing = saveTimers.current.get(photo.id);
if (existing) clearTimeout(existing);
saveTimers.current.set(
photo.id,
setTimeout(() => {
saveTimers.current.delete(photo.id);
putPhoto(photo).catch((err) => console.error('Failed to save photo', err));
if (!userRef.current) return;
const payload: PhotoRecord = photo.thumbUrl ? { ...photo, thumb: '' } : photo;
pushPhoto(payload)
.then((saved) => {
setPhotos((prev) =>
prev.map((p) =>
p.id === saved.id && (p.thumbUrl !== saved.thumbUrl || p.previewUrl !== saved.previewUrl)
? { ...p, thumbUrl: saved.thumbUrl, previewUrl: saved.previewUrl ?? p.previewUrl }
: p,
),
);
})
.catch((err) => console.warn('Could not sync photo', photo.name, err));
}, 320),
);
}, []);
const updatePhoto = useCallback(
(
id: string,
patch: Partial<PhotoRecord> | ((p: PhotoRecord) => Partial<PhotoRecord>),
historyLabel?: string,
) => {
setPhotos((prev) =>
prev.map((p) => {
if (p.id !== id) return p;
const partial = typeof patch === 'function' ? patch(p) : patch;
let next: PhotoRecord = { ...p, ...partial };
if (partial.edits && historyLabel) {
const now = Date.now();
const hist = next.history ?? [];
// Editing after Undo discards the old redo branch before the new
// history point is appended. Without this, redo could jump to an
// adjustment that is no longer part of the current timeline.
const currentIndex = hist.findIndex((entry) => entry.edits === p.edits);
const base = currentIndex >= 0 ? hist.slice(0, currentIndex + 1) : hist;
const last = base[base.length - 1];
const entry = { label: historyLabel, ts: now, edits: next.edits };
next = {
...next,
history:
last && last.label === historyLabel && now - last.ts < 1400
? [...base.slice(0, -1), entry]
: [...base, entry].slice(-90),
};
}
queueSave(next);
return next;
}),
);
},
[queueSave],
);
/**
* Re-decode selected RAW files on the server, then refresh the cached proxy so
* the grid and Develop pick up the new pixels without a reload. Existing edits
* are kept; only width, height and the decode engine change on the record.
*/
const reprocessRawPhotos = useCallback(
async (ids: string[], options: { eventName?: string } = {}) => {
if (rawBusyRef.current) {
setToast('A RAW reprocess is already running');
return;
}
const targets = photosRef.current.filter(
(photo) => ids.includes(photo.id) && photo.raw && !photo.deletedAt,
);
if (!targets.length) {
setToast('Select RAW photos to reprocess');
return;
}
if (!userRef.current) {
setToast('Sign in to the server to reprocess RAW files');
return;
}
rawBusyRef.current = true;
rawCancelRef.current = false;
const failures: RawReprocessFailure[] = [];
let attempts = 0;
setRawJob({
running: true,
done: 0,
total: targets.length,
current: targets[0].name,
eventName: options.eventName,
failures: [],
});
try {
for (let index = 0; index < targets.length; index += 1) {
if (rawCancelRef.current) break;
const photo = targets[index];
setRawJob((prev) =>
prev ? { ...prev, done: index, current: photo.name, failures: failures.slice() } : prev,
);
try {
const result = await reprocessRawPhoto(photo.id);
const res = await fetch(
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${Date.now()}`,
{ credentials: 'same-origin' },
);
if (!res.ok) throw new Error('The new preview could not be read');
const blob = await res.blob();
// Replace the cached proxy, then drop the decoded bitmap so the next
// render fetches the new pixels instead of the old ones.
await putAsset(photo.id, blob);
evictBitmap(photo.id);
const version = result.previewVersion ?? Date.now();
updatePhoto(photo.id, {
width: result.width || photo.width,
height: result.height || photo.height,
decode: result.engine ?? photo.decode,
previewVersion: version,
// The stored files keep their names; the query is only a cache buster.
previewUrl:
result.previewUrl ??
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${version}`,
thumbUrl:
result.thumbUrl ??
`/api/photos/${encodeURIComponent(photo.id)}/thumb?v=${version}`,
});
attempts += 1;
} catch (err) {
failures.push({
name: photo.name,
error: err instanceof Error ? err.message : 'could not be reprocessed',
});
}
setRawJob((prev) =>
prev
? { ...prev, done: index + 1, failures: failures.slice() }
: prev,
);
}
} finally {
rawBusyRef.current = false;
setRawJob((prev) =>
prev
? {
...prev,
running: false,
done: attempts,
failures: failures.slice(),
cancelled: rawCancelRef.current,
}
: prev,
);
}
const succeeded = attempts - failures.length;
const parts = [
`Reprocessed ${succeeded} of ${targets.length} RAW${targets.length === 1 ? '' : 's'}`,
];
if (failures.length) parts.push(`${failures.length} failed`);
if (rawCancelRef.current) parts.push('cancelled');
setToast(parts.join(' · '));
},
[updatePhoto],
);
/** Reprocess every RAW file in one event, with a confirmation that names it. */
const reprocessEventRaws = useCallback(
(id: string) => {
const event = eventsRef.current.find((item) => item.id === id);
if (!event) return;
const raws = photosRef.current.filter(
(photo) => photo.eventId === id && photo.raw && !photo.deletedAt,
);
if (!raws.length) {
setToast('This event has no RAW photos');
return;
}
if (!userRef.current) {
setToast('Sign in to the server to reprocess RAW files');
return;
}
if (rawBusyRef.current) {
setToast('A RAW reprocess is already running');
return;
}
const ok = window.confirm(
`Re-decode ${raws.length} RAW file${raws.length === 1 ? '' : 's'} in “${event.name}”? ` +
'Existing edits and crops are kept.',
);
if (!ok) return;
void reprocessRawPhotos(raws.map((photo) => photo.id), { eventName: event.name });
},
[reprocessRawPhotos],
);
/** Auto-sync in Develop: merge the same patch into every selected photo. */
const updatePhotoEdits = useCallback(
(ids: string[], patch: Partial<Edits>, historyLabel?: string) => {
for (const id of ids) {
updatePhoto(id, (p) => ({ edits: { ...p.edits, ...patch } }), historyLabel);
}
},
[updatePhoto],
);
const bulkUpdate = useCallback(
(ids: string[], patch: Partial<PhotoRecord>) => {
if (!ids.length) return;
setPhotos((prev) =>
prev.map((p) => {
if (!ids.includes(p.id)) return p;
const next = { ...p, ...patch };
queueSave(next);
return next;
}),
);
},
[queueSave],
);
const immichEventIds = useMemo(
() => new Set(events.filter((event) => event.immich).map((event) => event.id)),
[events],
);
const canSendToImmich = useCallback(
(photo: PhotoRecord) =>
Boolean(immichStatus?.enabled && (photo.immich || immichEventIds.has(photo.eventId))),
[immichStatus?.enabled, immichEventIds],
);
const livePhotos = useMemo(() => photos.filter((p) => !p.deletedAt), [photos]);
const trashCount = photos.length - livePhotos.length;
const proofCounts = useMemo(() => {
const map = new Map<string, number>();
for (const proof of proofs) map.set(proof.photoId, proof.count);
return map;
}, [proofs]);
const proofStatus = useMemo(() => {
const map = new Map<string, { approved: number; changes: number; comments: number }>();
for (const proof of proofs) {
map.set(proof.photoId, {
approved: proof.approved ?? 0,
changes: proof.changes ?? 0,
comments: proof.comments ?? 0,
});
}
return map;
}, [proofs]);
/** Current event/trash scope before the filter bar is applied. */
const scopePhotos = useMemo(
() =>
photos.filter((photo) => {
if (trashOpen ? !photo.deletedAt : !!photo.deletedAt) return false;
if (trashOpen) return true;
if (eventId === 'unsorted') return !photo.eventId;
if (eventId !== 'all') return photo.eventId === eventId;
return true;
}),
[eventId, photos, trashOpen],
);
const scopeReviewCounts = useMemo(() => {
let approved = 0;
let changes = 0;
for (const photo of scopePhotos) {
if (proofStatus.get(photo.id)?.approved) approved += 1;
if (proofStatus.get(photo.id)?.changes) changes += 1;
}
return { approved, changes };
}, [proofStatus, scopePhotos]);
const trashPhotos = useCallback(
(ids: string[]) => {
if (!ids.length) return;
const stamp = Date.now();
const affected = photosRef.current
.filter((photo) => ids.includes(photo.id) && !photo.deletedAt)
.map((photo) => photo.id);
if (!affected.length) return;
const previousActive = activeId;
const previousView = view;
setPhotos((prev) =>
prev.map((p) => {
if (!affected.includes(p.id)) return p;
const next = { ...p, deletedAt: stamp };
queueSave(next);
return next;
}),
);
setSelected([]);
if (activeId && affected.includes(activeId)) {
setActiveId(null);
setView('grid');
}
const message = `Moved ${affected.length === 1 ? '1 photo' : `${affected.length} photos`} to Trash`;
setToast(message);
setUndoAction({
message,
run: () => {
const restore = new Set(affected);
setPhotos((prev) =>
prev.map((photo) => {
if (!restore.has(photo.id) || !photo.deletedAt) return photo;
const next = { ...photo };
delete next.deletedAt;
queueSave(next);
return next;
}),
);
setSelected(affected);
setAnchorId(affected[0] ?? null);
if (previousActive && restore.has(previousActive)) {
setActiveId(previousActive);
setView(previousView);
}
setUndoAction(null);
setToast('Trash undone');
},
});
},
[activeId, queueSave, view],
);
const restorePhotos = useCallback(
(ids: string[]) => {
if (!ids.length) return;
setPhotos((prev) =>
prev.map((p) => {
if (!ids.includes(p.id) || !p.deletedAt) return p;
const next = { ...p };
delete next.deletedAt;
queueSave(next);
return next;
}),
);
setSelected([]);
setToast(`Restored ${ids.length === 1 ? '1 photo' : `${ids.length} photos`}`);
},
[queueSave],
);
const removePhotos = useCallback(
async (ids: string[]) => {
if (!ids.length) return;
const label = ids.length === 1 ? 'this photo' : `${ids.length} photos`;
if (!window.confirm(`Delete ${label} permanently? This cannot be undone.`)) return;
for (const id of ids) {
try {
await deletePhotoRecord(id);
evictBitmap(id);
if (userRef.current) await deletePhotoRemote(id).catch(() => undefined);
} catch (err) {
console.error('Delete failed', err);
}
}
setPhotos((prev) => prev.filter((p) => !ids.includes(p.id)));
setSelected((prev) => prev.filter((id) => !ids.includes(id)));
if (activeId && ids.includes(activeId)) {
setActiveId(null);
setView('grid');
}
setToast(`Deleted ${label}`);
},
[activeId],
);
const createEvent = useCallback(
async (name: string, options: { immichGallery?: boolean } = {}) => {
const event: EventRecord = {
id: uid(),
name: name.trim() || `Event ${new Date().toLocaleDateString()}`,
createdAt: Date.now(),
date: Date.now(),
order: eventsRef.current.length,
workspace: userRef.current?.id,
};
await putEvent(event);
// The gallery endpoint looks the event up server-side, so let this land first.
if (userRef.current) await pushEvent(event).catch(() => undefined);
let created = event;
if (options.immichGallery && userRef.current && immichStatusRef.current?.enabled) {
try {
const result = await createImmichEventAlbum(event.id, event.name);
created = result.event;
await putEvent(created);
setToast(`Immich gallery created for ${created.name}`);
} catch (err) {
setToast(
`Event created, but the Immich gallery failed: ${
err instanceof Error ? err.message : 'unknown error'
}`,
);
}
}
const nextEvents = [...eventsRef.current.filter((e) => e.id !== created.id), created].sort(byOrder);
// ImportModal creates an event and immediately asks for its Immich gallery.
// Update the ref now so that follow-up call can find the new event.
eventsRef.current = nextEvents;
setEvents(nextEvents);
return created;
},
[],
);
const createImmichGalleryForEvent = useCallback(async (id: string) => {
const event = eventsRef.current.find((item) => item.id === id);
if (!event) throw new Error('No such event');
const result = await createImmichEventAlbum(id, event.name);
await putEvent(result.event);
const nextEvents = eventsRef.current
.map((item) => (item.id === id ? result.event : item))
.sort(byOrder);
eventsRef.current = nextEvents;
setEvents(nextEvents);
setToast(`Immich gallery created for ${event.name}`);
return result.event;
}, []);
const renameEvent = useCallback(async (id: string, name: string) => {
const trimmed = name.trim();
if (!trimmed) return;
setEvents((prev) => {
const next = prev.map((e) => (e.id === id ? { ...e, name: trimmed } : e));
const target = next.find((e) => e.id === id);
if (target) {
putEvent(target).catch((err) => console.error(err));
if (userRef.current) pushEvent(target).catch(() => undefined);
}
return next;
});
}, []);
const removeEvent = useCallback(
async (id: string) => {
const event = events.find((e) => e.id === id);
if (!event) return;
if (!window.confirm(`Remove the event "${event.name}"? Its photos stay in All Photos.`)) return;
await deleteEventRecord(id);
if (userRef.current) await deleteEventRemote(id).catch(() => undefined);
setEvents((prev) => prev.filter((e) => e.id !== id));
setPhotos((prev) => {
const next = prev.map((p) => (p.eventId === id ? { ...p, eventId: '' } : p));
for (const p of next) if (p.eventId === '') queueSave(p);
return next;
});
if (eventId === id) setEventId('all');
},
[events, eventId, queueSave],
);
const baseSorted = useMemo(() => {
const text = filters.text.trim().toLowerCase();
const eventNames = new Map(events.map((e) => [e.id, e.name.toLowerCase()]));
const list = photos.filter((p) => {
// Trash is a separate bucket: deleted photos never mix with the library,
// and the trash view shows nothing else.
if (trashOpen ? !p.deletedAt : !!p.deletedAt) return false;
if (trashOpen) return true;
if (eventId === 'unsorted' && p.eventId) return false;
if (eventId !== 'all' && eventId !== 'unsorted' && p.eventId !== eventId) return false;
if (filters.minRating > 0 && p.rating < filters.minRating) return false;
if (filters.unrated && p.rating !== 0) return false;
if (filters.flag !== 'any' && p.flag !== filters.flag) return false;
if (filters.colors.length && !filters.colors.includes(p.color)) return false;
if (filters.editedOnly && !isEdited(p.edits)) return false;
if (filters.proofed && !proofCounts.has(p.id)) return false;
if (filters.clientStatus === 'approved' && !(proofStatus.get(p.id)?.approved ?? 0)) return false;
if (filters.clientStatus === 'changes' && !(proofStatus.get(p.id)?.changes ?? 0)) return false;
if (text) {
const hay = [
p.name,
p.title ?? '',
p.caption ?? '',
p.creator ?? '',
p.copyright ?? '',
p.meta.camera ?? '',
p.meta.lens ?? '',
p.eventId ? eventNames.get(p.eventId) ?? '' : '',
...p.keywords,
]
.join(' ')
.toLowerCase();
if (!hay.includes(text)) return false;
}
return true;
});
if (sort === 'custom') {
return [...list].sort(
(a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.addedAt - b.addedAt,
);
}
const dir = asc ? 1 : -1;
const keyOf = (p: PhotoRecord): number | string => {
if (sort === 'taken') return p.takenAt ?? p.addedAt;
if (sort === 'added') return p.addedAt;
if (sort === 'rating') return p.rating;
return p.name.toLowerCase();
};
return [...list].sort((a, b) => {
const ka = keyOf(a);
const kb = keyOf(b);
if (typeof ka === 'string' && typeof kb === 'string') return ka.localeCompare(kb) * dir;
return ((ka as number) - (kb as number)) * dir;
});
}, [photos, events, eventId, filters, sort, asc, trashOpen, proofCounts, proofStatus]);
// Stacks collapse to their lowest-index member until expanded. Grouping after
// filtering means a hidden stack never masks a visible sibling.
const sorted = useMemo(() => {
if (trashOpen) return baseSorted;
const groups = new Map<string, PhotoRecord[]>();
for (const photo of baseSorted) {
if (!photo.stackId) continue;
const list = groups.get(photo.stackId) ?? [];
list.push(photo);
groups.set(photo.stackId, list);
}
const seen = new Set<string>();
const out: PhotoRecord[] = [];
for (const photo of baseSorted) {
if (!photo.stackId) {
out.push(photo);
continue;
}
if (seen.has(photo.stackId)) continue;
seen.add(photo.stackId);
const members = [...(groups.get(photo.stackId) ?? [])].sort(
(a, b) => (a.stackIndex ?? 0) - (b.stackIndex ?? 0),
);
if (expandedStacks.has(photo.stackId)) out.push(...members);
else if (members[0]) out.push(members[0]);
}
return out;
}, [baseSorted, expandedStacks, trashOpen]);
const stackMeta = useMemo(() => {
const groups = new Map<string, PhotoRecord[]>();
for (const photo of baseSorted) {
if (!photo.stackId) continue;
const list = groups.get(photo.stackId) ?? [];
list.push(photo);
groups.set(photo.stackId, list);
}
const meta = new Map<string, { count: number; expanded: boolean }>();
for (const [id, members] of groups) {
if (members.length < 2) continue;
const expanded = expandedStacks.has(id);
const rep = members.reduce((a, b) => ((b.stackIndex ?? 0) < (a.stackIndex ?? 0) ? b : a));
if (expanded) {
for (const member of members) meta.set(member.id, { count: members.length, expanded: true });
} else {
meta.set(rep.id, { count: members.length, expanded: false });
}
}
return meta;
}, [baseSorted, expandedStacks]);
const activePhoto = useMemo(() => photos.find((p) => p.id === activeId) ?? null, [photos, activeId]);
const scopedProofCount = useMemo(() => {
if (trashOpen) return 0;
return livePhotos.filter((p) =>
proofCounts.has(p.id) &&
(eventId === 'all' || (eventId === 'unsorted' ? !p.eventId : p.eventId === eventId)),
).length;
}, [eventId, livePhotos, proofCounts, trashOpen]);
/** The dashboard event id this tab was opened for, when bridged. */
const bridgeParam = useMemo(
() => new URLSearchParams(window.location.search).get('bridge'),
[],
);
const bridgeEvent = useMemo(
() =>
events.find((event) => event.bridge && (event.id === bridgeParam || event.id === eventId)) ??
null,
[events, bridgeParam, eventId],
);
const bridgeSynced = useRef(false);
const selectPhoto = useCallback(
(id: string, e: React.MouseEvent) => {
if (e.shiftKey && anchorId) {
const a = sorted.findIndex((p) => p.id === anchorId);
const b = sorted.findIndex((p) => p.id === id);
if (a >= 0 && b >= 0) {
const [lo, hi] = a < b ? [a, b] : [b, a];
setSelected(sorted.slice(lo, hi + 1).map((p) => p.id));
return;
}
}
if (e.metaKey || e.ctrlKey) {
setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
setAnchorId(id);
return;
}
setSelected([id]);
setAnchorId(id);
},
[anchorId, sorted],
);
const openPhoto = useCallback((id: string) => {
setCatalogOpen(false);
setActiveId(id);
setSelected([id]);
setView('develop');
}, []);
const copySettings = useCallback(() => {
if (!activePhoto) return;
setClipboard(activePhoto.edits);
setClipboardSource({ id: activePhoto.id, name: activePhoto.name });
setToast('Develop settings copied');
}, [activePhoto]);
const openPaste = useCallback(
(ids: string[], mode: 'paste' | 'sync' = 'paste', sourcePhoto?: PhotoRecord) => {
if (!ids.length) return;
const source = sourcePhoto?.edits ?? clipboard;
if (!source) return;
setPasteRequest({
targets: ids,
source,
sourceName: sourcePhoto?.name ?? clipboardSource?.name ?? 'copied settings',
mode,
});
},
[clipboard, clipboardSource],
);
const applyPaste = useCallback(
(sections: EditSectionId[]) => {
if (!pasteRequest || !sections.length) return;
const targets = new Set(pasteRequest.targets);
setPhotos((prev) =>
prev.map((p) => {
if (!targets.has(p.id)) return p;
const edits = applyEditSections(pasteRequest.source, p.edits, sections);
const next: PhotoRecord = {
...p,
edits,
history: [
...p.history,
{ label: pasteRequest.mode === 'sync' ? 'Sync settings' : 'Paste settings', ts: Date.now(), edits },
].slice(-90),
};
queueSave(next);
return next;
}),
);
setToast(
`${pasteRequest.mode === 'sync' ? 'Synced' : 'Pasted'} ${sections.length} section${sections.length === 1 ? '' : 's'} to ${pasteRequest.targets.length} photo${pasteRequest.targets.length === 1 ? '' : 's'}`,
);
setPasteRequest(null);
},
[pasteRequest, queueSave],
);
/* ------------------------------------------------------- context actions */
const openPhotoMenu = useCallback(
(e: React.MouseEvent, id: string) => {
e.preventDefault();
e.stopPropagation();
const ids = selected.includes(id) ? selected : [id];
if (!selected.includes(id)) {
setSelected([id]);
setAnchorId(id);
}
setMenu({ x: e.clientX, y: e.clientY, ids });
},
[selected],
);
const copySettingsOf = useCallback((id: string) => {
const source = photosRef.current.find((p) => p.id === id);
if (!source) return;
setClipboard(source.edits);
setClipboardSource({ id: source.id, name: source.name });
setToast(`Develop settings copied from ${source.name}`);
}, []);
const resetEdits = useCallback(
(ids: string[]) => {
if (!ids.length) return;
setPhotos((prev) =>
prev.map((p) => {
if (!ids.includes(p.id)) return p;
const edits: Edits = { ...defaultEdits(), crop: p.edits.crop };
const next: PhotoRecord = {
...p,
edits,
history: [...p.history, { label: 'Reset', ts: Date.now(), edits }].slice(-90),
};
queueSave(next);
return next;
}),
);
setToast(`Reset adjustments on ${ids.length} photo${ids.length === 1 ? '' : 's'}`);
},
[queueSave],
);
const savePreset = useCallback(
(name: string, edits: Edits) => {
// Crop and the camera profile are properties of this photo, not a look:
// copying either onto another body would be wrong.
const { crop: _crop, cameraProfile: _cameraProfile, ...withoutCrop } = edits;
const preset: Preset = {
id: uid(),
name,
group: 'User presets',
custom: true,
edits: withoutCrop,
};
const next = [...customPresets, preset];
setCustomPresets(next);
setKV('customPresets', next).catch((err) => console.error(err));
if (userRef.current) {
import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined));
}
setToast(`Preset "${name}" saved`);
},
[customPresets],
);
const deletePreset = useCallback(
(id: string) => {
const next = customPresets.filter((preset) => preset.id !== id);
setCustomPresets(next);
setKV('customPresets', next).catch((err) => console.error(err));
if (userRef.current) {
import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined));
}
setToast('Preset deleted');
},
[customPresets],
);
/* ------------------------------------------------------------- reordering */
const reorderPhotos = useCallback(
(ids: string[], targetId: string | null) => {
if (!ids.length) return;
const visible = sorted.map((p) => p.id);
const moving = ids.filter((id) => visible.includes(id));
if (!moving.length) return;
const rest = visible.filter((id) => !ids.includes(id));
const at = targetId ? Math.max(0, rest.indexOf(targetId)) : rest.length;
rest.splice(at < 0 ? rest.length : at, 0, ...moving);
const positions = new Map(rest.map((id, i) => [id, i]));
setPhotos((prev) =>
prev.map((p) => {
const order = positions.get(p.id);
if (order === undefined || p.order === order) return p;
const next = { ...p, order };
queueSave(next);
return next;
}),
);
setSort('custom');
setToast(`Moved ${moving.length} photo${moving.length === 1 ? '' : 's'}`);
},
[sorted, queueSave],
);
const stackSelection = useCallback(
(ids: string[]) => {
const members = sorted.filter((photo) => ids.includes(photo.id));
if (members.length < 2) {
setToast('Select at least two photos to stack');
return;
}
const stackId = uid();
setPhotos((prev) =>
prev.map((photo) => {
const index = members.findIndex((member) => member.id === photo.id);
if (index < 0) return photo;
const next: PhotoRecord = { ...photo, stackId, stackIndex: index };
queueSave(next);
return next;
}),
);
setExpandedStacks((prev) => new Set(prev).add(stackId));
setToast(`Stacked ${members.length} photos`);
},
[sorted, queueSave],
);
const unstackSelection = useCallback(
(ids: string[]) => {
if (!ids.length) return;
// Unstacking one member releases the whole stack, otherwise a collapsed
// stack would leave its hidden siblings attached to a one-photo group.
const stackIds = new Set(
photos.filter((photo) => ids.includes(photo.id) && photo.stackId).map((photo) => photo.stackId!),
);
const targets = photos.filter(
(photo) => ids.includes(photo.id) || (photo.stackId && stackIds.has(photo.stackId)),
);
if (!targets.length) return;
const targetIds = new Set(targets.map((photo) => photo.id));
setPhotos((prev) =>
prev.map((photo) => {
if (!targetIds.has(photo.id) || !photo.stackId) return photo;
const next: PhotoRecord = { ...photo };
delete next.stackId;
delete next.stackIndex;
queueSave(next);
return next;
}),
);
setToast(`Unstacked ${targets.length === 1 ? '1 photo' : `${targets.length} photos`}`);
},
[photos, queueSave],
);
const createVirtualCopy = useCallback(
async (id: string, open = false) => {
const source = photosRef.current.find((p) => p.id === id);
if (!source) return;
const copyId = uid();
const master = source.copyOf ?? source.id;
const copyNumber = photosRef.current.filter((photo) => photo.copyOf === master).length + 1;
const base = source.name.replace(/ (copy \d+|virtual copy.*)$/i, '').replace(/\.[^.]+$/, '');
const copy = normalizePhoto({
...source,
id: copyId,
name: `${base} copy ${copyNumber}`,
addedAt: Date.now(),
copyOf: master,
copyName: `Virtual copy ${copyNumber}`,
snapshots: [],
stackId: undefined,
stackIndex: undefined,
});
const blob = await getAsset(source.id).catch(() => undefined);
if (blob) await putAsset(copyId, blob).catch(() => undefined);
await putPhoto(copy);
setPhotos((prev) => [copy, ...prev]);
setSelected([copyId]);
setAnchorId(copyId);
if (open) {
setActiveId(copyId);
setView('develop');
}
setToast(`Created ${copy.copyName}`);
if (userRef.current) {
if (blob) await uploadOriginal(copyId, blob, copy.name).catch(() => undefined);
pushPhoto(copy).catch(() => undefined);
}
},
[],
);
const saveSnapshot = useCallback(
(id: string, name: string) => {
const label = name.trim() || `Snapshot ${new Date().toLocaleTimeString()}`;
updatePhoto(id, (photo) => ({
snapshots: [
...(photo.snapshots ?? []),
{ id: uid(), name: label.slice(0, 40), ts: Date.now(), edits: photo.edits },
].slice(-30),
}));
setToast(`Snapshot “${label}” saved`);
},
[updatePhoto],
);
const restoreSnapshot = useCallback(
(id: string, snapshot: Snapshot) => {
updatePhoto(id, { edits: snapshot.edits }, `Snapshot: ${snapshot.name}`);
setToast(`Restored “${snapshot.name}”`);
},
[updatePhoto],
);
const deleteSnapshot = useCallback(
(id: string, snapshotId: string) => {
updatePhoto(id, (photo) => ({
snapshots: (photo.snapshots ?? []).filter((snapshot) => snapshot.id !== snapshotId),
}));
},
[updatePhoto],
);
const saveMetadataPreset = useCallback((preset: Omit<MetadataPreset, 'id'>) => {
const next = [...metadataPresets, { ...preset, id: uid() }];
setMetadataPresets(next);
setKV('metadataPresets', next).catch((err) => console.error(err));
}, [metadataPresets]);
const deleteMetadataPreset = useCallback((id: string) => {
const next = metadataPresets.filter((preset) => preset.id !== id);
setMetadataPresets(next);
setKV('metadataPresets', next).catch((err) => console.error(err));
}, [metadataPresets]);
const saveSmartCollection = useCallback(
(name: string) => {
const clean = name.trim();
if (!clean) return;
const next = [
...smartCollections,
{
id: uid(),
name: clean,
filters: { ...filters },
eventId: eventId === 'all' || eventId === 'unsorted' ? undefined : eventId,
sort,
asc,
},
];
setSmartCollections(next);
setKV('smartCollections', next).catch((err) => console.error(err));
setToast(`Saved collection “${clean}”`);
},
[smartCollections, filters, eventId, sort, asc],
);
const applySmartCollection = useCallback(
(id: string) => {
const collection = smartCollections.find((item) => item.id === id);
if (!collection) return;
setFilters({ ...EMPTY_FILTERS, ...collection.filters });
setSort(collection.sort);
setAsc(collection.asc);
setTrashOpen(false);
if (collection.eventId) setEventId(collection.eventId);
setActiveCollection(id);
},
[smartCollections],
);
const deleteSmartCollection = useCallback((id: string) => {
const next = smartCollections.filter((collection) => collection.id !== id);
setSmartCollections(next);
setKV('smartCollections', next).catch((err) => console.error(err));
setActiveCollection((current) => (current === id ? null : current));
}, [smartCollections]);
const toggleStack = useCallback((photoId: string) => {
const photo = photosRef.current.find((item) => item.id === photoId);
if (!photo?.stackId) return;
setExpandedStacks((prev) => {
const next = new Set(prev);
if (next.has(photo.stackId!)) next.delete(photo.stackId!);
else next.add(photo.stackId!);
return next;
});
}, []);
const movePhotosToEvent = useCallback(
(ids: string[], targetEventId: string) => {
if (!ids.length) return;
const inTarget = photos.filter((p) => p.eventId === targetEventId).length;
const previous = photosRef.current
.filter((photo) => ids.includes(photo.id))
.map((photo) => ({ id: photo.id, eventId: photo.eventId, order: photo.order }));
if (!previous.length) return;
setPhotos((prev) =>
prev.map((p, i) => {
if (!ids.includes(p.id)) return p;
const next = { ...p, eventId: targetEventId, order: inTarget + i };
queueSave(next);
return next;
}),
);
const name = targetEventId ? events.find((e) => e.id === targetEventId)?.name ?? 'event' : 'Unsorted';
const message = `Moved ${ids.length} photo${ids.length === 1 ? '' : 's'} to ${name}`;
setToast(message);
setUndoAction({
message,
run: () => {
const before = new Map(previous.map((photo) => [photo.id, photo]));
setPhotos((prev) =>
prev.map((photo) => {
const old = before.get(photo.id);
if (!old) return photo;
const next: PhotoRecord = { ...photo, eventId: old.eventId };
if (old.order === undefined) delete next.order;
else next.order = old.order;
queueSave(next);
return next;
}),
);
setUndoAction(null);
setToast('Move undone');
},
});
},
[events, photos, queueSave],
);
const reorderEvents = useCallback((dragId: string, targetId: string) => {
setEvents((prev) => {
const list = [...prev];
const from = list.findIndex((e) => e.id === dragId);
const to = list.findIndex((e) => e.id === targetId);
if (from < 0 || to < 0 || from === to) return prev;
const [moved] = list.splice(from, 1);
list.splice(to, 0, moved);
const next = list.map((e, i) => (e.order === i ? e : { ...e, order: i }));
for (const e of next) {
putEvent(e).catch(() => undefined);
if (userRef.current) pushEvent(e).catch(() => undefined);
}
return next;
});
}, []);
/* ------------------------------------------------------------------ cloud */
const applyRemote = useCallback(
(
remote: {
user: SessionUser;
events: EventRecord[];
photos: PhotoRecord[];
presets: Preset[];
proofs?: ProofSummary[];
},
local: PhotoRecord[],
) => {
const owner = remote.user?.id ?? '';
const localById = new Map(local.map((p) => [p.id, p]));
const merged = remote.photos.map((r) => {
const l = localById.get(r.id);
return normalizePhoto({ ...r, workspace: owner, thumb: l?.thumb || r.thumb || '' });
});
const seen = new Set(merged.map((p) => p.id));
// Cached photos from another account stay on the device but out of this workspace.
for (const l of local) {
if (seen.has(l.id)) continue;
if (!owner || l.workspace !== owner) continue;
merged.push(l);
}
setPhotos(merged);
for (const p of merged) putPhoto(p).catch(() => undefined);
setEvents([...remote.events].map((e) => ({ ...e, workspace: owner })).sort(byOrder));
if (remote.presets.length) setCustomPresets(remote.presets);
setProofs(remote.proofs ?? []);
},
[],
);
const syncLibrary = useCallback(async () => {
const user = userRef.current ?? (await currentUser());
if (!user) throw new Error('Sign in to the team server first');
const owner = user.id;
// Pull first. A brand-new workspace may adopt the library built on this
// device while signed out; an existing workspace never absorbs another
// account's cached records.
const before = await pullAll();
const emptyWorkspace = before.photos.length === 0 && before.events.length === 0;
const claimable = (record: { workspace?: string }) =>
record.workspace === owner || (emptyWorkspace && !record.workspace);
const localPhotos = photosRef.current.filter(claimable);
const localEvents = eventsRef.current.filter(claimable);
// Only records the server accepted become this account's cache. A rejected
// record (for example a stale copy owned by someone else) stays out of view.
const claimedEvents = new Set<string>();
const claimedPhotos = new Set<string>();
for (const event of localEvents) {
try {
await pushEvent({ ...event, workspace: owner });
claimedEvents.add(event.id);
} catch (err) {
console.warn('Could not sync event', event.name, err);
}
}
for (const photo of localPhotos) {
try {
if (!photo.raw && !photo.thumbUrl) {
const blob = await getAsset(photo.id);
if (blob) await uploadOriginal(photo.id, blob, photo.name).catch(() => undefined);
}
const payload: PhotoRecord = {
...photo,
workspace: owner,
...(photo.thumbUrl ? { thumb: '' } : {}),
};
const saved = await pushPhoto(payload);
claimedPhotos.add(photo.id);
if (saved.thumbUrl || saved.previewUrl) {
setPhotos((prev) =>
prev.map((p) =>
p.id === saved.id ? { ...p, thumbUrl: saved.thumbUrl ?? p.thumbUrl, previewUrl: saved.previewUrl ?? p.previewUrl } : p,
),
);
}
} catch (err) {
console.warn('Could not sync photo', photo.name, err);
}
}
const claimed = new Set<string>([...claimedEvents, ...claimedPhotos]);
const localSnapshot = photosRef.current.map((p) =>
claimed.has(p.id) || p.workspace === owner ? { ...p, workspace: owner } : p,
);
// Remember which account claimed the cache so switching accounts can't
// re-upload these records into someone else's workspace.
for (const p of localPhotos) {
if (claimedPhotos.has(p.id)) putPhoto({ ...p, workspace: owner }).catch(() => undefined);
}
for (const e of localEvents) {
if (claimedEvents.has(e.id)) putEvent({ ...e, workspace: owner }).catch(() => undefined);
}
setPhotos((prev) =>
prev.map((p) => (claimed.has(p.id) ? { ...p, workspace: owner } : p)),
);
setEvents((prev) =>
prev.map((e) => (claimed.has(e.id) ? { ...e, workspace: owner } : e)),
);
const remote = await pullAll();
applyRemote(remote, localSnapshot);
return remote.photos.length;
}, [applyRemote]);
// Arriving from the dashboard: the bridge login already created a session and
// imported the event, so pull it once and open that event.
useEffect(() => {
if (!loaded || !bridgeParam || !cloudUser || bridgeSynced.current) return;
bridgeSynced.current = true;
syncLibrary()
.then(() => {
setEventId(bridgeParam);
setView('grid');
})
.catch((err) =>
setLoadError(
err instanceof Error ? err.message : 'Could not load the advanced edit',
),
);
}, [loaded, bridgeParam, cloudUser, syncLibrary]);
/** Render the open photo at full size and store it on the event. */
const saveActiveToEvent = useCallback(async () => {
if (!activePhoto || !bridgeEvent) return;
setBridgeBusy(true);
try {
const blob = await renderPhotoBlob(activePhoto, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'none',
});
const res = await fetch('/api/bridge/export', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
photoId: activePhoto.id,
jpeg: await blobToBase64(blob),
edits: activePhoto.edits,
width: activePhoto.width,
height: activePhoto.height,
}),
});
const data = (await res.json().catch(() => ({}))) as { error?: string };
if (!res.ok) throw new Error(data.error || 'The photo could not be saved');
setToast(`Saved ${activePhoto.name} to the event`);
} catch (err) {
setToast(err instanceof Error ? err.message : 'The photo could not be saved');
} finally {
setBridgeBusy(false);
}
}, [activePhoto, bridgeEvent]);
/**
* Renders each edit and uploads the queue one at a time. Checksums make a
* repeat send of an unchanged edit a no-op on the server.
*/
const pushImmichQueue = useCallback(async (targets: PhotoRecord[]) => {
if (immichBusyRef.current) return;
const queue = targets.filter(
(photo) => photo.immich || immichEventIds.has(photo.eventId),
);
const localCount = targets.length - queue.length;
if (!queue.length) {
setToast('None of the selected photos can go to Immich yet');
return;
}
immichBusyRef.current = true;
let sent = 0;
let skipped = 0;
let failed = 0;
let trashed = 0;
let warning = '';
setImmichProgress({ done: 0, total: queue.length, current: queue[0].name });
try {
for (let i = 0; i < queue.length; i += 1) {
const photo = queue[i];
setImmichProgress({ done: i, total: queue.length, current: photo.name });
try {
const blob = await renderPhotoBlob(photo, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'none',
});
const result = await pushImmichPhoto(photo.id, await blobToBase64(blob));
if (result.alreadyPushed) skipped += 1;
else sent += 1;
if (result.trashed) trashed += 1;
if (result.warning && !warning) warning = result.warning;
} catch (err) {
failed += 1;
if (!warning) warning = err instanceof Error ? err.message : 'A photo could not be sent';
}
setImmichProgress({ done: i + 1, total: queue.length, current: photo.name });
// Let the progress paint before the next full-resolution render.
await new Promise((resolve) => setTimeout(resolve, 0));
}
} finally {
immichBusyRef.current = false;
setImmichProgress(null);
}
const parts = [];
if (sent) parts.push(`Sent ${sent} edit${sent === 1 ? '' : 's'}`);
if (skipped) parts.push(`${skipped} already in Immich`);
if (localCount) parts.push(`${localCount} not from Immich`);
if (trashed) parts.push(`${trashed} original${trashed === 1 ? '' : 's'} in trash`);
if (failed) parts.push(`${failed} failed`);
let message = parts.length ? parts.join(' · ') : 'Nothing to send';
if (warning) message += ` · ${warning}`;
setToast(message);
}, [immichEventIds]);
/**
* Manual push for one event. Photos Immich has never seen upload their
* original from the server; photos edited since the last push are rendered
* here so the gallery receives the current look. Nothing runs on its own -
* this only happens when the button is pressed, and each finished upload is
* recorded so a repeat press skips everything that is already up to date.
*/
const syncEventGallery = useCallback(async (targetEventId: string) => {
if (immichBusyRef.current) {
setToast('An Immich upload is already running');
return;
}
if (!immichStatusRef.current?.enabled) {
setToast('Turn on Immich in the Immich sync panel first');
return;
}
let plan: { photoId: string; mode: 'original' | 'edit' }[];
try {
plan = (await immichEventQueue(targetEventId)).queue;
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not read the Immich queue');
return;
}
const byId = new Map(
photosRef.current.filter((photo) => !photo.deletedAt).map((photo) => [photo.id, photo]),
);
const queue: { entry: { photoId: string; mode: 'original' | 'edit' }; photo: PhotoRecord }[] = [];
for (const entry of plan) {
const photo = byId.get(entry.photoId);
if (!photo) continue;
// A photo Immich already has only needs a new upload once it is edited.
if (entry.mode === 'edit' && !isEdited(photo.edits)) continue;
queue.push({ entry, photo });
}
if (!queue.length) {
setToast('Everything in this event is already in Immich');
return;
}
immichBusyRef.current = true;
let sent = 0;
let skipped = 0;
let failed = 0;
let warning = '';
setImmichProgress({ done: 0, total: queue.length, current: queue[0].photo.name });
try {
for (let i = 0; i < queue.length; i += 1) {
const { entry, photo } = queue[i];
setImmichProgress({ done: i, total: queue.length, current: photo.name });
try {
const result = entry.mode === 'edit'
? await pushImmichPhoto(
photo.id,
await blobToBase64(
await renderPhotoBlob(photo, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'none',
}),
),
)
: await publishImmichOriginal(photo.id);
if (result.alreadyPushed || result.skipped) skipped += 1;
else sent += 1;
if (result.warning && !warning) warning = result.warning;
} catch (err) {
failed += 1;
if (!warning) {
warning = `${photo.name}: ${
err instanceof Error ? err.message : 'could not be sent'
}`;
}
}
setImmichProgress({ done: i + 1, total: queue.length, current: photo.name });
// Let the progress paint before the next render or upload.
await new Promise((resolve) => setTimeout(resolve, 0));
}
} finally {
immichBusyRef.current = false;
setImmichProgress(null);
}
const parts = [];
if (sent) parts.push(`Sent ${sent} photo${sent === 1 ? '' : 's'}`);
if (skipped) parts.push(`${skipped} already in Immich`);
if (failed) parts.push(`${failed} failed`);
let message = parts.length ? parts.join(' · ') : 'Nothing to send';
if (warning) message += ` · ${warning}`;
setToast(message);
}, []);
/**
* Manual publish for an event that has no Immich gallery yet: create the
* album, link it to the event, then push originals and current edits.
*/
const publishEventToImmich = useCallback(
async (targetEventId: string) => {
const event = eventsRef.current.find((item) => item.id === targetEventId);
if (!event) return;
if (!immichStatusRef.current?.enabled) {
setToast('Turn on Immich in the Immich sync panel first');
return;
}
if (event.immich) {
await syncEventGallery(targetEventId);
return;
}
try {
await createImmichGalleryForEvent(targetEventId);
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not create the Immich gallery');
return;
}
const count = photosRef.current.filter(
(photo) => photo.eventId === targetEventId && !photo.deletedAt,
).length;
if (!count) {
setToast(`Immich gallery created for ${event.name} — import photos to fill it`);
return;
}
await syncEventGallery(targetEventId);
},
[createImmichGalleryForEvent, syncEventGallery],
);
const openImmichAsset = useCallback((photo: PhotoRecord) => {
const status = immichStatusRef.current;
if (!status?.url || !photo.immich) return;
window.open(
`${status.url.replace(/\/+$/, '')}/photos/${encodeURIComponent(photo.immich.assetId)}`,
'_blank',
'noopener,noreferrer',
);
}, []);
const handleCloudLogin = useCallback(
async (email: string, password: string) => {
setCloudBusy(true);
setCloudError(null);
try {
const user = await apiLogin(email, password);
userRef.current = user;
setCloudUser(user);
const count = await syncLibrary();
await refreshQuota();
setCloudHealth(await getHealth());
setCloudNote(`Signed in · ${count} photo${count === 1 ? '' : 's'} on the server`);
setToast('Connected to the team server');
} catch (err) {
setCloudError(err instanceof Error ? err.message : 'Could not sign in');
} finally {
setCloudBusy(false);
}
},
[syncLibrary, refreshQuota],
);
const handleCloudRegister = useCallback(
async (input: { email: string; password: string; name: string; invite: string }) => {
setCloudBusy(true);
setCloudError(null);
try {
const user = await apiRegister(input);
userRef.current = user;
setCloudUser(user);
const count = await syncLibrary();
await refreshQuota();
setCloudHealth(await getHealth());
setCloudNote(`Account created · ${count} photo${count === 1 ? '' : 's'} on the server`);
setToast('Team account created');
} catch (err) {
setCloudError(err instanceof Error ? err.message : 'Could not create the account');
} finally {
setCloudBusy(false);
}
},
[syncLibrary, refreshQuota],
);
const handleCloudLogout = useCallback(async () => {
setCloudBusy(true);
try {
await apiLogout();
} catch {
/* signing out locally is enough */
}
setCloudUser(null);
setCloudNote(null);
setCloudError(null);
setCloudBusy(false);
setPhotos((prev) => prev.filter((p) => !p.workspace));
setEvents((prev) => prev.filter((e) => !e.workspace));
setToast('Signed out — your workspace stays on the server');
}, []);
const refreshCatalogFromServer = useCallback(async () => {
try {
const remote = await pullAll();
applyRemote(remote, photosRef.current);
setProofs(remote.proofs ?? []);
setCloudHealth(await getHealth());
setToast('Catalog restored from the server');
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not reload the restored catalog');
}
}, [applyRemote]);
const handleSync = useCallback(async () => {
setCloudBusy(true);
setCloudError(null);
try {
const count = await syncLibrary();
await refreshQuota();
setProofs(await pullProofs().catch(() => []));
setCloudHealth(await getHealth());
setCloudNote(`Synced · ${count} photo${count === 1 ? '' : 's'} on the server`);
setToast('Library synced');
} catch (err) {
setCloudError(err instanceof Error ? err.message : 'Sync failed');
} finally {
setCloudBusy(false);
}
}, [syncLibrary, refreshQuota]);
/* ----------------------------------------------------------------- export */
const exportTargets = useMemo(() => {
if (view === 'develop' && activePhoto) return [activePhoto];
return photos.filter((p) => selected.includes(p.id));
}, [view, activePhoto, photos, selected]);
const openExport = useCallback(() => {
if (!exportTargets.length) {
setToast('Select photos to export');
return;
}
setExportOpen(true);
}, [exportTargets]);
const closeExport = useCallback((message: string) => {
setToast(message);
}, []);
const addMergedPhoto = useCallback(
async (result: MergeResult) => {
const first = photosRef.current.find((photo) => result.sourceIds.includes(photo.id));
if (!first) return;
const id = uid();
const label = result.kind === 'hdr' ? 'HDR' : result.kind === 'panorama' ? 'Panorama' : 'Focus stack';
const name = `${label} ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
const record = normalizePhoto({
...first,
id,
name,
width: result.width,
height: result.height,
size: result.blob.size,
mime: 'image/jpeg',
thumb: result.thumb,
thumbUrl: undefined,
previewUrl: undefined,
raw: false,
decode: undefined,
addedAt: Date.now(),
copyOf: undefined,
copyName: undefined,
snapshots: [],
merge: { kind: result.kind, sourceIds: result.sourceIds },
edits: defaultEdits(),
history: [],
stackId: undefined,
stackIndex: undefined,
keywords: [...new Set(result.sourceIds.flatMap((sourceId) => photosRef.current.find((photo) => photo.id === sourceId)?.keywords ?? []))],
});
await putAsset(id, result.blob);
await putPhoto(record);
setPhotos((prev) => [record, ...prev]);
setSelected([id]);
setAnchorId(id);
setMergeOpen(false);
setToast(`${label} created`);
if (userRef.current) {
await uploadOriginal(id, result.blob, name).catch(() => undefined);
pushPhoto(record)
.then((saved) =>
setPhotos((prev) => prev.map((photo) => (photo.id === id ? { ...photo, ...saved } : photo))),
)
.catch(() => undefined);
}
},
[],
);
// Keyboard selection walks the grid the way it is laid out: the column count
// comes from the rendered rows, so up/down move by whole rows at any width.
const moveSelection = useCallback(
(dx: number, dy: number, extend: boolean) => {
if (!sorted.length) return;
const currentId = selected[0] ?? anchorId;
const index = Math.max(0, sorted.findIndex((p) => p.id === currentId));
let columns = 1;
const grid = document.querySelector<HTMLElement>('.grid');
if (grid) {
const card = grid.querySelector<HTMLElement>('.card');
if (card) {
const firstTop = Math.round(card.getBoundingClientRect().top);
const perRow = new Map<number, number>();
for (const el of grid.querySelectorAll<HTMLElement>('.card')) {
const top = Math.round(el.getBoundingClientRect().top);
perRow.set(top, (perRow.get(top) ?? 0) + 1);
}
columns = perRow.get(firstTop) ?? 1;
}
}
const nextIndex = Math.min(sorted.length - 1, Math.max(0, index + dy * columns + dx));
const target = sorted[nextIndex];
if (!target) return;
if (extend && anchorId) {
const a = sorted.findIndex((p) => p.id === anchorId);
const [lo, hi] = a < nextIndex ? [a, nextIndex] : [nextIndex, a];
setSelected(sorted.slice(lo, hi + 1).map((p) => p.id));
} else {
setSelected([target.id]);
setAnchorId(target.id);
}
},
[anchorId, selected, sorted],
);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey;
const k = e.key.toLowerCase();
// Search is deliberately available even when a filter field has focus.
if (
mod &&
k === 'k' &&
!helpOpen &&
!aboutOpen &&
!importOpen &&
!exportOpen &&
!cloudOpen &&
!adminOpen &&
!compareOpen
) {
e.preventDefault();
setSearchOpen(true);
return;
}
const target = e.target as HTMLElement | null;
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return;
if (e.key === '?') {
e.preventDefault();
setHelpOpen((v) => !v);
return;
}
if (helpOpen || aboutOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return;
if (mod && k === 'i') {
e.preventDefault();
setPendingFiles([]);
setImportOpen(true);
return;
}
if (mod && k === 'e') {
e.preventDefault();
openExport();
return;
}
if (mod && k === 'a' && view === 'grid') {
e.preventDefault();
setSelected(sorted.map((p) => p.id));
setAnchorId(sorted[0]?.id ?? null);
return;
}
if (!mod && k === 'c' && view === 'grid' && !trashOpen && selected.length >= 2 && selected.length <= 4) {
e.preventDefault();
setCompareOpen(true);
return;
}
if ((e.key === 'Delete' || e.key === 'Backspace') && selected.length) {
e.preventDefault();
if (trashOpen) void removePhotos(selected);
else trashPhotos(selected);
return;
}
if (view === 'grid') {
if (e.key.startsWith('Arrow')) {
e.preventDefault();
const dx = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
const dy = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : 0;
moveSelection(dx, dy, e.shiftKey);
return;
}
if (e.key === 'Home' || e.key === 'End') {
e.preventDefault();
const target = e.key === 'Home' ? sorted[0] : sorted[sorted.length - 1];
if (target) {
setSelected([target.id]);
setAnchorId(target.id);
}
return;
}
if (k === 'escape') {
setSelected([]);
return;
}
}
if (!selected.length) {
if (k === 'g') setView('grid');
return;
}
if (/^[0-5]$/.test(e.key)) {
bulkUpdate(selected, { rating: Number(e.key) });
e.preventDefault();
return;
}
if (/^[6-9]$/.test(e.key)) {
const label = COLOR_LABELS[Number(e.key) - 6];
if (label) {
bulkUpdate(selected, { color: label.value });
e.preventDefault();
}
return;
}
if (k === 'p') bulkUpdate(selected, { flag: 'pick' });
else if (k === 'x') bulkUpdate(selected, { flag: 'reject' });
else if (k === 'u') bulkUpdate(selected, { flag: 'none' });
else if (k === 'g') setView('grid');
else if (k === 'e' && selected[0]) openPhoto(selected[0]);
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [
selected,
sorted,
anchorId,
view,
bulkUpdate,
openPhoto,
moveSelection,
removePhotos,
trashOpen,
trashPhotos,
openExport,
helpOpen,
importOpen,
exportOpen,
cloudOpen,
adminOpen,
compareOpen,
]);
// Dropping files anywhere in the window imports them, like any desktop editor.
useEffect(() => {
const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files');
let depth = 0;
const onEnter = (e: DragEvent) => {
if (!hasFiles(e)) return;
depth += 1;
setDropActive(true);
};
const onOver = (e: DragEvent) => {
if (!hasFiles(e)) return;
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
};
const onLeave = (e: DragEvent) => {
if (!hasFiles(e)) return;
depth = Math.max(0, depth - 1);
if (!depth) setDropActive(false);
};
const onDrop = (e: DragEvent) => {
if (!hasFiles(e)) return;
e.preventDefault();
depth = 0;
setDropActive(false);
const files = Array.from(e.dataTransfer?.files ?? []);
if (!files.length) return;
setPendingFiles(files);
setImportOpen(true);
};
window.addEventListener('dragenter', onEnter);
window.addEventListener('dragover', onOver);
window.addEventListener('dragleave', onLeave);
window.addEventListener('drop', onDrop);
return () => {
window.removeEventListener('dragenter', onEnter);
window.removeEventListener('dragover', onOver);
window.removeEventListener('dragleave', onLeave);
window.removeEventListener('drop', onDrop);
};
}, []);
const eventName =
eventId === 'all'
? 'All photos'
: eventId === 'unsorted'
? 'Unsorted'
: events.find((e) => e.id === eventId)?.name ?? 'All photos';
const tetherImport = useCallback(
async (files: File[]) => {
if (!tetherEventId) return 0;
const result = await importFiles(
files,
tetherEventId,
[],
undefined,
cloudUser ? { uploadOriginal, push: pushPhoto } : null,
);
if (result.photos.length) {
const tagged = result.photos.map((photo) =>
cloudUser ? { ...photo, workspace: cloudUser.id } : photo,
);
setPhotos((prev) => [...tagged, ...prev]);
}
return result.photos.length;
},
[cloudUser, tetherEventId],
);
const importSidecar = useCallback(async () => {
if (selected.length !== 1) {
setToast('Select exactly one photo to import a sidecar into');
return;
}
const target = photos.find((photo) => photo.id === selected[0]);
if (!target) return;
try {
const xml = await readXmpFile();
if (!xml) return;
const result = xmpToEdits(xml, target.edits);
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar');
setToast(
result.source === 'luminary'
? 'Imported Luminary settings from the sidecar'
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`,
);
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
}
}, [photos, selected, updatePhoto]);
const paletteActions = [
{
id: 'xmp-export',
label: 'Export XMP sidecar for the selection',
hint: 'Sidecar',
run: () => {
const chosen = photos.filter((photo) => selected.includes(photo.id));
if (!chosen.length) {
setToast('Select photos to export sidecars for');
return;
}
for (const photo of chosen) downloadXmp(photo);
setToast(`Exported ${chosen.length} sidecar${chosen.length === 1 ? '' : 's'}`);
},
},
{
id: 'xmp-import',
label: 'Import XMP sidecar into the selected photo',
hint: 'Sidecar',
run: () => void importSidecar(),
},
{
id: 'tether',
label: 'Tether this event from a watch folder',
hint: 'Capture',
run: () => {
if (eventId === 'all' || eventId === 'unsorted') {
setToast('Open an event to tether into it');
return;
}
setTetherEventId(eventId);
},
},
{
id: 'cull-assist',
label: 'Cull assist for the selection',
hint: 'Focus',
run: () => {
if (!selected.length) {
setToast('Select photos to cull');
return;
}
setCullOpen(true);
},
},
{
id: 'import',
label: 'Import photos',
hint: '⌘I',
run: () => {
setPendingFiles([]);
setImportOpen(true);
},
},
{ id: 'export', label: 'Export selected photos', hint: '⌘E', run: openExport },
{ id: 'library', label: 'Go to Library', hint: 'G', run: () => setView('grid') },
{
id: 'develop',
label: activePhoto ? 'Return to Develop' : 'Develop the first photo',
hint: 'E',
run: () => {
if (activePhoto) setView('develop');
else if (sorted[0]) openPhoto(sorted[0].id);
else setToast('There are no photos in this view');
},
},
{
id: 'sidebar',
label: sidebarOpen ? 'Collapse the catalog sidebar' : 'Expand the catalog sidebar',
hint: 'Panels',
run: () => setSidebarOpen((open) => !open),
},
{
id: 'clear-filters',
label: 'Clear library filters',
hint: 'View',
run: () => setFilters(EMPTY_FILTERS),
},
{ id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) },
...(cloudUser &&
eventId !== 'all' &&
eventId !== 'unsorted' &&
photos.some((photo) => photo.eventId === eventId && photo.raw && !photo.deletedAt)
? [
{
id: 'reprocess-event-raws',
label: 'Reprocess all RAW photos in this event',
hint: 'RAW',
run: () => reprocessEventRaws(eventId),
},
]
: []),
...(cloudUser && immichStatus?.enabled && eventId !== 'all' && eventId !== 'unsorted'
? [
{
id: 'immich-publish',
label: 'Publish this event to Immich',
hint: 'Immich',
run: () => void publishEventToImmich(eventId),
},
]
: []),
...(cloudUser && eventId !== 'all' && eventId !== 'unsorted'
? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }]
: []),
];
if (!loaded) {
return (
<div className="splash">
<div className="logo large">Luminary</div>
<p>Opening your library…</p>
</div>
);
}
// The Windows desktop bundle runs as one local admin (LUMINARY_LOCAL=1).
// Accounts and team administration have nothing to manage there, so both
// panels and the entry point to them stay out of the UI.
const localMode = cloudHealth?.local === true;
return (
<div className="app">
<TopBar
view={view}
eventName={eventName}
photoCount={photos.length}
selectedCount={selected.length}
cloudLabel={cloudUser ? cloudUser.name || cloudUser.email : cloudHealth ? 'Sign in' : 'Local only'}
cloudOn={!!cloudUser}
localMode={localMode}
onViewChange={(v) => {
setCatalogOpen(false);
if (v === 'develop' && !activePhoto) {
if (sorted[0]) openPhoto(sorted[0].id);
return;
}
setView(v);
}}
onImport={() => {
setPendingFiles([]);
setImportOpen(true);
}}
onExport={openExport}
onCloud={() => {
setCloudError(null);
setCloudOpen(true);
}}
onHelp={() => setHelpOpen(true)}
onAbout={() => setAboutOpen(true)}
onSearch={() => setSearchOpen(true)}
onCatalog={() => {
setView('grid');
setCatalogOpen(true);
}}
canShare={!!cloudUser && eventId !== 'all' && eventId !== 'unsorted' && !trashOpen}
onShare={() => setShareEventId(eventId)}
/>
{loadError && <div className="banner error">Storage unavailable: {loadError}</div>}
{quota && (quota.warn || quota.over || quota.pruneAt) && (
<div className={`banner quota-banner ${quota.over ? 'quota-banner-over' : ''}`}>
<span>
<strong>
{quota.over
? 'Storage quota exceeded.'
: quota.pruneAt
? 'Storage cleanup scheduled.'
: 'Storage nearly full.'}
</strong>{' '}
{quota.used >= 1024 ** 3
? `${(quota.used / 1024 ** 3).toFixed(1)} GB`
: `${Math.round(quota.used / 1024 ** 2)} MB`}{' '}
of {quota.limit >= 1024 ** 3 ? `${Math.round(quota.limit / 1024 ** 3)} GB` : `${Math.round(quota.limit / 1024 ** 2)} MB`}{' '}
used ({quota.percent}%).{' '}
{quota.pruneAt
? `The oldest planned content will be removed after ${new Date(quota.pruneAt).toLocaleString()}. Free space before then to stop it.`
: 'Delete photos or empty Trash to free space.'}
</span>
</div>
)}
{bridgeEvent?.bridge && (
<div className="banner bridge-banner">
<span>
Advanced edit of “{bridgeEvent.name}” — a temporary copy. Use “Save to
event” on a photo when its look is ready.
</span>
<span className="banner-actions">
<button
className="btn"
disabled={!activePhoto || bridgeBusy}
onClick={saveActiveToEvent}
>
{bridgeBusy ? 'Saving…' : 'Save to event'}
</button>
<a className="btn" href={bridgeEvent.bridge.dashboardUrl}>
Back to dashboard
</a>
</span>
</div>
)}
<div className="app-body">
{view === 'grid' && (
<EventSidebar
collapsed={!sidebarOpen}
mobileOpen={catalogOpen}
events={events}
photos={livePhotos}
eventId={eventId}
trashOpen={trashOpen}
trashCount={trashCount}
onOpenTrash={() => {
setCatalogOpen(false);
setTrashOpen(true);
setEventId('all');
setSelected([]);
}}
onSelectEvent={(id) => {
setCatalogOpen(false);
setTrashOpen(false);
setEventId(id);
}}
immichEnabled={Boolean(immichStatus?.enabled)}
onCreate={async (name, immichGallery) => {
await createEvent(name, { immichGallery });
}}
onSyncGallery={syncEventGallery}
onPublishGallery={publishEventToImmich}
canReprocessRaw={Boolean(cloudUser)}
onReprocessEvent={reprocessEventRaws}
onRename={renameEvent}
onDelete={removeEvent}
onReorderEvents={reorderEvents}
onDropPhotos={movePhotosToEvent}
storageNote={
cloudUser
? `Synced as ${cloudUser.name || cloudUser.email}. Originals live on the team server.`
: cloudHealth
? 'Server found — sign in to share this library with the team.'
: 'Stored in this browser. Run "npm run server" to share with the team.'
}
collections={smartCollections}
activeCollectionId={activeCollection}
onSelectCollection={applySmartCollection}
onDeleteCollection={deleteSmartCollection}
/>
)}
{view === 'grid' && catalogOpen && (
<button
type="button"
className="mobile-catalog-backdrop"
aria-label="Close catalog"
onClick={() => setCatalogOpen(false)}
/>
)}
{view === 'grid' && (
<button
type="button"
className={`dev-edge library-edge ${sidebarOpen ? '' : 'closed'}`}
onClick={() => setSidebarOpen((open) => !open)}
aria-controls="library-sidebar"
aria-expanded={sidebarOpen}
aria-label={sidebarOpen ? 'Collapse catalog sidebar' : 'Expand catalog sidebar'}
title={sidebarOpen ? 'Collapse catalog sidebar' : 'Expand catalog sidebar'}
>
<span className="dev-edge-tab" aria-hidden="true">{sidebarOpen ? '‹' : '›'}</span>
</button>
)}
<main className={`main ${view === 'develop' ? 'main-develop' : ''}`}>
{view === 'grid' ? (
<>
{trashOpen && (
<div className="trash-bar">
<span className="trash-title">Trash · {sorted.length} photo{sorted.length === 1 ? '' : 's'}</span>
<div className="trash-actions">
<button
className="btn small"
disabled={!selected.length}
onClick={() => restorePhotos(selected)}
>
Restore
</button>
<button
className="btn small danger"
disabled={!selected.length}
onClick={() => void removePhotos(selected)}
>
Delete permanently
</button>
<button
className="btn small danger"
disabled={!sorted.length}
onClick={() => void removePhotos(sorted.map((p) => p.id))}
>
Empty trash
</button>
</div>
</div>
)}
<FilterBar
filters={filters}
setFilters={setFilters}
count={sorted.length}
total={scopePhotos.length}
scopePhotos={scopePhotos}
reviewCounts={scopeReviewCounts}
sort={sort}
setSort={setSort}
asc={asc}
setAsc={setAsc}
proofCount={scopedProofCount}
onSaveCollection={() => {
const name = window.prompt('Smart collection name', 'My view');
if (name?.trim()) saveSmartCollection(name);
}}
/>
<LibraryGrid
photos={sorted}
totalCount={photos.length}
selected={selected}
onSelect={selectPhoto}
onContextMenu={openPhotoMenu}
onOpen={openPhoto}
onRate={(id, rating) => updatePhoto(id, { rating })}
onBulkRate={(rating) => bulkUpdate(selected, { rating })}
onBulkFlag={(flag) => bulkUpdate(selected, { flag })}
onBulkColor={(color) => bulkUpdate(selected, { color })}
onSendToImmich={
selected.some((id) => {
const photo = photos.find((item) => item.id === id);
return photo ? canSendToImmich(photo) : false;
})
? () => void pushImmichQueue(photos.filter((photo) => selected.includes(photo.id)))
: undefined
}
immichBusy={Boolean(immichProgress)}
onReprocessRaw={
cloudUser && selected.some((id) => photos.find((photo) => photo.id === id)?.raw)
? () => void reprocessRawPhotos(selected)
: undefined
}
reprocessBusy={rawBusy}
onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))}
onExport={openExport}
onCompare={() => setCompareOpen(true)}
onStack={() => stackSelection(selected)}
onVirtualCopy={() => {
if (selected.length === 1) void createVirtualCopy(selected[0]);
}}
onMerge={() => setMergeOpen(true)}
onPrint={() => setPrintOpen(true)}
stacks={stackMeta}
onToggleStack={toggleStack}
onImport={() => {
setPendingFiles([]);
setImportOpen(true);
}}
onDropFiles={(files) => {
setPendingFiles(files);
setImportOpen(true);
}}
onClearSelection={() => setSelected([])}
onReorder={reorderPhotos}
onMarqueeSelect={(ids) => {
setSelected(ids);
setAnchorId(ids[0] ?? null);
}}
proofCounts={proofCounts}
proofStatus={proofStatus}
/>
</>
) : activePhoto ? (
<Develop
photo={activePhoto}
photos={sorted}
events={events}
onSelect={setActiveId}
onExit={() => setView('grid')}
onUpdate={updatePhoto}
onUpdateEdits={updatePhotoEdits}
clipboard={clipboard}
onCopy={copySettings}
onCopyOf={copySettingsOf}
onPaste={(ids) => openPaste(ids?.length ? ids : [activePhoto.id])}
onResetSelection={resetEdits}
localClipboard={localClipboard}
onLocalClipboard={setLocalClipboard}
onExport={openExport}
onPrint={() => setPrintOpen(true)}
canPushImmich={canSendToImmich(activePhoto)}
onPushImmich={() => void pushImmichQueue([activePhoto])}
onOpenImmich={
activePhoto.immich ? () => openImmichAsset(activePhoto) : undefined
}
presets={[...PRESETS, ...customPresets]}
onSavePreset={savePreset}
onDeletePreset={deletePreset}
onDelete={() => trashPhotos([activePhoto.id])}
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
metadataPresets={metadataPresets}
keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()}
onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)}
onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)}
onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)}
onSaveMetadataPreset={saveMetadataPreset}
onDeleteMetadataPreset={deleteMetadataPreset}
/>
) : (
<div className="empty">
<h2>No photo selected</h2>
<button className="btn" onClick={() => setView('grid')}>
Back to library
</button>
</div>
)}
</main>
</div>
{importOpen && (
<ImportModal
events={events}
initialEventId={eventId}
initialFiles={pendingFiles}
existing={photos}
cloud={cloudUser ? { uploadOriginal, push: pushPhoto } : null}
local={localMode}
onNeedServer={() => {
setImportOpen(false);
setCloudError(null);
setCloudOpen(true);
}}
onClose={() => {
setImportOpen(false);
setPendingFiles([]);
}}
onImported={(imported, targetEventId) => {
const tagged = imported.map((p) =>
cloudUser ? { ...p, workspace: cloudUser.id } : p,
);
for (const p of tagged) putPhoto(p).catch(() => undefined);
setPhotos((prev) => [...tagged, ...prev]);
setEventId(targetEventId);
setSelected(imported.map((p) => p.id));
setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`);
}}
onCreateEvent={createEvent}
immichEnabled={Boolean(immichStatus?.enabled)}
onCreateImmichGallery={createImmichGalleryForEvent}
/>
)}
{compareOpen && selected.length >= 2 && selected.length <= 4 && (
<Suspense fallback={null}>
<CompareView
photos={selected
.map((id) => photos.find((photo) => photo.id === id))
.filter((photo): photo is PhotoRecord => Boolean(photo))
.slice(0, 4)}
onClose={() => setCompareOpen(false)}
onOpen={(id) => {
setCompareOpen(false);
openPhoto(id);
}}
/>
</Suspense>
)}
{printOpen && (
<Suspense fallback={null}>
<PrintModal
photos={photos.filter((photo) => selected.includes(photo.id))}
onClose={() => setPrintOpen(false)}
/>
</Suspense>
)}
{mergeOpen && (
<Suspense fallback={null}>
<MergeModal
photos={photos.filter((photo) => selected.includes(photo.id))}
onClose={() => setMergeOpen(false)}
onDone={(result) => void addMergedPhoto(result)}
/>
</Suspense>
)}
{exportOpen && (
<ExportModal
photos={exportTargets}
initial={exportOptions}
onClose={() => setExportOpen(false)}
recipes={exportRecipes}
onSaveRecipe={(name, options) => {
const next = [...exportRecipes, { id: uid(), name, options }];
setExportRecipes(next);
setKV('exportRecipes', next).catch(() => undefined);
}}
onDeleteRecipe={(id) => {
const next = exportRecipes.filter((recipe) => recipe.id !== id);
setExportRecipes(next);
setKV('exportRecipes', next).catch(() => undefined);
}}
onDone={(message, options) => {
setExportOptions(options);
closeExport(message);
}}
/>
)}
{helpOpen && <Shortcuts onClose={() => setHelpOpen(false)} />}
{aboutOpen && <AboutModal onClose={() => setAboutOpen(false)} />}
{searchOpen && (
<CommandPalette
events={events}
photos={livePhotos}
actions={paletteActions}
onOpenEvent={(id) => {
setTrashOpen(false);
setEventId(id);
setView('grid');
setSelected([]);
}}
onOpenPhoto={openPhoto}
onClose={() => setSearchOpen(false)}
/>
)}
{shareEventId &&
(() => {
const shared = events.find((e) => e.id === shareEventId);
if (!shared) return null;
return (
<Suspense fallback={null}>
<ShareModal
event={shared}
photos={livePhotos.filter((p) => p.eventId === shared.id)}
onClose={() => setShareEventId(null)}
onToast={setToast}
onProofPublished={handleProofPublished}
/>
</Suspense>
);
})()}
{dropActive && (
<div className="drop-overlay">
<div className="drop-overlay-inner">
<strong>Drop to import</strong>
JPEG, PNG, TIFF or camera raw — released anywhere in the window
</div>
</div>
)}
{cloudOpen && !localMode && (
<CloudPanel
health={cloudHealth}
user={cloudUser}
busy={cloudBusy}
note={cloudNote}
error={cloudError}
onLogin={(email, password) => void handleCloudLogin(email, password)}
onRegister={(input) => void handleCloudRegister(input)}
onLogout={() => void handleCloudLogout()}
onSync={() => void handleSync()}
onAdmin={() => {
setCloudOpen(false);
setAdminOpen(true);
}}
onImmich={() => {
setCloudOpen(false);
setImmichOpen(true);
}}
onClose={() => setCloudOpen(false)}
/>
)}
{adminOpen && cloudUser && !localMode && (
<Suspense fallback={null}>
<AdminPanel
user={cloudUser}
onClose={() => setAdminOpen(false)}
onChanged={() => {
void getHealth().then((health) => setCloudHealth(health));
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
}}
onRestored={() => void refreshCatalogFromServer()}
/>
</Suspense>
)}
{immichOpen && cloudUser && (
<Suspense fallback={null}>
<ImmichPanel
onClose={() => setImmichOpen(false)}
onChanged={() => {
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
void refreshCatalogFromServer();
}}
onToast={setToast}
/>
</Suspense>
)}
{menu &&
(() => {
const targets = photos.filter((p) => menu.ids.includes(p.id));
const lead = targets[0];
if (!lead) return null;
const sharedRating = targets.every((p) => p.rating === lead.rating) ? lead.rating : 0;
const sharedFlag = targets.every((p) => p.flag === lead.flag) ? lead.flag : 'none';
const sharedColor = targets.every((p) => p.color === lead.color) ? lead.color : '';
const anyEdited = targets.some((p) => isEdited(p.edits));
const entries: MenuEntry[] = [
{ label: 'Open in Develop', shortcut: 'E', onSelect: () => openPhoto(lead.id) },
'separator',
{ label: 'Copy settings', shortcut: '⌘C', onSelect: () => copySettingsOf(lead.id) },
{
label: 'Paste settings…',
shortcut: '⌘V',
disabled: !clipboard,
onSelect: () => openPaste(menu.ids),
},
{
label: 'Sync settings from this photo…',
disabled: menu.ids.length < 2,
onSelect: () => openPaste(menu.ids, 'sync', lead),
},
'separator',
{ label: 'Reset adjustments', disabled: !anyEdited, onSelect: () => resetEdits(menu.ids) },
{
label: 'Create virtual copy',
disabled: menu.ids.length !== 1,
onSelect: () => void createVirtualCopy(lead.id),
},
'separator',
{
label: 'Compare selected',
shortcut: 'C',
disabled: menu.ids.length < 2 || menu.ids.length > 4,
onSelect: () => {
setSelected(menu.ids);
setCompareOpen(true);
},
},
{
label: 'Stack selected',
disabled: menu.ids.length < 2,
onSelect: () => stackSelection(menu.ids),
},
{
label: 'Unstack',
disabled: !menu.ids.some((id) => photos.find((p) => p.id === id)?.stackId),
onSelect: () => unstackSelection(menu.ids),
},
'separator',
{
label: 'Merge selected…',
disabled: menu.ids.length < 2,
onSelect: () => setMergeOpen(true),
},
...(targets.some(canSendToImmich)
? ([
{
label:
targets.filter(canSendToImmich).length === 1
? 'Send edit to Immich'
: `Send ${targets.filter(canSendToImmich).length} edits to Immich`,
disabled: Boolean(immichProgress),
onSelect: () => void pushImmichQueue(targets),
},
...(lead.immich
? [{ label: 'Open in Immich', onSelect: () => openImmichAsset(lead) }]
: []),
] as MenuEntry[])
: []),
{ label: 'Export…', onSelect: openExport },
{ label: 'Print…', onSelect: () => setPrintOpen(true) },
{
label: trashOpen ? 'Delete permanently…' : 'Move to Trash',
danger: true,
onSelect: () => (trashOpen ? void removePhotos(menu.ids) : trashPhotos(menu.ids)),
},
];
return (
<ContextMenu
x={menu.x}
y={menu.y}
onClose={() => setMenu(null)}
header={
<div className="ctx-rows">
<Stars value={sharedRating} onChange={(n) => bulkUpdate(menu.ids, { rating: n })} size="md" />
<FlagButtons value={sharedFlag} onChange={(f) => bulkUpdate(menu.ids, { flag: f })} />
<ColorSwatches value={sharedColor} onChange={(c) => bulkUpdate(menu.ids, { color: c })} />
</div>
}
entries={entries}
/>
);
})()}
{pasteRequest && (
<PasteSettingsModal
sourceName={pasteRequest.sourceName}
targetCount={pasteRequest.targets.length}
mode={pasteRequest.mode}
onApply={applyPaste}
onClose={() => setPasteRequest(null)}
/>
)}
{immichProgress && (
<div className="toast immich-progress" role="status" aria-live="polite">
<div className="immich-progress-head">
<strong>Sending to Immich</strong>
<span>
{immichProgress.done} / {immichProgress.total}
</span>
</div>
<div className="quota-meter">
<span
style={{
width: `${immichProgress.total ? Math.round((immichProgress.done / immichProgress.total) * 100) : 0}%`,
}}
/>
</div>
<span className="muted small">{immichProgress.current}</span>
</div>
)}
{tetherEventId && (
<TetherPanel
event={{
id: tetherEventId,
name: events.find((e) => e.id === tetherEventId)?.name ?? 'this event',
}}
onImport={tetherImport}
onClose={() => setTetherEventId(null)}
/>
)}
{cullOpen && (
<CullAssistModal
photos={photos.filter((photo) => selected.includes(photo.id))}
onReject={(ids) => bulkUpdate(ids, { flag: 'reject' })}
onClose={() => setCullOpen(false)}
/>
)}
{rawJob && (
<RawReprocessModal
job={rawJob}
onCancel={() => {
rawCancelRef.current = true;
setRawJob((prev) => (prev ? { ...prev, cancelled: true } : prev));
}}
onClose={() => setRawJob(null)}
/>
)}
{toast && (
<div className="toast">
<span>{toast}</span>
{undoAction && toast === undoAction.message && (
<button
type="button"
className="toast-action"
onClick={undoAction.run}
>
Undo
</button>
)}
</div>
)}
</div>
);
}