import { useCallback, useEffect, useRef, useState } from 'react'; import { useSearchParams } from 'react-router'; import { Images, Loader2, Plus, Trash2 } from 'lucide-react'; import { useClient } from 'hooks/useClient'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { CarouselPicker } from '../CarouselPicker'; import { readableError } from '../errors'; import { useEditorSlot } from '../useEditorSlot'; import { mediaThumbUrl } from '../thumbnail'; import { SubjectFields } from './SubjectFields'; import type { SubjectPhoto, SubjectRecord, SubjectSection } from './subjects'; /** * A list of things, each with a gallery and a form — Collections, and the Gallery's pieces. * * One panel for both. They are the same object edited the same way, and what differs is small enough * to be a configuration: see subjects.ts, which is also where the reasoning lives. * * ── The rows are EDITORIAL ── * * A row exists because somebody made it, not because a folder does. An earlier version read * `originals/COLLECTIONS/` and registered every directory it found, which meant whoever last tidied a * folder decided the website's structure. * * ── The grid is READ-ONLY ── * * The photographs belong to the carousel, and so does their order — including which one leads, which * is simply the first. Making them look pressable here would promise a control that lives in * Carousels. */ export const SubjectPanel = ({ section }: { section: SubjectSection }) => { const client = useClient(); const clientRef = useRef(client); clientRef.current = client; const Icon = section.icon; const [records, setRecords] = useState(null); const [photos, setPhotos] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [name, setName] = useState(''); const [picking, setPicking] = useState(false); // Selection in the URL, like every other screen here — see docs/navigation-audit.md. const [params, setParams] = useSearchParams(); const selectedId = Number(params.get(section.param)) || null; const selected = records?.find((one) => one.id === selectedId) ?? null; const load = useCallback(async () => { try { const response = await clientRef.current.get<{ data: T[] }>(section.endpoint); setRecords(response.data); } catch (failure) { setError(readableError(failure)); setRecords([]); } }, [section.endpoint]); useEffect(() => { void load(); }, [load]); /* A selection naming something that is not there any more. The id lives in the URL, so it outlives the row: delete one with it open, reload, and the address still asks for it. Left alone that became a 404 from the media fetch, rendered as "Not found" over a panel that was otherwise working — an error about the URL, phrased as an error about the server. Dropped rather than reported. There is nothing for anybody to do about it and the correct state is simply "nothing selected". */ useEffect(() => { if (!records || !selectedId) return; if (records.some((one) => one.id === selectedId)) return; setParams( (current) => { const next = new URLSearchParams(current); next.delete(section.param); return next; }, { replace: true }, ); }, [records, selectedId, setParams, section.param]); // The carousel's photographs, re-read when the selection moves. Null while nothing is chosen, so the // empty state and "still loading" are not the same thing. useEffect(() => { if (!selectedId || !selected) { setPhotos(null); return; } let alive = true; setPhotos(null); // Cleared here rather than only on success: an error from the last selection has nothing to say // about this one, and leaving it up reads as the new one having failed too. setError(null); void clientRef.current .get<{ data: SubjectPhoto[] }>(`${section.endpoint}/${selectedId}/media`) .then((response) => alive && setPhotos(response.data)) .catch((failure: unknown) => alive && setError(readableError(failure))); return () => { alive = false; }; }, [selectedId, selected, section.endpoint]); /* The fields, in the editor column — a SIBLING panel, so they are announced rather than rendered. See useEditorSlot. */ const [, setEditor] = useEditorSlot(); const setEditorRef = useRef(setEditor); setEditorRef.current = setEditor; useEffect(() => { setEditorRef.current( selected ? ( void load()} /> ) : null, ); }, [selected, load, section, photos]); useEffect(() => () => setEditorRef.current(null), []); const select = (id: number) => setParams( (current) => { const next = new URLSearchParams(current); next.set(section.param, String(id)); return next; }, { replace: true }, ); const send = async (call: () => Promise) => { setBusy(true); setError(null); try { await call(); await load(); } catch (failure) { setError(readableError(failure)); } finally { setBusy(false); } }; const create = () => send(async () => { const created = await clientRef.current.post<{ data: T }>(section.endpoint, { title: name.trim() }); setName(''); // Straight to it: making one and then having to find it in the list is a step nobody wants. select(created.data.id); }); const remove = () => send(async () => { if (!selected) return; await clientRef.current.delete(`${section.endpoint}/${selected.id}`); setParams( (current) => { const next = new URLSearchParams(current); next.delete(section.param); return next; }, { replace: true }, ); }); const chooseCarousel = (carouselId: number) => send(async () => { if (!selected) return; setPicking(false); await clientRef.current.patch(`${section.endpoint}/${selected.id}`, { carousel_id: carouselId }); }); return (
    {records === null ? (
  • Reading them…
  • ) : records.length === 0 ? (
  • Nothing here yet.
  • ) : ( records.map((record) => (
  • )) )}
{/* Creating is a name and a button, at the bottom of the list it adds to. A dialog for one field is a dialog nobody thanks you for. */}
setName(event.target.value)} onKeyDown={(event) => { if (event.key === 'Enter' && name.trim()) void create(); }} />
{error &&

{error}

} {selected && (
{/* Deleting removes the ROW, never the photographs — they belong to a carousel, which belongs to Carousels. Said on the button so nobody has to find out. */}
)} {!selected ? (

Choose a {section.noun}, or make one.

) : !selected.carousel_id ? (

No carousel yet. Choose one and its photographs appear here.

) : photos === null ? (

Reading the carousel…

) : photos.length === 0 ? (

That carousel is empty. Add photographs to it in Carousels.

) : ( <>

{photos.length} photographs, in the carousel’s order — the first one leads. Reorder them in Carousels.

    {photos.map((photo) => (
  • {photo.name}

  • ))}
)}
{/* `selected` guarded: the picker writes to whatever is open, and there is nothing to write to when nothing is. */} {selected && ( setPicking(false)} onPick={(carouselId) => void chooseCarousel(carouselId)} selected={selected.carousel_id} /> )}
); };