NGU-Web/src/components/admin/fields.tsx
Zaldimmar 048c7599ce Fix dark mode and bring the public design in line with the taste audit
- Dark mode: the countdown card, timeline section, Giving text, error
  text, the Leadership button, skeletons and the admin's dark text all
  follow the tokens; logos get a light plate in dark mode
- One BRAND accent (the button token, so the admin palette reaches
  every page) and one ACCENTS family in color.ts, replacing 20 local
  teal constants and the purple, ochre and rust section colours;
  neon green and gold become mint and brand green
- Shadows are tinted with the site's ink; glow shadows are gone
- One giving label, Give, in the nav, footer and Giving page
- Phosphor icons replace the hand-drawn SVGs and the glyph icons;
  Pathfinder paths pick a named icon (emoji still shown) and lose the
  watermark
- Home keeps two eyebrows; StatsBand's title is a real heading;
  section headings step down under the page title
- Nav links switch to the menu below lg, so they never wrap; jump
  links land clear of the header; press feedback on buttons
- Empty sections say what's coming and who to ask; loading is a
  skeleton; form placeholders and borders are readable; one
  corner-radius rule; theme-color for both modes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:54:03 -05:00

706 lines
27 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN FORM PRIMITIVES
Field renders one input from a manifest entry. Repeater renders
an ordered collection of them, and nests one level for content
blocks and their items.
Ordering is array position (the server writes sort_order from
the index), so moving a row is a splice, not a number to
hand-edit.
Rows fold to their title line. They start folded, so a long
collection (the front page's slides and paths) reads as a list
rather than a wall of fields; a row just added starts open, and
one the server rejected opens itself so the error can't hide.
Which rows are open is a set of indices, remapped by every move,
insert and removal here, so it survives a save (which replaces
every row object but keeps their order). Rows can be dragged by the handle or moved with the
arrow buttons; the arrows are the keyboard path and stay whether
or not a pointer is in use.
A row added and never filled in is dropped by the server rather
than rejected, which depends on spec.blank seeding nothing the
server doesn't also declare as a column default. If you give a
blank row a starting value here, add the matching default: to
that column in the server's admin-schema.js or the row will be
saved as real input.
In a repeater row, `when: { path, value }` shows a field only
while another field of the row holds that value (or one of them,
given an array). A field that goes hidden is cleared, so a row
can't keep a value for a choice it no longer makes: a featured
card switched from "record" to "link" drops its record.
`when: { scope: "parent", path, value }` looks at the row this
collection belongs to instead: a schedule entry shows its day and
time only while the block above it is a schedule.
A nested collection takes `when` the same way, and one that goes
hidden is emptied: a list block turned into a paragraph drops its
items.
`help` and `label` may be functions of the row, for wording that
depends on another field (a content block's type says what its
text is).
`preview` on a collection names an entry in PREVIEWS below; each
open row then shows how it will look on the site, drawn by the
site's own component.
Every row can be duplicated (a copy lands below it, ids stripped
so it saves as new) or have a blank row inserted below it, as
well as appended at the end.
`widget: "linkPreview"` is a URL box with a "Fetch preview" button
(LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty
title, blurb and image through `onPatch`.
`widget: "image"` is a text box with a preview and upload and
library buttons beside it (ImageInput in MediaLibrary.tsx). Its
`resolve` option is the media.ts helper for the field's public/
directory, so a bare filename previews from the right place.
Two options change the box itself rather than what goes in it:
prefix fixed text inside the box, left of the cursor. The
value it decorates is only the part after it, so
the caller joins the two. Used by composed slugs,
where the prefix is a fact about another field
rather than something to retype.
readOnly shown, selectable, not editable. Deliberately not
`disabled`: a disabled control reads as switched
off and drops out of the tab order, whereas an
immutable id is settled fact you still want to be
able to read and copy.
═══════════════════════════════════════════════════════════════ */
import { ArrowUp, ArrowDown, CaretRight } from "@phosphor-icons/react";
import { useRef, useState } from "react";
import ContentBlocks from "../ContentBlocks.tsx";
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
/* Live previews a collection can name with `preview`. Each gets the
row as the form holds it, which is the API's shape. */
const PREVIEWS = {
// The form holds an entry's person as person_id; the renderer wants
// the person, so it's looked up in the select options (a name, no
// photo: the options carry no more).
contentBlock: (row, options) => (
<ContentBlocks
blocks={[
{
...row,
items: (row.items ?? []).map((item) => {
const person = item.person_id
? options?.people?.find((p) => p.id === item.person_id)
: null;
return { ...item, person: person ? { id: person.id, name: person.label } : null };
}),
},
]}
/>
),
};
const input =
"w-full rounded-lg border border-muted/25 bg-surface px-3 py-2 text-sm text-body " +
"outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25";
/* Same box, but lit by the real input nested inside it. */
const inputShell =
"flex w-full items-center rounded-lg border border-muted/25 bg-surface px-3 py-2 text-sm " +
"text-body transition-colors focus-within:border-brand focus-within:ring-2 " +
"focus-within:ring-brand/25";
const inputError = "border-danger focus:border-danger focus:ring-danger/20";
const shellError =
"border-danger focus-within:border-danger focus-within:ring-danger/20";
/* Reads as settled fact rather than as an empty box someone forgot
to fill in. */
const inputLocked =
"w-full rounded-lg border border-muted/20 bg-tint-soft px-3 py-2 text-sm " +
"text-muted outline-none cursor-default focus:border-muted/40";
/* ── Dotted paths ────────────────────────────────────────────── */
/* What an empty colour field shows in its swatch and placeholder:
the field's own default (a value, or one worked out from the row),
else the brand teal. */
function colorPlaceholder(field, row): string {
const own = typeof field.placeholder === "function" ? field.placeholder(row) : field.placeholder;
return own || "#138ba0";
}
export function getPath(object, path) {
// An entity with no slug has no heading path either, and a missing
// path should read as "no value" rather than throwing on .split.
if (!path) return undefined;
return path.split(".").reduce((value, key) => value?.[key], object);
}
export function setPath(object, path, value) {
const [head, ...rest] = path.split(".");
if (rest.length === 0) return { ...object, [head]: value };
return { ...object, [head]: setPath(object?.[head] ?? {}, rest.join("."), value) };
}
/* ── Conditional fields ──────────────────────────────────────── */
export function fieldShown(field, row, parent?) {
if (!field.when) return true;
const want = Array.isArray(field.when.value) ? field.when.value : [field.when.value];
const source = field.when.scope === "parent" ? parent : row;
return want.includes(source?.[field.when.path]);
}
/* A row after an edit, with any field the edit hid cleared. "" is
the engine's deliberate clear, so it saves as NULL. */
function withHiddenCleared(spec, row, parent?) {
let next = row;
for (const field of spec.fields) {
const value = next[field.path];
if (!fieldShown(field, next, parent) && value != null && value !== "") {
next = { ...next, [field.path]: "" };
}
}
for (const nested of spec.children ?? []) {
const rows = next[nested.key];
if (!rows?.length) continue;
if (!fieldShown(nested, next, parent)) {
next = { ...next, [nested.key]: [] };
} else {
// Its rows may have fields that follow this row (scope
// "parent"), which this edit may just have hidden.
const cleared = rows.map((child) => withHiddenCleared(nested, child, next));
if (cleared.some((child, i) => child !== rows[i])) next = { ...next, [nested.key]: cleared };
}
}
return next;
}
/* A copy of a row with every id removed, nested rows included, so
the server inserts it as new rather than colliding with the row
it was copied from. */
function withoutIds(value) {
if (Array.isArray(value)) return value.map(withoutIds);
if (!value || typeof value !== "object") return value;
const copy = {};
for (const [key, inner] of Object.entries(value)) {
if (key !== "id") copy[key] = withoutIds(inner);
}
return copy;
}
const helpText = (field, row) => (typeof field.help === "function" ? field.help(row) : field.help);
/* ── Field ───────────────────────────────────────────────────── */
export function Field({ field, value, row, options, error, onChange, onPatch }: any) {
const id = `f-${field.path.replace(/\./g, "-")}`;
const widget = field.widget ?? "text";
const locked = Boolean(field.readOnly);
let list: any = null;
let orphaned = false;
if (widget === "select") {
list = field.optionsFrom
? (options?.[field.optionsFrom] ?? []).map((o) => [o.id, o.label, o])
: (field.options ?? []).map((o) =>
Array.isArray(o) ? [o[0], o[1]] : [o, o],
);
if (field.filterBy && row) {
list = list.filter(([, , raw]) => !raw || field.filterBy(raw, row));
}
// A stored value with no matching option renders as the blank
// choice, which reads as "nobody set this" and saves as a
// deliberate clear. It usually means the row it pointed at was
// deleted, so keep it on screen and say so.
orphaned =
value != null &&
value !== "" &&
!list.some(([optionId]) => String(optionId) === String(value));
}
const common = {
id,
className: `${input} ${error ? inputError : ""}`,
value: value ?? "",
onChange: (e) => onChange(e.target.value),
};
return (
<div className={field.full ? "sm:col-span-2" : ""}>
<label htmlFor={id} className="block text-sm font-medium text-body">
{typeof field.label === "function" ? field.label(row) : field.label}
{field.required && !locked && <span className="ml-1 text-danger">*</span>}
</label>
<div className="mt-1.5">
{widget === "checkbox" ? (
<label className="flex items-center gap-2 text-sm text-muted">
<input
id={id}
type="checkbox"
checked={value === 1 || value === true}
disabled={locked}
onChange={(e) => onChange(e.target.checked ? 1 : 0)}
className="h-4 w-4 rounded border-muted/40 text-link focus:ring-brand/40 disabled:opacity-50"
/>
{helpText(field, row) ?? "Yes"}
</label>
) : widget === "textarea" ? (
<textarea
{...common}
rows={4}
readOnly={locked}
className={`${locked ? inputLocked : common.className} resize-y`}
/>
) : widget === "select" ? (
// A select has no readOnly, so this one really does have
// to be disabled: there's no way to keep it focusable
// and still refuse a new choice.
<select
{...common}
disabled={locked}
className={`${locked ? inputLocked : common.className} ${
orphaned && !locked ? inputError : ""
}`}
>
<option value="">{field.blankLabel ?? "- Please choose from the list -"}</option>
{orphaned && <option value={value}>{value} no longer exists</option>}
{list.map(([id2, label]) => (
<option key={id2} value={id2}>
{label}
</option>
))}
</select>
) : widget === "color" ? (
<div className="flex gap-2">
<input
type="color"
value={/^#[0-9a-f]{6}$/i.test(value ?? "") ? value : colorPlaceholder(field, row)}
disabled={locked}
onChange={(e) => onChange(e.target.value)}
className="h-9 w-12 shrink-0 rounded border border-muted/25 bg-surface disabled:opacity-50"
/>
<input
{...common}
readOnly={locked}
placeholder={colorPlaceholder(field, row)}
className={locked ? inputLocked : common.className}
/>
</div>
) : widget === "linkPreview" ? (
<LinkPreviewInput
id={id}
value={value}
row={row}
locked={locked}
className={locked ? inputLocked : common.className}
showButton={!field.previewWhen || fieldShown({ when: field.previewWhen }, row)}
onChange={onChange}
onPatch={onPatch}
/>
) : widget === "image" ? (
<ImageInput
id={id}
value={value}
resolve={field.resolve}
locked={locked}
className={locked ? inputLocked : common.className}
onChange={onChange}
/>
) : field.prefix && !locked ? (
// The span is not a form control, so it can't be typed
// into, tabbed to, or selected by dragging through the
// field. Clicking it focuses the input, which is what
// makes the two read as one box.
<div
className={`${inputShell} ${error ? shellError : ""}`}
onClick={() => document.getElementById(id)?.focus()}
>
<span
aria-hidden="true"
className={`shrink-0 select-none ${
field.prefixPending ? "text-muted/45" : "text-muted"
}`}
>
{field.prefix}
</span>
<input
id={id}
type="text"
value={value ?? ""}
onChange={(e) => onChange(e.target.value)}
placeholder={field.placeholder}
className="w-full border-0 bg-transparent p-0 text-body outline-none placeholder:text-muted/45"
/>
</div>
) : (
<input
type={
widget === "number" || widget === "date" || widget === "time" ? widget : "text"
}
step={widget === "number" ? "any" : undefined}
{...common}
readOnly={locked}
aria-readonly={locked || undefined}
className={locked ? inputLocked : common.className}
/>
)}
</div>
{error ? (
<p className="mt-1 text-xs text-danger">{error}</p>
) : orphaned && !locked ? (
<p className="mt-1 text-xs text-danger">
This points at something that has been deleted. Pick a replacement before saving.
</p>
) : (
helpText(field, row) &&
widget !== "checkbox" && (
<p className="mt-1 text-xs text-muted">{helpText(field, row)}</p>
)
)}
</div>
);
}
export function FieldGrid({ children }) {
return <div className="grid gap-4 sm:grid-cols-2">{children}</div>;
}
/* ── Repeater ────────────────────────────────────────────────── */
/* Where each old index ends up after a change to the list, or -1
when that row is gone. Used to carry the open set across it. */
function remapOpen(open: Set<number>, where: (index: number) => number) {
const next = new Set<number>();
for (const index of open) {
const moved = where(index);
if (moved >= 0) next.add(moved);
}
return next;
}
export function Repeater({
spec,
rows,
options,
errors,
errorPrefix,
onChange,
className = "mt-8",
parentRow = undefined,
}: any) {
const list = rows ?? [];
const [open, setOpen] = useState<Set<number>>(() => new Set());
const hasError = (index) =>
Object.keys(errors ?? {}).some(
(key) => errors[key] && key.startsWith(`${errorPrefix}${index}.`),
);
const isOpen = (index) => open.has(index) || hasError(index);
const toggle = (index) =>
setOpen((prev) => {
const next = new Set(prev);
if (next.has(index)) next.delete(index);
else next.add(index);
return next;
});
// Which row is in flight, and which one it's currently over.
// Both are per-Repeater, which is what keeps a drag inside a
// nested collection from being accepted by the outer one.
const [dragIndex, setDragIndex] = useState<any>(null);
const [overIndex, setOverIndex] = useState<any>(null);
const rowRefs = useRef<any[]>([]);
const update = (index, next) =>
onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec, next, parentRow) : row)));
const move = (index, delta) => {
const target = index + delta;
if (target < 0 || target >= list.length) return;
const next = [...list];
[next[index], next[target]] = [next[target], next[index]];
setOpen((prev) =>
remapOpen(prev, (i) => (i === index ? target : i === target ? index : i)),
);
onChange(next);
};
const relocate = (from, to) => {
if (from === to || from == null || to == null) return;
const next = [...list];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved);
setOpen((prev) =>
remapOpen(prev, (i) => {
if (i === from) return to;
if (from < to && i > from && i <= to) return i - 1;
if (from > to && i >= to && i < from) return i + 1;
return i;
}),
);
onChange(next);
};
const add = () => {
setOpen((prev) => new Set(prev).add(list.length));
onChange([...list, { ...spec.blank }]);
};
/* A row placed at `at`, pushing everything from there down one,
and opened so it can be filled in straight away. */
const insertAt = (at, row) => {
setOpen((prev) => remapOpen(prev, (i) => (i >= at ? i + 1 : i)).add(at));
onChange([...list.slice(0, at), row, ...list.slice(at)]);
};
const removeAt = (index) => {
setOpen((prev) => remapOpen(prev, (i) => (i === index ? -1 : i > index ? i - 1 : i)));
onChange(list.filter((_, i) => i !== index));
};
const endDrag = () => {
setDragIndex(null);
setOverIndex(null);
};
return (
<section className={className}>
<div className="flex flex-wrap items-center gap-3">
<h3 className="text-base font-semibold text-body">
{spec.label}
{list.length > 0 && (
<span className="ml-2 text-sm font-normal text-muted/80">{list.length}</span>
)}
</h3>
{list.length > 1 && (
<div className="flex gap-3 text-xs text-muted">
<button
type="button"
onClick={() => setOpen(new Set(list.map((_, i) => i)))}
className="hover:text-link hover:underline"
>
Expand all
</button>
<button
type="button"
onClick={() => setOpen(new Set())}
className="hover:text-link hover:underline"
>
Collapse all
</button>
</div>
)}
<button
type="button"
onClick={add}
className="ml-auto rounded-full border border-brand px-3 py-1 text-sm font-medium text-link transition-colors hover:bg-tint"
>
{spec.addLabel ?? "Add"}
</button>
</div>
{spec.note && <p className="mt-1 text-sm text-muted">{spec.note}</p>}
{list.length === 0 && <p className="mt-2 text-sm text-muted">None yet.</p>}
<div className="mt-3 space-y-3">
{list.map((row, index) => {
const dragging = dragIndex === index;
const over = overIndex === index && dragIndex !== null && !dragging;
const expanded = isOpen(index);
return (
<div
key={index}
ref={(el) => {
rowRefs.current[index] = el;
}}
onDragOver={(e) => {
// A null dragIndex means the drag started in some
// other collection; leave it to whoever owns it.
if (dragIndex === null) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = "move";
if (overIndex !== index) setOverIndex(index);
}}
onDrop={(e) => {
if (dragIndex === null) return;
e.preventDefault();
e.stopPropagation();
relocate(dragIndex, index);
endDrag();
}}
className={
`rounded-xl border bg-tint-soft ${expanded ? "p-4" : "px-4 py-2.5"} transition-colors ` +
(over
? "border-brand ring-2 ring-brand/25 "
: "border-muted/20 ") +
(dragging ? "opacity-50" : "")
}
>
<div className={`flex items-center gap-2 ${expanded ? "mb-3" : ""}`}>
<span
draggable
onDragStart={(e) => {
e.stopPropagation();
setDragIndex(index);
e.dataTransfer.effectAllowed = "move";
// Firefox won't start a drag without payload.
e.dataTransfer.setData("text/plain", String(index));
// Drag the whole row, not just the handle.
const el = rowRefs.current[index];
if (el) e.dataTransfer.setDragImage(el, 16, 16);
}}
onDragEnd={endDrag}
title="Drag to reorder"
aria-hidden="true"
className="cursor-grab select-none px-1 text-muted/60 active:cursor-grabbing"
>
⠿
</span>
<button
type="button"
onClick={() => toggle(index)}
aria-expanded={expanded}
className="flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-medium text-body hover:text-link"
>
<span
aria-hidden="true"
className={`inline-block text-xs text-muted transition-transform ${
expanded ? "rotate-90" : ""
}`}
>
<CaretRight size={14} weight="bold" aria-hidden="true" />
</span>
<span className="truncate">
{spec.title ? spec.title(row, options) : `#${index + 1}`}
</span>
{!expanded && hasError(index) && (
<span className="text-xs text-danger">needs attention</span>
)}
</button>
<div className="ml-auto flex shrink-0 gap-1">
<IconButton
label="Move up"
onClick={() => move(index, -1)}
disabled={index === 0}
>
<ArrowUp size={14} weight="bold" aria-hidden="true" />
</IconButton>
<IconButton
label="Move down"
onClick={() => move(index, 1)}
disabled={index === list.length - 1}
>
<ArrowDown size={14} weight="bold" aria-hidden="true" />
</IconButton>
<IconButton
label="Insert a new one below"
onClick={() => insertAt(index + 1, { ...spec.blank })}
>
+
</IconButton>
<IconButton
label="Duplicate"
onClick={() => insertAt(index + 1, withoutIds(row))}
>
⧉
</IconButton>
<IconButton
label="Remove"
danger
onClick={() => removeAt(index)}
>
✕
</IconButton>
</div>
</div>
{expanded && (
<>
<FieldGrid>
{spec.fields
.filter((field) => fieldShown(field, row, parentRow))
.map((field) => (
<Field
key={field.path}
field={field}
row={row}
value={row[field.path]}
options={options}
error={errors?.[`${errorPrefix}${index}.${field.path}`]}
onChange={(value) => update(index, { ...row, [field.path]: value })}
onPatch={(patch) => update(index, { ...row, ...patch })}
/>
))}
</FieldGrid>
{(spec.children ?? [])
.filter((nested) => fieldShown(nested, row, parentRow))
.map((nested) => (
<div key={nested.key} className="mt-4 border-t border-muted/15 pt-4">
<Repeater
spec={nested}
rows={row[nested.key]}
options={options}
errors={errors}
errorPrefix={`${errorPrefix}${index}.${nested.key}.`}
parentRow={row}
className=""
onChange={(value) => update(index, { ...row, [nested.key]: value })}
/>
</div>
))}
{spec.preview && PREVIEWS[spec.preview] && (
<div className="mt-4 rounded-lg border border-dashed border-brand/30 bg-surface p-4">
<p className="mb-3 text-xs font-semibold uppercase tracking-wider text-muted/70">
Preview
</p>
{PREVIEWS[spec.preview](row, options)}
</div>
)}
</>
)}
</div>
);
})}
</div>
</section>
);
}
function IconButton({ label, onClick, danger = false, disabled = false, children }) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={label}
title={label}
className={
"h-7 w-7 rounded-full border text-sm leading-none transition-colors " +
(disabled
? "cursor-default border-muted/20 text-muted/40"
: danger
? "border-danger/30 text-danger hover:bg-danger-tint"
: "border-muted/30 text-muted hover:bg-surface")
}
>
{children}
</button>
);
}