Branchwell

Lumen & Gesso / website · lumengesso.com / app / components / SavedPhotos.tsx

1'use client';
2
3import { useEffect, useState } from 'react';
4import Link from 'next/link';
5import { urlToFile } from '@/app/lib/url-to-file';
6
7type SavedPhoto = { orderId: string; slot: number; name: string };
8
9export function SavedPhotos({ onAdd, disabled = false }: {
10 onAdd?: (file: File, name: string) => void;
11 disabled?: boolean;
12}) {
13 const [photos, setPhotos] = useState<SavedPhoto[] | null>(null);
14 const [error, setError] = useState('');
15 const [loadingPhoto, setLoadingPhoto] = useState('');
16 const [added, setAdded] = useState<string[]>([]);
17 useEffect(() => {
18 const controller = new AbortController();
19 fetch('/api/orders/photos', { signal: controller.signal })
20 .then(async response => {
21 if (!response.ok) throw new Error(response.status === 401 ? 'Sign in to use your saved photos.' : 'Could not load saved photos.');
22 const data = await response.json() as { photos: SavedPhoto[] };
23 setPhotos(data.photos);
24 })
25 .catch(error => { if (!controller.signal.aborted) setError(error.message); });
26 return () => controller.abort();
27 }, []);
28
29 const add = async (photo: SavedPhoto, url: string, id: string) => {
30 setLoadingPhoto(id);
31 setError('');
32 try {
33 const file = await urlToFile(url, `saved-photo-${photo.slot + 1}.jpg`);
34 onAdd?.(file, photo.name);
35 setAdded(previous => [...previous, id]);
36 } catch {
37 setError('Could not add this photo. Try again.');
38 } finally {
39 setLoadingPhoto('');
40 }
41 };
42 return <div className="saved-photos">
43 {error && <p role="alert">{error} {photos === null && <Link href="/login?next=/orders/photos">Sign in</Link>}</p>}
44 {photos === null && !error && <p role="status">Loading saved photos…</p>}
45 {photos?.length === 0 && <p>Photos from cancelled commissions will appear here.</p>}
46 {photos && photos.length > 0 && <ul className="saved-photos__grid">
47 {photos.map((photo, index) => {
48 const url = `/api/orders/photos?order=${encodeURIComponent(photo.orderId)}&slot=${photo.slot}`;
49 const id = `${photo.orderId}:${photo.slot}`;
50 return <li key={id}>
51 {/* eslint-disable-next-line @next/next/no-img-element */}
52 <img src={url + '&thumbnail=1'} alt={photo.name || `Saved photo ${index + 1}`} loading="lazy" />
53 {photo.name && <span>{photo.name}</span>}
54 {onAdd ? <button type="button" className="btn btn--secondary btn--sm" disabled={disabled || !!loadingPhoto || added.includes(id)}
55 onClick={() => void add(photo, url, id)}>{loadingPhoto === id ? 'Adding…' : added.includes(id) ? 'Added' : 'Add photo'}</button>
56 : <Link className="btn btn--secondary btn--sm" href={`/builder?savedPhoto=${encodeURIComponent(id)}`}>Use in a new order</Link>}
57 </li>;
58 })}
59 </ul>}
60 </div>;
61}