NGU-Web/src/pages/admin/AdminFeedback.tsx
Zaldimmar b816203c0c Accessibility: reading and color blind modes, audit fixes, calendar window
- Accessibility panel: the switch knob stays in its track; the panel
  follows its button in the Tab order and opens on its first switch.
- Reading mode is the page as plain text: one column, no colors,
  pictures, cards or motion; descriptions stay in place.
- Color blind mode (protanopia, deuteranopia, tritanopia, monochrome):
  palette swaps chosen by simulation, applied to code, data and CSS
  colors on public pages only. The newsletter uses the stored palette.
- Audit fixes: focus not hidden by the header, focus on page change
  and in-page jumps, focus return for the menu, day list and people
  details, labelled admin fields and dialogs, keyboard map tiles,
  scrollable tables, and more.
- Calendar asks /events for its six weeks only (?from=&to=); carousels
  take their 12 most recent past events (?past=12).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:33:09 -05:00

674 lines
25 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN: FEEDBACK TRIAGE
Reads /api/admin/feedback, writes status and notes back through
PATCH, and deletes through DELETE. Deliberately a flat list
rather than a table: the message is the content, and messages
don't fit in a cell.
Two capabilities, two ranks. Editors and above can change a
status or leave a note; deleting is admin and above, matching
requireRole on the server. Both come from the roles ladder
rather than an equality check: a superadmin is not role ===
"admin", and reading it that way is what hid these controls.
Every read passes ttl: 0. The api cache exists for public
content that changes weekly; a triage queue two people are
working at the same time is the opposite case.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { del, get, patch, post, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts";
import { feedbackTypeLabel } from "../../data/feedbackTypes.ts";
import { fromRequest, requestType, requestTypeLabel } from "../../data/requestTypes.ts";
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
const STATUS_STYLE = {
new: "bg-action text-white",
read: "bg-tint text-link",
// The brand green at a tint, as text in light mode and lifted in dark.
actioned: "bg-[color-mix(in_srgb,#56733f_14%,transparent)] text-[color-mix(in_srgb,#56733f_var(--accent-text-mix),#ffffff)]",
archived: "bg-muted/10 text-muted",
spam: "bg-danger-tint text-danger",
};
// created_at is UTC in 'YYYY-MM-DD HH:MM:SS' form, which Safari
// won't parse without the T and the Z.
function formatDate(value) {
const date = new Date(`${value.replace(" ", "T")}Z`);
return date.toLocaleString(undefined, {
dateStyle: "medium",
timeStyle: "short",
});
}
const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
/* A content request's files: each downloads from Drive through the
server, and a Word document can become a draft blog post
(the same import as Blog posts → Import from Word). */
function RequestFiles({ row, canWrite, canRemove }) {
const navigate = useNavigate();
const [files, setFiles] = useState<any[]>(row.files);
const [busy, setBusy] = useState<number | null>(null);
const [confirming, setConfirming] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => setFiles(row.files), [row.files]);
async function makePost(file) {
setBusy(file.id);
setError(null);
try {
const result = await post(`/admin/feedback/${row.id}/files/${file.id}/blog-post`, {});
navigate(`/admin/blog_posts/${result.id}`, { state: { imported: result.summary } });
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
setBusy(null);
}
}
async function remove(file) {
setBusy(file.id);
setError(null);
try {
await del(`/admin/feedback/${row.id}/files/${file.id}`);
setFiles((current) => current.filter((f) => f.id !== file.id));
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't remove it.");
} finally {
setBusy(null);
setConfirming(null);
}
}
if (files.length === 0) return null;
const small = "btn border px-3 py-0.5 text-xs transition-colors disabled:opacity-60";
return (
<div className="mt-4">
<ul className="space-y-2">
{files.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
{file.missing ? (
// Deleted or moved out of Requests in Drive: nothing to open.
<span className="font-medium text-muted line-through">{file.name}</span>
) : (
<a
href={`/api/admin/feedback/${row.id}/files/${file.id}`}
download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
)}
<span className="text-xs text-muted">{sizeOf(file.size)}</span>
{file.missing && (
<span className="bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">
Missing from Drive
</span>
)}
{canWrite && !file.missing && /\.docx$/i.test(file.name) && (
<button
type="button"
disabled={busy !== null}
onClick={() => makePost(file)}
className={`${small} border-link text-link hover:bg-tint`}
>
{busy === file.id ? "Making the post…" : "Make a blog post from it"}
</button>
)}
{canRemove &&
(confirming === file.id ? (
<>
<button
type="button"
disabled={busy !== null}
onClick={() => remove(file)}
className={`${small} border-danger bg-danger text-white`}
>
{busy === file.id ? "Removing…" : "Remove it"}
</button>
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button
type="button"
disabled={busy !== null}
onClick={() => setConfirming(file.id)}
className="text-xs text-muted hover:text-danger"
title={file.missing ? "Take it off this request" : "Into Drive's trash, and off this request"}
>
Remove
</button>
))}
</li>
))}
</ul>
{error && (
<p role="alert" className="mt-2 text-sm text-danger">
{error}
</p>
)}
</div>
);
}
/* A content request's details (049), labeled from requestTypes.ts;
keys it no longer knows are shown as they are. */
function RequestDetails({ row }) {
const entries = Object.entries(row.details ?? {});
if (entries.length === 0) return null;
const labels = new Map((requestType(row.category)?.fields ?? []).map((f) => [f.key, f.label]));
return (
<dl className="mt-4 grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
{entries.map(([key, value]) => (
<div key={key} className="contents">
<dt className="font-medium text-muted">{labels.get(key) ?? key.replace(/_/g, " ")}</dt>
<dd className="whitespace-pre-wrap text-body">{value as string}</dd>
</div>
))}
</dl>
);
}
/* The record a request is about, in its editor: a new one filled in
from the request, or, for an update, the existing one (picked here,
the closest name first) with the requested values beside its own.
Nothing is saved until Save in the editor. */
function RequestRecord({ row }) {
const navigate = useNavigate();
const type = requestType(row.category);
const [candidates, setCandidates] = useState<any[] | null>(null);
const [picked, setPicked] = useState("");
const [error, setError] = useState<string | null>(null);
if (!type) return null;
const state = { fromRequest: fromRequest(row) };
const button =
"btn border border-link px-4 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:opacity-60";
if (row.request_action === "new") {
return (
<div className="mt-4">
<button type="button" className={button} onClick={() => navigate(`/admin/${type.entity}/new`, { state })}>
Create {type.label.toLowerCase()} from this
</button>
</div>
);
}
async function find() {
if (!type) return;
setError(null);
try {
const params = new URLSearchParams({ limit: "500", ...(type.preset ?? {}) });
// The records matching the request's name, however far down the
// list they sort, then the first 500 for picking by hand.
const search = new URLSearchParams(params);
search.set("q", String(row.subject ?? "").trim().slice(0, 100));
const [matches, all] = await Promise.all([
search.get("q") ? get(`/admin/${type.entity}?${search}`, { ttl: 0 }) : { rows: [] },
get(`/admin/${type.entity}?${params}`, { ttl: 0 }),
]);
const seen = new Set();
const rows = [...matches.rows, ...all.rows].filter((r) => !seen.has(r.id) && seen.add(r.id));
const wanted = String(row.subject ?? "").toLowerCase().trim();
const name = (r) => String(r[type.heading] ?? r.id);
// The closest name first: exact, then containing, then the rest.
const score = (r) => {
const n = name(r).toLowerCase();
return n === wanted ? 0 : wanted && (n.includes(wanted) || wanted.includes(n)) ? 1 : 2;
};
const sorted = [...rows].sort((a, b) => score(a) - score(b) || name(a).localeCompare(name(b)));
setCandidates(sorted.map((r) => ({ id: r.id, name: name(r) })));
setPicked(sorted[0]?.id ?? "");
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't load the list.");
}
}
return (
<div className="mt-4 flex flex-wrap items-center gap-3">
{candidates === null ? (
<button type="button" className={button} onClick={find}>
Find the {type.label.toLowerCase()} to update
</button>
) : candidates.length === 0 ? (
<span className="text-sm text-muted">No {type.label.toLowerCase()} records yet.</span>
) : (
<>
<label htmlFor={`record-${row.id}`} className="sr-only">
Which {type.label.toLowerCase()}
</label>
<select
id={`record-${row.id}`}
value={picked}
onChange={(e) => setPicked(e.target.value)}
className="border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
>
{candidates.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button
type="button"
className={button}
disabled={!picked}
onClick={() => navigate(`/admin/${type.entity}/${encodeURIComponent(picked)}`, { state })}
>
Open it with the requested changes
</button>
</>
)}
{error && <span className="text-sm text-danger">{error}</span>}
</div>
);
}
function locationOf(row) {
if (!row.page_path) return "Not page-specific";
return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path;
}
/* ── One submission ──────────────────────────────────────────── */
function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
const [note, setNote] = useState(row.admin_note ?? "");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<any>(null);
const [confirming, setConfirming] = useState(false);
const noteDirty = note !== (row.admin_note ?? "");
async function save(changes) {
setBusy(true);
setError(null);
try {
const data = await patch(`/admin/feedback/${row.id}`, changes);
onChange(data.feedback);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't save that.");
} finally {
setBusy(false);
}
}
// On success this card unmounts, so there's no finally here:
// busy only needs clearing on the path where the row survives.
async function remove() {
setBusy(true);
setError(null);
try {
await del(`/admin/feedback/${row.id}`);
onRemove(row);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't delete that.");
setConfirming(false);
setBusy(false);
}
}
return (
<article className="border border-brand/20 bg-surface p-5">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
<span className="font-semibold text-body">
{row.feedback_type === "content"
? `${row.request_action === "update" ? "Update" : "New"} ${requestTypeLabel(row.category).toLowerCase()}`
: feedbackTypeLabel(row.feedback_type)}
</span>
<span
className={` px-2.5 py-0.5 text-xs font-medium ${
STATUS_STYLE[row.status] ?? ""
}`}
>
{row.status}
</span>
{row.feedback_type !== "content" && <span className="text-muted">{locationOf(row)}</span>}
<span className="ml-auto text-xs text-muted">
#{row.id} · {formatDate(row.created_at)}
</span>
</div>
{row.subject && <h2 className="mt-4 text-lg font-bold text-body">{row.subject}</h2>}
<p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p>
{row.feedback_type === "content" && <RequestDetails row={row} />}
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} canRemove={canRemove} />}
{row.feedback_type === "content" && canWrite && <RequestRecord row={row} />}
<p className="mt-4 text-sm text-muted">
{row.name || row.email ? (
<>
{row.name && <span>{row.name}</span>}
{row.name && row.email && " · "}
{row.email && (
<a
href={`mailto:${row.email}?subject=${encodeURIComponent(row.subject ? `Your request: ${row.subject}` : "Your NGU site feedback")}`}
className="text-link underline underline-offset-2"
>
{row.email}
</a>
)}
</>
) : (
<span className="italic">Sent anonymously</span>
)}
</p>
{canWrite && (
<div className="mt-5 border-t border-muted/15 pt-4">
<div className="flex flex-wrap items-center gap-3">
<label
htmlFor={`status-${row.id}`}
className="text-sm font-medium text-body"
>
Status
</label>
<select
id={`status-${row.id}`}
value={row.status}
disabled={busy}
onChange={(e) => save({ status: e.target.value })}
className="border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
>
{STATUSES.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<textarea
rows={2}
value={note}
disabled={busy}
placeholder="Internal note: who's handling it, what was done"
aria-label="Internal note"
onChange={(e) => setNote(e.target.value)}
className="mt-3 w-full resize-y border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
/>
{noteDirty && (
<button
type="button"
disabled={busy}
onClick={() => save({ admin_note: note })}
className="mt-2 btn bg-action px-4 py-1.5 text-sm text-white transition-colors hover:bg-action-hover disabled:bg-muted/25"
>
{busy ? "Saving…" : "Save note"}
</button>
)}
</div>
)}
{/* Deleting is the irreversible option; marking something
spam or archived is the habit this defers to. Hence the
second click rather than a window.confirm. */}
{canRemove && (
<div className="mt-4 flex flex-wrap items-center gap-3 border-t border-muted/15 pt-4">
{confirming ? (
<>
<span className="text-sm text-body">
Delete #{row.id} for good? Marking it spam keeps it recoverable.
</span>
<button
type="button"
disabled={busy}
onClick={remove}
className="btn bg-danger px-4 py-1.5 text-sm text-white transition-colors hover:bg-[#8f1e18] disabled:bg-muted/25"
>
{busy ? "Deleting…" : "Delete"}
</button>
<button
type="button"
disabled={busy}
onClick={() => setConfirming(false)}
className="btn border border-muted/25 px-4 py-1.5 text-sm text-muted transition-colors hover:border-muted/50"
>
Keep it
</button>
</>
) : (
<button
type="button"
disabled={busy}
onClick={() => setConfirming(true)}
className="btn border border-danger/30 px-4 py-1.5 text-sm text-danger transition-colors hover:bg-danger-tint"
>
Delete
</button>
)}
</div>
)}
{error && (
<p role="alert" className="mt-3 text-sm text-danger">
{error}
</p>
)}
</article>
);
}
/* ── The page ────────────────────────────────────────────────── */
/* The queues this page shows: the website feedback form, content
requests from /request, and data requests from the Privacy page.
Same table, same triage. */
const QUEUES = {
feedback: {
to: "/admin/feedback",
title: "Website feedback",
blurb: "Everything submitted through the site's feedback form.",
},
content: {
to: "/admin/requests",
title: "Content requests",
blurb: "Requests from the site's Request form: blog posts, events, and new or updated organizations, teams, awards and people. Files open from Google Drive.",
},
privacy: {
to: "/admin/data-requests",
title: "Data requests",
blurb: "Requests to see, correct or delete someone's information, from the Privacy page. Each has an email to answer.",
},
} as const;
export default function AdminFeedback({ kind = "feedback" }: { kind?: keyof typeof QUEUES }) {
const { user } = useAuth();
const navigate = useNavigate();
const queue = QUEUES[kind];
const [status, setStatus] = useState("new");
const [query, setQuery] = useState("");
const [search, setSearch] = useState(""); // applied, not typed
const [rows, setRows] = useState<any[]>([]);
const [counts, setCounts] = useState<any>({});
const [newByKind, setNewByKind] = useState<any>({});
const [cursor, setCursor] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<any>(null);
// Minimums, not equality; see lib/roles.ts.
const canWrite = roleCanWrite(user);
const canRemove = canDelete(user);
const load = useCallback(
async (before = null) => {
setLoading(true);
setError(null);
const params = new URLSearchParams();
params.set("kind", kind);
if (status !== "all") params.set("status", status);
if (search) params.set("q", search);
if (before) params.set("before", String(before));
try {
const data = await get(`/admin/feedback?${params}`, { ttl: 0 });
setRows((prev) => (before ? [...prev, ...data.feedback] : data.feedback));
setCounts(data.counts);
setNewByKind(data.newByKind ?? {});
setCursor(data.nextCursor);
} catch (err) {
if (isUnauthorized(err)) {
// Session expired while the page was open.
navigate("/admin/login", { replace: true });
return;
}
setError(
err instanceof ApiError ? err.message : "Couldn't reach the server.",
);
} finally {
setLoading(false);
}
},
[kind, status, search, navigate],
);
useEffect(() => {
load();
}, [load]);
function replaceRow(updated) {
setRows((prev) =>
prev
.map((row) => (row.id === updated.id ? updated : row))
// A row that no longer matches the filter drops out, so
// marking something 'read' clears it from the 'new' queue.
.filter((row) => status === "all" || row.status === status),
);
setCounts((prev) => ({ ...prev })); // counts refresh on next load
}
// The deleted row is passed whole rather than by id: its status
// is what says which tab count to drop.
function removeRow(removed) {
setRows((prev) => prev.filter((row) => row.id !== removed.id));
setCounts((prev) => ({
...prev,
[removed.status]: Math.max((prev[removed.status] ?? 1) - 1, 0),
}));
}
const tabs: any[] = [
{ id: "all", label: "All" },
...STATUSES.map((s) => ({ id: s, label: s, count: counts[s] })),
];
return (
<div>
{/* The two queues, each with what's new in it. */}
<nav aria-label="Forms" className="mb-6 flex gap-1 border-b border-brand/15">
{Object.entries(QUEUES).map(([id, q]) => (
<Link
key={id}
to={q.to}
aria-current={id === kind ? "page" : undefined}
className={
"-mb-px border-b-2 px-4 py-2 text-sm font-semibold transition-colors " +
(id === kind ? "border-link text-link" : "border-transparent text-muted hover:text-link")
}
>
{q.title}
{newByKind[id] ? ` (${newByKind[id]} new)` : ""}
</Link>
))}
</nav>
<h1 className="text-3xl font-bold text-link">{queue.title}</h1>
<p className="mt-2 text-sm text-muted">
{canWrite ? queue.blurb : "Read-only: your account can't change statuses or notes."}
</p>
{/* Filters */}
<div className="mt-6 flex flex-wrap items-center gap-2">
{tabs.map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => setStatus(tab.id)}
className={
"btn px-4 py-1.5 text-sm transition-colors " +
(status === tab.id
? "bg-action font-semibold text-white"
: "border border-muted/25 text-muted hover:border-brand/50")
}
>
{tab.label}
{tab.count ? ` (${tab.count})` : ""}
</button>
))}
<div className="ml-auto flex gap-2">
<input
type="search"
value={query}
placeholder="Search messages"
aria-label="Search messages"
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") setSearch(query.trim());
}}
className="border border-muted/25 bg-surface px-4 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
/>
<button
type="button"
onClick={() => setSearch(query.trim())}
className="btn border border-muted/25 px-4 py-1.5 text-sm text-muted transition-colors hover:border-brand/50"
>
Search
</button>
</div>
</div>
{/* Results */}
{error && (
<p
role="alert"
className="mt-6 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger"
>
{error}
</p>
)}
{!loading && rows.length === 0 && !error && (
<p className="mt-10 text-muted">
Nothing here. {status === "new" ? "The queue is clear." : "Try another filter."}
</p>
)}
<div className="mt-6 space-y-4">
{rows.map((row) => (
<FeedbackCard
key={row.id}
row={row}
canWrite={canWrite}
canRemove={canRemove}
onChange={replaceRow}
onRemove={removeRow}
/>
))}
</div>
{loading && <p className="mt-6 text-sm text-muted">Loading…</p>}
{cursor && !loading && (
<button
type="button"
onClick={() => load(cursor)}
className="mt-6 btn border border-brand px-5 py-2 text-link transition-colors hover:bg-tint"
>
Load older
</button>
)}
</div>
);
}