NGU-Web/src/components/admin/fields.tsx
Zaldimmar e060153798 Newsletter: Pick a redirect on every link field
Link fields with redirects: true get a list of Data > Links/redirects that fills in the short link's full address; the newsletter turns it on for its blocks' links and their items' links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:39:52 -05:00

869 lines
34 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`.
`files: true` on a link field adds "Choose a file" (FilePicker in
DriveFiles.tsx): the field takes the file's Drive link, and with
`previewFills` (a link card) the row's empty title and picture take
the file's name and first-page preview. `filesWhen` limits it to
rows that match, as `when` does for the field.
`redirects: true` on a link field adds "Pick a redirect": a list of
Data → Links/redirects (the `redirects` options) that fills the
field with the short link's full address, <site>/go/<URL ID>.
`widget: "testNotice"` is a text box of email addresses with a
"Send a test notice" button (TestNoticeInput below), for Site
settings → Notices.
`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. Its
`folder` ("logos" for logo and icon fields) is where uploads go and
the tab the library opens on. `frameFrom` names the row's video
link field and adds "Frame at" (a still at a typed time, saved to
thumbnails/); `frameWhen` limits it to rows that match.
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, Copy, Plus, X } from "@phosphor-icons/react";
import { useMemo, useRef, useState } from "react";
import { ApiError, post } from "../../lib/api.ts";
import ContentBlocks from "../ContentBlocks.tsx";
import { FILTER_FROM, OptionFilter, narrow } from "../OptionFilter.tsx";
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
import { ChooseFileButton } from "./DriveFiles.tsx";
import { siteUrl } from "../../lib/site.ts";
/* 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 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 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 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 color 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 || "#00748a";
}
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 ──────────────────────────────────────── */
/* `when: { path, value }` shows a field when the other field holds
that value (or one of a list); `when: { path, filled: true }` when
it holds anything at all. */
export function fieldShown(field, row, parent?) {
if (!field.when) return true;
const source = field.when.scope === "parent" ? parent : row;
if (field.when.filled) return Boolean(source?.[field.when.path]);
const want = Array.isArray(field.when.value) ? field.when.value : [field.when.value];
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;
// Two fields can share a path, each shown for a different kind of
// row (a card's Description and a list item's Detail are both
// `detail`); a value is only hidden when none of them is showing.
const shownPaths = new Set(spec.fields.filter((f) => fieldShown(f, row, parent)).map((f) => f.path));
for (const field of spec.fields) {
const value = next[field.path];
if (!shownPaths.has(field.path) && 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);
// The select's options, rebuilt only when their source changes
// (or, with filterBy, the row they're filtered by), not on every
// keystroke elsewhere in the form.
const source = field.optionsFrom ? options?.[field.optionsFrom] : field.options;
const filterRow = field.filterBy ? row : null;
const list: any[] | null = useMemo<any[] | null>(() => {
if (widget !== "select") return null;
let all = field.optionsFrom
? (source ?? []).map((o) => [o.id, o.label, o])
: (source ?? []).map((o) => (Array.isArray(o) ? [o[0], o[1]] : [o, o]));
if (field.filterBy && filterRow) {
all = all.filter(([, , raw]) => !raw || field.filterBy(raw, filterRow));
}
return all;
}, [widget, field, source, filterRow]);
// Past FILTER_FROM options, a box above the select narrows them.
const [needle, setNeedle] = useState("");
const shown: any[] = list ? narrow<any>(list, needle, ([, label]) => label, ([optionId]) => String(optionId) === String(value)) : [];
// 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.
const orphaned =
list != null &&
value != null &&
value !== "" &&
!list.some(([optionId]) => String(optionId) === String(value));
// A file from the Drive library into this link field (`files`).
const pickFile = (file) => {
const fills = field.previewFills;
const patch = { [field.path]: file.url };
if (fills && !row?.[fills.title]) patch[fills.title] = file.title;
if (fills && !row?.[fills.image] && file.preview) patch[fills.image] = file.preview;
if (onPatch && !field.path.includes(".")) onPatch(patch);
else onChange(file.url);
};
const showFiles = field.files && !locked && (!field.filesWhen || fieldShown({ when: field.filesWhen }, row));
// The line under the field (its error, the deleted-row warning, or
// its help) is read with it, and the field says when it's required
// or wrong, not only the red star and border.
const noteId = `${id}-note`;
const hasNote = Boolean(error || (orphaned && !locked) || (helpText(field, row) && widget !== "checkbox"));
const described = {
"aria-describedby": hasNote ? noteId : undefined,
"aria-invalid": Boolean(error || (orphaned && !locked)) || undefined,
"aria-required": (field.required && !locked) || undefined,
};
const common = {
id,
className: `${input} ${error ? inputError : ""}`,
value: value ?? "",
onChange: (e) => onChange(e.target.value),
...described,
};
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 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.
<>
{(list?.length ?? 0) > FILTER_FROM && !locked && (
<OptionFilter
value={needle}
onChange={setNeedle}
label={`Narrow the ${typeof field.label === "function" ? field.label(row) : field.label} list`}
/>
)}
<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>}
{shown.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)}
aria-label={`${typeof field.label === "function" ? field.label(row) : field.label}: pick a color`}
className="h-9 w-12 shrink-0 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)}
fills={field.previewFills}
onChange={onChange}
onPatch={onPatch}
/>
) : widget === "testNotice" ? (
<TestNoticeInput
id={id}
value={value}
locked={locked}
className={locked ? inputLocked : common.className}
onChange={onChange}
/>
) : widget === "image" ? (
<ImageInput
id={id}
value={value}
resolve={field.resolve}
folder={field.folder}
videoUrl={field.frameFrom && fieldShown({ when: field.frameWhen }, row) ? getPath(row, field.frameFrom) : null}
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}
{...described}
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}
/>
)}
{showFiles && (
<div className="mt-2">
<ChooseFileButton value={value} onPick={pickFile} />
</div>
)}
{field.redirects && !locked && options?.redirects?.length > 0 && (
<select
value=""
onChange={(e) => e.target.value && onChange(siteUrl(`/go/${e.target.value}`))}
aria-label={`${typeof field.label === "function" ? field.label(row) : field.label}: pick a redirect`}
className={`mt-2 ${common.className}`}
>
<option value="">Pick a redirect (Data → Links/redirects)</option>
{options.redirects.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
)}
</div>
{error ? (
<p id={noteId} className="mt-1 text-xs text-danger">{error}</p>
) : orphaned && !locked ? (
<p id={noteId} 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 id={noteId} 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-bold 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 btn border border-brand px-3 py-1 text-sm 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={
`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 })}
>
<Plus size={14} weight="bold" aria-hidden="true" />
</IconButton>
<IconButton
label="Duplicate"
onClick={() => insertAt(index + 1, withoutIds(row))}
>
<Copy size={14} weight="bold" aria-hidden="true" />
</IconButton>
<IconButton
label="Remove"
danger
onClick={() => removeAt(index)}
>
<X size={14} weight="bold" aria-hidden="true" />
</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="notice mt-4 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={
"flex h-7 w-7 items-center justify-center btn 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>
);
}
/* Addresses, and a button that emails them a test notice now (the
box as typed, saved or not), showing what Google said. */
function TestNoticeInput({
id,
value,
locked,
className,
onChange,
}: {
id: string;
value: string | null | undefined;
locked: boolean;
className: string;
onChange: (value: string) => void;
}) {
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
async function send() {
setBusy(true);
setNote(null);
try {
const { sent, from } = await post("/admin/panel/test-notice", { to: value });
setNote({ tone: "ok", text: `Sent from ${from} to ${sent.join(", ")}. Check the inbox (and spam).` });
} catch (err) {
setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
} finally {
setBusy(false);
}
}
return (
<div className="space-y-2">
<input
id={id}
type="text"
value={value ?? ""}
readOnly={locked}
onChange={(e) => onChange(e.target.value)}
className={className}
/>
{!locked && (
<div className="flex flex-wrap items-center gap-3">
<button
type="button"
disabled={busy || !value?.trim()}
onClick={send}
className="btn border border-brand px-3 py-1 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"
>
{busy ? "Sending…" : "Send a test notice"}
</button>
{note && (
<span role="status" className={`text-xs ${note.tone === "ok" ? "text-link" : "text-danger"}`}>
{note.text}
</span>
)}
</div>
)}
</div>
);
}