Files
luminary/src/components/ShareModal.tsx
T
bhursey cd52a2f82f Initial commit: Luminary photo catalog and RAW editor
Browser-based photo catalog with an optional team server (SQLite + LibRaw).
Local database, uploaded photos, build output and dependencies are gitignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-23 15:19:25 +00:00

322 lines
11 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 { useCallback, useEffect, useMemo, useState } from 'react';
import { createShare, getShare, pushProof, revokeShare } from '../lib/api';
import type { ShareState } from '../lib/api';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
import type { ExportOptions } from '../lib/export';
import type { PhotoRecord } from '../types';
interface Props {
event: { id: string; name: string };
photos: PhotoRecord[];
onClose: () => void;
onToast: (message: string) => void;
/** Update the local record after a rendered proof is accepted by the server. */
onProofPublished?: (photoId: string, thumbUrl: string, proofAt: number) => void;
}
const PROOF_EXPORT: ExportOptions = {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'longEdge',
longEdge: 2800,
zip: false,
metadata: false,
outputSharpen: 8,
watermark: { ...DEFAULT_EXPORT.watermark, enabled: false },
};
function proofBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const value = typeof reader.result === 'string' ? reader.result : '';
resolve(value.includes(',') ? value.slice(value.indexOf(',') + 1) : value);
};
reader.onerror = () => reject(reader.error ?? new Error('Could not read the proof'));
reader.readAsDataURL(blob);
});
}
/**
* Owner-side control for a proofing link: turn it on, copy it, see who has
* picked what, and revoke it. Picks live on the server keyed by the link, so
* anyone with the URL can choose photos without an account.
*/
export default function ShareModal({ event, photos, onClose, onToast, onProofPublished }: Props) {
const [share, setShare] = useState<ShareState | null>(null);
const [busy, setBusy] = useState(false);
const [publishing, setPublishing] = useState(false);
const [published, setPublished] = useState(0);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const refresh = useCallback(async () => {
try {
setShare(await getShare(event.id));
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read the proofing link');
}
}, [event.id]);
useEffect(() => {
void refresh();
}, [refresh]);
useEffect(() => {
if (!share?.token) return;
const timer = setInterval(() => void refresh(), 20000);
return () => clearInterval(timer);
}, [refresh, share?.token]);
const url = useMemo(() => {
if (!share?.token) return '';
return `${window.location.origin}/g/${share.token}`;
}, [share]);
const picksByPhoto = useMemo(() => {
const map = new Map<string, string[]>();
for (const pick of share?.picks ?? []) {
const names = map.get(pick.photoId) ?? [];
names.push(pick.clientName || 'Client');
map.set(pick.photoId, names);
}
return map;
}, [share]);
const names = useMemo(() => {
const set = new Set<string>();
for (const pick of share?.picks ?? []) set.add(pick.clientName || 'Client');
return [...set];
}, [share]);
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
const publishProofs = async () => {
if (!photos.length || publishing) return 0;
setPublishing(true);
setPublished(0);
setError(null);
let done = 0;
try {
for (const photo of photos) {
const blob = await renderPhotoBlob(photo, PROOF_EXPORT);
const result = await pushProof(photo.id, await proofBase64(blob));
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
done += 1;
setPublished(done);
}
onToast(`Published ${done} edited proof${done === 1 ? '' : 's'}`);
return done;
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
return done;
} finally {
setPublishing(false);
}
};
const enable = async () => {
setBusy(true);
setError(null);
try {
await createShare(event.id);
await refresh();
// A gallery without rendered proofs would show the unedited originals.
await publishProofs();
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the link');
} finally {
setBusy(false);
}
};
const copy = async () => {
if (!url) return;
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 1800);
} catch {
// Clipboard needs permission; selecting the text still lets them copy it.
setError('Could not copy automatically — select the link and copy it.');
}
};
const revoke = async () => {
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
return;
}
setBusy(true);
try {
await revokeShare(event.id);
setShare({ token: null, picks: [] });
onToast('Proofing link turned off');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not turn off the link');
} finally {
setBusy(false);
}
};
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && !busy && onClose()}
>
<div className="modal share-modal">
<header className="modal-head">
<div>
<h2>Client proofing</h2>
<p className="muted small">
Share “{event.name}” as a public gallery. Clients pick favourites without an
account, and their choices show up here and in the library.
</p>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
×
</button>
</header>
<div className="modal-body">
{error && <div className="banner error">{error}</div>}
{!share ? (
<p className="muted">Reading the link…</p>
) : share.token ? (
<>
<div className="share-link-row">
<input value={url} readOnly spellCheck={false} onFocus={(e) => e.target.select()} />
<button className="btn primary" onClick={() => void copy()}>
{copied ? 'Copied' : 'Copy link'}
</button>
</div>
<p className="muted small">
Anyone with this link can view the {photos.length} photos in this event and pick
favourites. Links can be turned off at any time.
</p>
<div className="share-stats">
<div>
<strong>{share.picks.length}</strong>
<span>picks</span>
</div>
<div>
<strong>{names.length}</strong>
<span>{names.length === 1 ? 'client' : 'clients'}</span>
</div>
<div>
<strong>{new Set(share.picks.map((p) => p.photoId)).size}</strong>
<span>photos chosen</span>
</div>
</div>
<div className="share-publish">
<div>
<strong>Edited proofs</strong>
<p className="muted small">
Generate the gallery from the current crop, grade and retouching. The
originals and editable proxies stay untouched.
</p>
</div>
<button
className="btn primary small"
disabled={busy || publishing || !photos.length}
onClick={() => void publishProofs()}
>
{publishing ? `Publishing ${published}/${photos.length}…` : 'Publish edited proofs'}
</button>
</div>
{(share.feedback ?? []).length > 0 && (
<div className="share-feedback">
<div className="share-picks-head">
<span>Client feedback</span>
<button className="btn ghost small" onClick={() => void refresh()}>
Refresh
</button>
</div>
<ul>
{(share.feedback ?? []).slice(0, 40).map((item, index) => (
<li key={`${item.kind}:${item.photoId}:${item.createdAt}:${index}`}>
<span className="share-pick-name">
{namesByPhoto.get(item.photoId) ?? 'Photo'}
</span>
<span className={`share-feedback-kind ${item.kind}`}>
{item.kind === 'approved'
? 'Approved'
: item.kind === 'changes'
? 'Changes requested'
: item.clientName || 'Client'}
</span>
{item.body && <p>{item.body}</p>}
{item.kind === 'comment' && (
<span className="muted small">{item.clientName || 'Client'}</span>
)}
</li>
))}
</ul>
</div>
)}
{share.picks.length ? (
<div className="share-picks">
<div className="share-picks-head">
<span>Client picks</span>
<button className="btn ghost small" onClick={() => void refresh()}>
Refresh
</button>
</div>
<ul>
{[...picksByPhoto.entries()]
.sort((a, b) => b[1].length - a[1].length)
.map(([photoId, who]) => (
<li key={photoId}>
<span className="share-pick-name">
{namesByPhoto.get(photoId) ?? 'Photo'}
</span>
<span className="muted small">{who.join(', ')}</span>
</li>
))}
</ul>
</div>
) : (
<p className="muted small share-waiting">
No picks yet. Client hearts appear here as they work through the gallery.
</p>
)}
<div className="share-warning">
<button className="btn ghost small danger" disabled={busy} onClick={() => void revoke()}>
Turn off link
</button>
<span className="muted small">Clears the gallery and its picks.</span>
</div>
</>
) : (
<div className="share-empty">
<p>
This event has no proofing link yet. Creating one lets a client review the shoot
and mark favourites.
</p>
<button className="btn primary" disabled={busy} onClick={() => void enable()}>
{busy ? 'Creating…' : 'Create proofing link'}
</button>
</div>
)}
</div>
<footer className="modal-foot">
<span className="muted small">
Photos in the trash and develop settings stay private.
</span>
<button className="btn" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}