NGU-Web/src/pages/admin/EntityEdit.tsx
Zaldimmar d81f7bd856 Adopt the new palette; square corners, superellipse buttons
The theme defaults (light and dark) come from the 16-color grid,
kept as PALETTE in src/lib/color.ts; every text pair passes the
admin's 4.5:1 check. Nothing is rounded any more except buttons,
which share one btn utility (Poppins Bold, a superellipse corner
where the browser has corner-shape) and true dots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:39 -05:00

648 lines
25 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN: ENTITY EDIT
Create and edit for every entity in the manifest. The form holds
the whole nested object (parent row, side tables, child
collections) and PATCH sends the lot. The server replaces
children wholesale, so what you see here is exactly what will
exist afterwards.
Nothing is written until Save, which is what makes removing a
repeater row safe: leaving without saving undoes it. That only
holds if leaving is hard to do by accident, hence the dirty
tracking and the two guards below.
A field the form never sets is left out of the payload entirely,
and the server lets the column's own DEFAULT apply. So a blank
new-record form is deliberate, not lazy: writing "" into every
field is what used to turn a default into a constraint failure.
updated_at rides along untouched. If someone else saved while
this page was open the server answers 409 rather than letting
one of you quietly overwrite the other. Entities with no
updated_at column simply never get one, and the 409 path stays
dormant for them.
Two capabilities, not one role. An editor may create and update
but not delete, so the action bar asks canWrite/canDelete rather
than comparing user.role to a string. The comparison this
replaced (role === "admin") locked superadmins out of saving
the moment a rank above admin existed, which is what an equality
test against a ladder always eventually does.
None of this is protection. The server refuses the request; this
only decides whether to draw a button that would be refused.
The page is laid out as sections: the URL ID, each field group,
then each child collection in a card of its own. SectionNav lists
them (a sticky column on wide screens, a "Jump to" bar below lg),
derived here from the manifest, so no descriptor declares a nav.
The editor asks the layout for extra width to fit it.
slugFrom may name one field or several. Most ids are unique
because the name is: two organizations aren't both called
Northwest. Team ids are the exception: teams.id is a global
primary key, so every org's 'Board' would collide, which is
why the array form exists and teams uses it.
═══════════════════════════════════════════════════════════════ */
import { ArrowLeft } from "@phosphor-icons/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { get, post, patch, del, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { useAdminDetail } from "../../lib/adminTitle.tsx";
import { useWideAdminPage } from "../../lib/adminWidth.tsx";
import { ADMIN_ENTITIES, slugify } from "../../lib/adminSchema.ts";
import { atLeast } from "../../lib/roles.ts";
import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx";
import {
SectionJump,
SectionNav,
type EditorSection,
} from "../../components/admin/SectionNav.tsx";
/* One card per section. scroll-mt clears the sticky "Jump to" bar
below lg, and leaves a little air above the card on desktop. */
const CARD = "mt-6 scroll-mt-16 border border-brand/20 bg-surface p-5 lg:scroll-mt-6";
const sectionId = (name) => `section-${slugify(name)}`;
/* A foreign key refusing to budge is the most common way a save or
delete fails here, and SQLite's own wording explains nothing to
whoever is filling in the form. */
function friendly(message, singular) {
if (/FOREIGN KEY constraint failed/i.test(message ?? "")) {
return `Something still points at this ${singular}. Reassign or remove those first.`;
}
return message;
}
export default function EntityEdit() {
const { entity: entityKey, id } = useParams();
const manifest = ADMIN_ENTITIES[entityKey ?? ""];
const navigate = useNavigate();
const { user } = useAuth();
useWideAdminPage();
const isNew = id === "new";
// From Forms → Content requests (requestTypes.ts, fromRequest): a
// new record starts filled in with it; an existing one shows it in
// RequestedChanges to use value by value.
const fromRequest = (useLocation().state as any)?.fromRequest ?? null;
// Editor, unless the entity asks for more (site settings:
// superadmin), matching the server's writeRole.
const canWrite = atLeast(user, manifest?.writeRole ?? "editor");
const canDelete = atLeast(user, "admin");
// Some entities have no slug: the table assigns an integer id, so
// there is nothing to type on create and nothing to compose from
// other fields. Timeline entries are the first: an entry that
// references an event has no name of its own.
const autoId = manifest?.idKind === "auto";
// A singleton has one row, made by its migration: no slug to show
// or type, no list to go back to, nothing to delete. The server
// refuses create and delete regardless; this only stops offering
// them.
const singleton = Boolean(manifest?.singleton);
// Hoisted above the loading guards: the title hook below is a
// hook, so it can't sit after an early return, and it needs the
// same paths the heading uses.
const slugPaths = Array.isArray(manifest?.slugFrom)
? manifest.slugFrom
: [manifest?.slugFrom].filter(Boolean);
// Everything before the last path is a qualifier: a fact about
// another field rather than something to type. It renders as
// fixed text inside the slug box, and the editable part is only
// what follows it.
const qualifierPaths = slugPaths.slice(0, -1);
// Empty until every qualifier is chosen, because half a prefix
// would be saved into an id that then never matches.
const prefixOf = (source) => {
if (qualifierPaths.length === 0) return "";
const parts = qualifierPaths.map((path) => getPath(source, path));
if (parts.some((part) => !part)) return "";
return `${slugify(parts.join(" "))}-`;
};
// What to show grayed out before then: org_id becomes "org-".
const prefixHint = qualifierPaths.length
? `${qualifierPaths.map((path) => path.replace(/_id$/, "")).join("-")}-`
: "";
const tailOf = (source) => {
const prefix = prefixOf(source);
const value = source?.id ?? "";
return prefix && value.startsWith(prefix) ? value.slice(prefix.length) : value;
};
// The heading wants the specific half, not the qualifier: a team
// page reads "Board", not "northwest Board". An entity with no slug
// names the field to read instead.
const headingPath = slugPaths[slugPaths.length - 1] ?? manifest?.titleFrom;
const [form, setForm] = useState<any>(null);
const [options, setOptions] = useState<any>({});
const [errors, setErrors] = useState<any>({});
const [message, setMessage] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [slugTouched, setSlugTouched] = useState(false);
// The last state the server confirmed. Everything else compares
// against this to decide whether there's anything to lose.
const baseline = useRef<any>(null);
const load = useCallback(async () => {
if (!manifest) return;
setLoading(true);
setErrors({});
try {
const opts = await get("/admin/options", { ttl: 60_000 });
setOptions(opts.options);
if (isNew) {
// Blank children arrays matter: an absent key means "don't
// touch", which is wrong for a row that doesn't exist yet.
// The parent's own fields stay absent on purpose so the
// server's column defaults apply to whatever isn't filled in.
// No id key for an auto entity: the table assigns it, and
// sending "" would be an explicit value rather than an absence.
const blank = autoId ? {} : { id: "" };
for (const child of manifest.children ?? []) blank[child.key] = [];
// The baseline stays the empty form, so a filled-in one counts
// as unsaved until Create.
baseline.current = JSON.stringify(blank);
let start: any = blank;
if (fromRequest) {
for (const item of fromRequest.set) start = setPath(start, item.path, item.value);
for (const item of fromRequest.add) start = { ...start, [item.child]: [...(start[item.child] ?? []), item.row] };
if (!autoId && headingPath) {
start = { ...start, id: `${prefixOf(start)}${slugify(getPath(start, headingPath) ?? "")}` };
}
}
setForm(start);
} else {
const data = await get(`/admin/${manifest.key}/${id}`, { ttl: 0 });
setForm(data.row);
baseline.current = JSON.stringify(data.row);
}
setMessage(null);
} catch (err) {
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
setMessage({
tone: "error",
text: err instanceof ApiError ? err.message : "Couldn't load that.",
});
} finally {
setLoading(false);
}
// prefixOf and headingPath follow the manifest, already a dependency.
}, [manifest, id, isNew, autoId, navigate, fromRequest]);
useEffect(() => {
load();
}, [load]);
const dirty = useMemo(
() => Boolean(form) && JSON.stringify(form) !== baseline.current,
[form],
);
// The tab says what's on screen; the layout adds the section and
// the site name. Null while loading, so it reads "Teams | NGU
// Admin CMS" for the half-second before the record arrives
// rather than flashing a slug.
useAdminDetail(
!manifest
? null
: isNew
? `New ${manifest.singular}`
: form
? getPath(form, headingPath) || form.id
: null,
);
// Closing the tab or hitting the browser back button skips React
// Router entirely, so the only hook available is this one.
useEffect(() => {
if (!dirty) return undefined;
const warn = (event) => {
event.preventDefault();
event.returnValue = "";
};
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [dirty]);
if (!manifest) return <p className="text-muted">No such thing to edit.</p>;
if (loading || !form) return <p className="text-muted">Loading…</p>;
/* ── Heading ───────────────────────────────────────────────── */
const heading = singleton ? manifest.label : getPath(form, headingPath) || form.id;
const updatedAt = form.updated_at;
const children = manifest.children ?? [];
/* ── Actions ───────────────────────────────────────────────── */
const leave = (to) => {
if (dirty && !window.confirm("Leave without saving? Your changes will be lost.")) return;
navigate(to);
};
const change = (path, value) => {
setForm((prev) => {
let next = setPath(prev, path, value);
// Recompose the id whenever one of its sources moves. The
// prefix always follows the organization; picking a
// different one has to change the slug, or it would claim a
// team belongs somewhere it doesn't. The tail only follows
// the name until someone types over it.
if (isNew && slugPaths.includes(path)) {
const tail = slugTouched
? tailOf(prev)
: slugify(getPath(next, headingPath) ?? "");
next = { ...next, id: `${prefixOf(next)}${tail}` };
}
return next;
});
// Clear this field's error as soon as it's touched; leaving a
// stale red outline on a field the user just fixed reads as a
// save that didn't take.
setErrors((prev) => (prev[path] ? { ...prev, [path]: undefined } : prev));
};
async function save() {
setSaving(true);
setErrors({});
setMessage(null);
try {
const data = isNew
? await post(`/admin/${manifest.key}`, form)
: await patch(`/admin/${manifest.key}/${id}`, form);
setForm(data.row);
baseline.current = JSON.stringify(data.row);
setMessage({ tone: "ok", text: "Saved." });
if (isNew) navigate(`/admin/${manifest.key}/${data.row.id}`, { replace: true });
} catch (err) {
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
if (err instanceof ApiError) {
// 409 means the updated_at we're holding is stale. Every
// further save will fail the same way until the page is
// reloaded, so offer that rather than just saying no.
if (err.status === 409) {
setMessage({ tone: "error", text: err.message, recover: "reload" });
} else {
setErrors(err.fields ?? {});
setMessage({
tone: "error",
text: err.fields
? "Some fields need attention."
: friendly(err.message, manifest.singular),
});
}
} else {
setMessage({ tone: "error", text: "Couldn't reach the server." });
}
} finally {
setSaving(false);
}
}
async function remove() {
if (!window.confirm(`Delete ${heading}? Its links, blocks and roles go with it.`)) return;
try {
await del(`/admin/${manifest.key}/${id}`);
baseline.current = JSON.stringify(form); // nothing left to warn about
navigate(`/admin/${manifest.key}`, { replace: true });
} catch (err) {
setMessage({
tone: "error",
text:
err instanceof ApiError
? friendly(err.message, manifest.singular)
: "Couldn't delete that.",
});
}
}
const visible = (when) => !when || getPath(form, when.path) === when.value;
const groups = manifest.groups.filter((group) => visible(group.when));
const shownChildren = children.filter((child) => visible(child.when));
const childHasError = (key) =>
Object.keys(errors).some((path) => errors[path] && path.startsWith(`${key}.`));
// A singleton's only header box is "Last saved", and a new
// auto-id record has no box at all: neither is worth a nav entry.
const idSection = !singleton && (!autoId || !isNew);
const sections: EditorSection[] = [
...(idSection
? [{ id: "section-url-id", label: manifest.idLabel, hasError: Boolean(errors.id) }]
: []),
...groups.map((group) => ({
id: sectionId(group.legend),
label: group.legend,
hasError: group.fields.some((field) => errors[field.path]),
})),
...shownChildren.map((child) => ({
id: sectionId(`${child.key}-list`),
label: child.label,
count: (form[child.key] ?? []).length,
hasError: childHasError(child.key),
})),
];
return (
<div className="pb-24">
{!singleton && (
<button
type="button"
onClick={() => leave(`/admin/${manifest.key}`)}
className="text-sm text-muted hover:text-link"
>
<ArrowLeft size="1em" weight="bold" className="inline align-[-0.125em]" aria-hidden="true" /> {manifest.label}
</button>
)}
<h1 className="mt-2 text-3xl font-bold text-link">
{isNew ? `New ${manifest.singular}` : heading}
</h1>
<ImportedNote />
{fromRequest && (
<RequestedChanges
request={fromRequest}
isNew={isNew}
form={form}
onUse={change}
onAdd={(child, row) => setForm((prev) => ({ ...prev, [child]: [...(prev[child] ?? []), row] }))}
/>
)}
{/* Straight in the page, not wrapped: a sticky element only
travels within its parent, so its parent has to be tall. */}
<SectionJump sections={sections} />
<div className="lg:grid lg:grid-cols-[13rem_minmax(0,1fr)] lg:items-start lg:gap-10">
{/* The grid cell is what sticks: it spans the grid, where the
nav inside it would only span itself and have nowhere to go. */}
<div className="lg:sticky lg:top-0 lg:pt-6">
<SectionNav sections={sections} />
</div>
<div className="min-w-0">
{/* Slug. An auto-id entity has nothing to ask for on create, and
nothing editable afterwards, so it gets a plain line rather
than a disabled box pretending to be a field. */}
{singleton ? (
updatedAt && (
<div className={CARD}>
<p className="text-sm text-muted">Last saved {updatedAt}</p>
</div>
)
) : autoId ? (
!isNew && (
<div id="section-url-id" className={CARD}>
<p className="text-sm text-muted">
{manifest.idLabel} #{form.id}
{form.updated_at && <> · last saved {form.updated_at}</>}
</p>
</div>
)
) : (
<div id="section-url-id" className={CARD}>
<Field
field={{
path: "id",
label: manifest.idLabel,
prefix: isNew && qualifierPaths.length ? prefixOf(form) || prefixHint : undefined,
prefixPending: isNew && !prefixOf(form),
placeholder: isNew && qualifierPaths.length ? "board" : undefined,
readOnly: !isNew,
help: !isNew
? "Fixed once created, since links and content blocks reference it."
: qualifierPaths.length
? "The prefix comes from the organization. Type the rest."
: "Lowercase, hyphens, no spaces. Can't be changed later.",
}}
value={isNew ? tailOf(form) : form.id}
error={errors.id}
onChange={(value) => {
setSlugTouched(true);
change("id", `${prefixOf(form)}${slugify(value)}`);
}}
/>
{!isNew && form.updated_at && (
<p className="mt-2 text-xs text-muted">
Last saved {form.updated_at}
</p>
)}
</div>
)}
{/* Field groups */}
{groups.map((group) => (
<section key={group.legend} id={sectionId(group.legend)} className={CARD}>
<h2 className="text-lg font-semibold text-body">{group.legend}</h2>
{group.note && <p className="mt-1 text-sm text-muted">{group.note}</p>}
<div className="mt-4">
<FieldGrid>
{group.fields.map((field) => (
<Field
key={field.path}
field={field}
row={form}
value={getPath(form, field.path)}
options={options}
error={errors[field.path]}
onChange={(value) => change(field.path, value)}
/>
))}
</FieldGrid>
</div>
</section>
))}
{/* Child collections, a card each, so the front page's slides,
stats and paths read as separate things. */}
{shownChildren.map((child) => (
<div key={child.key} id={sectionId(`${child.key}-list`)} className={CARD}>
<Repeater
spec={child}
rows={form[child.key]}
options={options}
errors={errors}
errorPrefix={`${child.key}.`}
className=""
onChange={(rows) => setForm((prev) => ({ ...prev, [child.key]: rows }))}
/>
</div>
))}
</div>
</div>
{/* Sticky action bar */}
<div className="fixed inset-x-0 bottom-0 border-t border-brand/20 bg-surface/95 backdrop-blur">
<div className="mx-auto flex max-w-5xl flex-wrap items-center gap-4 px-6 py-3">
{canWrite ? (
<>
<button
type="button"
onClick={save}
disabled={saving || !dirty}
className="btn bg-action px-6 py-2 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25"
>
{saving ? "Saving…" : isNew ? "Create" : "Save changes"}
</button>
{!isNew && !singleton && canDelete && (
<button
type="button"
onClick={remove}
className="btn border border-danger/40 px-4 py-2 text-sm text-danger transition-colors hover:bg-danger-tint"
>
Delete
</button>
)}
</>
) : (
<span className="text-sm text-muted">
Read-only: your account can view this but not change it.
</span>
)}
{dirty && !saving && (
<span className="text-sm text-muted">Unsaved changes</span>
)}
{message && (
<span
role="status"
className={`flex items-center gap-2 text-sm ${
message.tone === "ok" ? "text-link" : "text-danger"
}`}
>
{message.text}
{message.recover === "reload" && (
<button
type="button"
onClick={load}
className="btn border border-danger/40 px-3 py-1 text-xs"
>
Reload
</button>
)}
</span>
)}
</div>
</div>
</div>
);
}
/* After Import from Word (EntityList's ImportButton): what came over,
and what's left to do before publishing. Gone on the next visit. */
function ImportedNote() {
const summary = (useLocation().state as any)?.imported;
if (!summary) return null;
const parts = [
`${summary.headings} headings`,
`${summary.paragraphs} paragraphs`,
`${summary.lists} lists`,
`${summary.tables} tables`,
];
return (
<p role="status" className="mt-4 border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
Imported from Word: {parts.join(", ")}.
{summary.skipped?.images
? ` ${summary.skipped.images} image${summary.skipped.images === 1 ? " was" : "s were"} not carried over; add them as Image blocks.`
: ""}{" "}
It's saved unpublished: check it, add the authors and a cover, then tick Published.
</p>
);
}
/* From a content request (Forms → Content requests). A new record
is already filled in: this says so. An existing one lists each
requested value beside the current one, to use or leave; nothing
changes until it's used, and nothing is saved until Save. */
function RequestedChanges({ request, isNew, form, onUse, onAdd }: any) {
const [done, setDone] = useState<Set<string>>(() => new Set());
const mark = (key: string) => setDone((prev) => new Set(prev).add(key));
const button = "btn border border-link px-3 py-0.5 text-xs text-link transition-colors hover:bg-tint";
if (isNew) {
return (
<p role="status" className="mt-4 border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
Filled in from content request #{request.request}. Check it, fill in the rest, then Create. It isn't saved yet.
</p>
);
}
const items = [
...request.set.map((item) => ({ key: `set:${item.path}`, ...item, current: getPath(form, item.path) })),
...request.add.map((item, i) => ({ key: `add:${i}`, ...item })),
];
if (items.length === 0) {
return (
<p className="mt-4 border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
Content request #{request.request} has no details to copy; its message is in Forms → Content requests.
</p>
);
}
return (
<div className="mt-4 border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
<p className="font-semibold">Requested in content request #{request.request}</p>
<p className="mt-0.5 text-xs text-muted">Use what should change, then Save changes.</p>
<ul className="mt-3 space-y-2">
{items.map((item) => (
<li key={item.key} className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="font-medium">{item.label}</span>
{"path" in item ? (
<>
<span className="text-muted">
now {item.current ? <q>{String(item.current)}</q> : "blank"}, requested <q>{item.value}</q>
</span>
{done.has(item.key) || String(item.current ?? "") === item.value ? (
<span className="text-xs text-muted">in the form</span>
) : (
<button type="button" className={button} onClick={() => {
onUse(item.path, item.value);
mark(item.key);
}}>
Use this
</button>
)}
</>
) : done.has(item.key) ? (
<span className="text-xs text-muted">added below</span>
) : (
<button type="button" className={button} onClick={() => {
onAdd(item.child, item.row);
mark(item.key);
}}>
Add it
</button>
)}
</li>
))}
</ul>
</div>
);
}