NGU-Web/src/pages/admin/EntityList.tsx
Aidan Dona 56acedf926 Featured event card beside the hero text; Word import: tabs, quotes, callouts, dividers, videos, buttons
From lg up the featured event's photo sits beside its words, so the card
is about as tall as the hero text. Word import turns a 'Tab:' line into a
tab, the Quote and Intense Quote styles into quotes and callouts, '---'
into a divider, a lone video link into a video and 'Button: label' into
a button; Blog posts shows the whole mapping beside Import from Word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:43:25 -05:00

339 lines
13 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN: ENTITY LIST
One component for organizations, events and people. The :entity
route param picks the manifest; nothing here knows what a
group or a retreat is.
The "New X" link follows the same rule as EntityEdit's save
button: atLeast(user, "editor"), matching requireRole("editor")
on POST /api/admin/:entity. Drawing it is not permission (the
server decides); it only avoids offering a click that 403s, and
avoids hiding one that wouldn't.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useState } from "react";
import { Link, Navigate, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { get, upload, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { ADMIN_ENTITIES, optionsPath } from "../../lib/adminSchema.ts";
import { atLeast } from "../../lib/roles.ts";
export default function EntityList() {
const { entity: entityKey } = useParams();
const manifest = ADMIN_ENTITIES[entityKey ?? ""];
const navigate = useNavigate();
const { user } = useAuth();
const [params, setParams] = useSearchParams();
const [rows, setRows] = useState<any[]>([]);
const [total, setTotal] = useState(0);
// Ids with a draft waiting (server/src/drafts.js), marked in the list.
const [drafts, setDrafts] = useState<Set<string>>(() => new Set());
const [loadingMore, setLoadingMore] = useState(false);
const [options, setOptions] = useState<any>({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<any>(null);
const [query, setQuery] = useState(params.get("q") ?? "");
// Minimum rank, never equality. POST /api/admin/:entity is gated
// at "editor", so anyone from editor upward may create, and the
// equality test this replaced hid the button from superadmins as
// well as editors, which is the failure mode an == against a
// ladder always produces once a rank is added above it.
const canWrite = atLeast(user, manifest?.writeRole ?? "editor");
// The cell that carries the row's link: the primary column, else the first.
const columns = manifest?.list.columns ?? [];
const linkKey = (columns.find((c) => c.primary) ?? columns[0])?.key;
const load = useCallback(async () => {
if (!manifest || manifest.singleton) return;
setLoading(true);
setError(null);
try {
const optsPath = optionsPath(manifest.list.filters);
const [list, opts] = await Promise.all([
get(`/admin/${manifest.key}?${params}`, { ttl: 0 }),
optsPath ? get(optsPath, { ttl: 60_000 }) : { options: {} },
]);
setRows(list.rows);
setTotal(list.total);
setDrafts(new Set((list.drafts ?? []).map(String)));
setOptions(opts.options);
} catch (err) {
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
} finally {
setLoading(false);
}
}, [manifest, params, navigate]);
useEffect(() => {
load();
}, [load]);
// The server sends a page at a time; the next one goes under it.
async function loadMore() {
setLoadingMore(true);
try {
const next = new URLSearchParams(params);
next.set("offset", String(rows.length));
const list = await get(`/admin/${manifest.key}?${next}`, { ttl: 0 });
setRows((current) => [...current, ...list.rows]);
setTotal(list.total);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
} finally {
setLoadingMore(false);
}
}
if (!manifest) {
return <p className="text-muted">No such thing to edit.</p>;
}
// One row, so no list: the tab opens the row.
if (manifest.singleton) {
return <Navigate to={`/admin/${manifest.key}/${manifest.singleton}`} replace />;
}
function setParam(key, value) {
const next = new URLSearchParams(params);
if (value) next.set(key, value);
else next.delete(key);
setParams(next, { replace: true });
}
function labelFor(filter) {
if (filter.optionsFrom) {
return (options[filter.optionsFrom] ?? []).map((o) => [o.id, o.label]);
}
return filter.options.map((o) => (Array.isArray(o) ? o : [o, o]));
}
return (
<div>
<div className="flex flex-wrap items-center gap-4">
<h1 className="text-3xl font-bold text-link">{manifest.label}</h1>
{canWrite && manifest.importer && <ImportButton manifest={manifest} />}
{canWrite && (
<Link
to={`/admin/${manifest.key}/new`}
className={`${manifest.importer ? "" : "ml-auto "}btn bg-action px-4 py-2 text-sm text-white transition-colors hover:bg-action-hover`}
>
New {manifest.singular}
</Link>
)}
</div>
{/* Filters */}
<div className="mt-6 flex flex-wrap items-end gap-3">
{manifest.list.filters.map((filter) => (
<label key={filter.key} className="text-xs text-muted">
<span className="block">{filter.label}</span>
<select
value={params.get(filter.key) ?? ""}
onChange={(e) => setParam(filter.key, e.target.value)}
className="mt-1 border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand"
>
<option value="">All</option>
{labelFor(filter).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</label>
))}
<div className="ml-auto flex gap-2">
<input
type="search"
value={query}
placeholder="Search"
aria-label="Search"
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && setParam("q", query.trim())}
className="border border-muted/25 bg-surface px-4 py-1.5 text-sm text-body outline-none focus:border-brand"
/>
<button
type="button"
onClick={() => setParam("q", query.trim())}
className="btn border border-muted/25 px-4 py-1.5 text-sm text-muted hover:border-brand/50"
>
Search
</button>
</div>
</div>
{error && (
<p
role="alert"
className="mt-6 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger"
>
{error}
</p>
)}
{/* Rows */}
<div className="mt-6 overflow-x-auto border border-brand/20 bg-surface">
<table className="w-full text-left text-sm">
<thead className="border-b border-muted/15 text-xs text-muted">
<tr>
{manifest.list.columns.map((column) => (
<th key={column.key} className="px-4 py-3 font-medium">
{column.label}
</th>
))}
<th className="px-4 py-3 font-medium">Slug</th>
</tr>
</thead>
<tbody>
{/* The row click is for the mouse; the link in the primary
cell is what a keyboard or screen reader uses. */}
{rows.map((row) => (
<tr
key={row.id}
className="cursor-pointer border-b border-muted/10 last:border-0 hover:bg-tint-soft"
onClick={() => navigate(`/admin/${manifest.key}/${row.id}`)}
>
{manifest.list.columns.map((column) => (
<td
key={column.key}
className={`px-4 py-3 ${
column.primary ? "font-medium text-body" : "text-muted"
}`}
>
{column.key === linkKey ? (
<>
<Link
to={`/admin/${manifest.key}/${row.id}`}
onClick={(e) => e.stopPropagation()}
className="hover:underline"
>
{row[column.key] || row.id}
</Link>
{drafts.has(String(row.id)) && (
<span className="ml-2 bg-tint px-2 py-0.5 text-xs font-medium text-link">Draft</span>
)}
</>
) : column.widget === "bool" ? (
row[column.key] ? (
"Yes"
) : (
"-"
)
) : (
row[column.key] || "-"
)}
</td>
))}
<td className="px-4 py-3 font-mono text-xs text-muted">{row.id}</td>
</tr>
))}
</tbody>
</table>
{!loading && rows.length === 0 && (
<p className="px-4 py-8 text-center text-muted">Nothing matches.</p>
)}
{loading && <p className="px-4 py-8 text-center text-muted">Loading…</p>}
</div>
{!loading && rows.length < total && (
<div className="mt-4 flex items-center gap-4">
<button
type="button"
onClick={loadMore}
disabled={loadingMore}
className="btn border border-muted/25 px-4 py-1.5 text-sm text-muted hover:border-brand/50 disabled:opacity-60"
>
{loadingMore ? "Loading…" : "Show more"}
</button>
<p className="text-sm text-muted">
{rows.length} of {total}
</p>
</div>
)}
</div>
);
}
/* A manifest's `importer`: pick a file, the server turns it into a
new record, and its editor opens with a note of what came over
(EntityEdit shows it). Blog posts take Word documents. */
function ImportButton({ manifest }: { manifest: any }) {
const navigate = useNavigate();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function send(file: File) {
setBusy(true);
setError(null);
const form = new FormData();
form.set("file", file);
try {
const result = await upload(manifest.importer.endpoint, form);
navigate(`/admin/${manifest.key}/${result.id}`, { state: { imported: result.summary } });
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
setBusy(false);
}
}
const guide = manifest.importer.guide;
return (
<div className="ml-auto flex flex-wrap items-center gap-3">
{error && (
<span role="alert" className="text-sm text-danger">
{error}
</span>
)}
{guide && (
<details className="relative">
<summary className="cursor-pointer text-sm text-link hover:underline">What becomes what</summary>
<div className="absolute right-0 z-20 mt-2 w-[min(36rem,90vw)] bg-raised p-4 text-sm shadow-xl">
<p className="text-body">{guide.intro}</p>
<table className="mt-3 w-full text-left">
<thead className="text-xs uppercase tracking-wider text-muted">
<tr>
<th className="py-1 pr-4 font-medium">In Word</th>
<th className="py-1 font-medium">In the post</th>
</tr>
</thead>
<tbody>
{guide.rows.map(([from, to]) => (
<tr key={from} className="border-t border-muted/10 align-top">
<td className="py-1.5 pr-4 text-body">{from}</td>
<td className="py-1.5 text-muted">{to}</td>
</tr>
))}
</tbody>
</table>
{guide.outro && <p className="mt-3 text-xs text-muted">{guide.outro}</p>}
</div>
</details>
)}
<label
className={`cursor-pointer btn border border-link px-4 py-2 text-sm text-link transition-colors hover:bg-tint ${
busy ? "pointer-events-none opacity-60" : ""
}`}
>
{busy ? "Importing…" : manifest.importer.label}
<input
type="file"
accept={manifest.importer.accept}
className="sr-only"
disabled={busy}
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (file) send(file);
}}
/>
</label>
</div>
);
}