NGU-Web/src/pages/sections/RequestForm.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

394 lines
16 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
REQUEST FORM
Posts to /api/requests (server/src/routes/requests.js), as a form
so files can go with it. What can be asked for is REQUEST_TYPES;
?type=group in the address picks one to start with, which is how
the site's "Request" buttons open it.
Each type's details (its `fields` in requestTypes.ts: a group's
city and meeting time, an event's dates) go as one JSON field; the
admin opens the record's editor filled in from them.
Files go to Google Drive on the server; when Drive isn't set up
(REQUEST_FILES) the file field isn't shown. The limits here match
the server's, so nobody waits on an upload that will be refused.
═══════════════════════════════════════════════════════════════ */
import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import { ApiError, upload } from "../../lib/api.ts";
import { accentText, BRAND } from "../../lib/color.ts";
import { REQUEST_FILES } from "../../lib/site.ts";
import { REQUEST_TYPES, type RequestAction } from "../../data/requestTypes.ts";
import { FieldError, MinimumNote, OptionalTag, RequiredTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx";
const MUTED = "var(--color-muted)";
const MAX_CHARS = 5000;
const MIN_MESSAGE = 10; // matches the server
const MAX_FILES = 3;
const MAX_FILE_MB = 10;
const ACCEPT = ".docx,.pdf,.jpg,.jpeg,.png";
const ACTION_LABEL: Record<RequestAction, string> = {
new: "Something new",
update: "An update to what's there",
};
const PLACEHOLDER: Record<string, string> = {
blog: "A few lines about the post: what it's about, and anything we should know. Attach the post as a Word document.",
event: "When and where, who it's for, how to register, and who to contact.",
};
export default function RequestForm() {
const [params] = useSearchParams();
const start = REQUEST_TYPES.find((t) => t.id === params.get("type")) ?? null;
const [category, setCategory] = useState<string | null>(start?.id ?? null);
const [action, setAction] = useState<RequestAction | null>(start?.actions.length === 1 ? start.actions[0] : null);
const [subject, setSubject] = useState("");
const [message, setMessage] = useState("");
const [files, setFiles] = useState<File[]>([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
// By field key; kept when the type changes, since types share keys.
const [details, setDetails] = useState<Record<string, string>>({});
const [website, setWebsite] = useState(""); // honeypot
const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle");
const [formError, setFormError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const type = REQUEST_TYPES.find((t) => t.id === category);
const sending = status === "sending";
const fileError =
files.length > MAX_FILES
? `${MAX_FILES} files at most.`
: files.find((f) => f.size > MAX_FILE_MB * 1024 * 1024)
? `Files can be ${MAX_FILE_MB} MB each at most.`
: null;
const ready =
Boolean(type && action) &&
subject.trim() !== "" &&
message.trim().length >= MIN_MESSAGE &&
email.trim() !== "" &&
!fileError;
function pick(id: string) {
const next = REQUEST_TYPES.find((t) => t.id === id);
setCategory(id);
// One choice picks itself; otherwise keep what was chosen if it still applies.
setAction((prev) => (next?.actions.length === 1 ? next.actions[0] : prev && next?.actions.includes(prev) ? prev : null));
}
async function handleSubmit(event) {
event.preventDefault();
if (!ready || sending || !category || !action) return;
setStatus("sending");
setFormError(null);
setFieldErrors({});
const form = new FormData();
form.set("category", category);
form.set("action", action);
form.set("subject", subject.trim());
form.set("message", message.trim());
form.set("name", name.trim());
form.set("email", email.trim());
// Only the chosen type's fields, and only filled ones.
form.set(
"details",
JSON.stringify(
Object.fromEntries(
(type?.fields ?? []).map((f) => [f.key, (details[f.key] ?? "").trim()]).filter(([, value]) => value),
),
),
);
form.set("website", website);
for (const file of files) form.append("files", file);
try {
await upload("/requests", form);
setStatus("sent");
} catch (error) {
setStatus("idle");
if (error instanceof ApiError) {
setFieldErrors(error.fields ?? {});
setFormError(error.fields ? "Have another look at the highlighted fields." : error.message);
} else {
setFormError("Couldn't reach the server. Try again in a moment.");
}
}
}
function reset() {
setSubject("");
setDetails({});
setMessage("");
setFiles([]);
setStatus("idle");
setFormError(null);
setFieldErrors({});
}
if (status === "sent") {
return (
<div aria-live="polite" className="border border-brand/20 bg-surface p-8 sm:p-10">
<h3 className="text-2xl font-bold" style={{ color: accentText(BRAND) }}>
Thanks, we've got it
</h3>
<p className="mt-3 max-w-prose" style={{ color: MUTED }}>
We'll look it over and follow up at {email}, usually within a week.
</p>
<button
type="button"
onClick={reset}
className="mt-6 btn border border-brand px-5 py-2.5 text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40"
>
Send another request
</button>
</div>
);
}
return (
<form onSubmit={handleSubmit} noValidate className="border border-brand/20 bg-surface p-6 sm:p-8">
<TilePicker
legend="What is this about?"
blurb="Pick the closest fit."
name="category"
options={REQUEST_TYPES}
value={category}
onChange={pick}
/>
<FieldError id="request-category-error">{fieldErrors.category}</FieldError>
{type && type.actions.length > 1 && (
<fieldset className="mt-8">
<legend className="text-base font-semibold text-body">New, or an update?</legend>
<div className="mt-3 flex flex-wrap gap-3">
{type.actions.map((a) => (
<label key={a} className="cursor-pointer">
<input
type="radio"
name="action"
value={a}
checked={action === a}
onChange={() => setAction(a)}
className="peer sr-only"
/>
<span
className={
"inline-block btn border px-5 py-2 text-sm transition-colors " +
"peer-focus-visible:ring-2 peer-focus-visible:ring-brand/40 " +
(action === a ? "border-brand bg-tint text-link" : "border-muted/30 text-body hover:border-brand/50")
}
>
{ACTION_LABEL[a]}
</span>
</label>
))}
</div>
<FieldError id="request-action-error">{fieldErrors.action}</FieldError>
</fieldset>
)}
{type?.id === "region" && (
<p className="mt-4 text-sm" style={{ color: MUTED }}>
Regions are set by Unity, so this is for updating one that's on the site.
</p>
)}
{type && (
<>
<div className="mt-8">
<label htmlFor="request-subject" className="text-base font-semibold text-body">
{action === "update" && type.actions.length > 1 ? `Which ${type.label.toLowerCase()}?` : type.subject}
<RequiredTag />
</label>
<input
id="request-subject"
type="text"
maxLength={200}
value={subject}
onChange={(e) => setSubject(e.target.value)}
aria-invalid={Boolean(fieldErrors.subject)}
aria-describedby={fieldErrors.subject ? "request-subject-error" : undefined}
className={`mt-3 ${fieldClass} ${fieldErrors.subject ? errorFieldClass : ""}`}
/>
<FieldError id="request-subject-error">{fieldErrors.subject}</FieldError>
</div>
{type.fields.length > 0 && (
<fieldset className="mt-8">
<legend className="flex flex-wrap items-center text-base font-semibold text-body">
Details
<OptionalTag />
</legend>
<p className="mt-1 text-sm" style={{ color: MUTED }}>
{action === "update"
? "Only what should change; leave the rest blank."
: "Whatever you know. Blanks are fine, and the rest can go in the message or a document."}
</p>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{type.fields.map((f) => {
const id = `request-detail-${f.key}`;
const common = {
id,
value: details[f.key] ?? "",
placeholder: f.placeholder,
maxLength: 2000,
className: fieldClass,
};
const set = (value: string) => setDetails((prev) => ({ ...prev, [f.key]: value }));
return (
<div key={f.key} className={f.input === "textarea" ? "sm:col-span-2" : ""}>
<label htmlFor={id} className="block text-sm font-medium text-body">
{f.label}
</label>
{f.input === "textarea" ? (
<textarea {...common} rows={3} onChange={(e) => set(e.target.value)} className={`mt-2 resize-y ${fieldClass}`} />
) : (
<input {...common} type={f.input ?? "text"} onChange={(e) => set(e.target.value)} className={`mt-2 ${fieldClass}`} />
)}
</div>
);
})}
</div>
</fieldset>
)}
<div className="mt-8">
<label htmlFor="request-message" className="text-base font-semibold text-body">
{action === "update" ? "What should change?" : "Tell us about it"}
<RequiredTag />
</label>
<textarea
id="request-message"
rows={7}
maxLength={MAX_CHARS}
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder={
action === "update"
? "What's there now, and what it should say instead."
: (PLACEHOLDER[type.id] ?? "Everything we'd need to add it: a description, links, and who to contact.")
}
aria-invalid={Boolean(fieldErrors.message)}
aria-describedby={fieldErrors.message ? "request-message-error" : undefined}
className={`mt-3 resize-y ${fieldClass} ${fieldErrors.message ? errorFieldClass : ""}`}
/>
<div className="mt-2 flex items-start justify-between gap-4">
<FieldError id="request-message-error">{fieldErrors.message}</FieldError>
{!fieldErrors.message && <MinimumNote length={message.trim().length} min={MIN_MESSAGE} />}
<span className="ml-auto shrink-0 text-xs tabular-nums" style={{ color: MUTED }}>
{message.length} / {MAX_CHARS}
</span>
</div>
</div>
{REQUEST_FILES && (
<div className="mt-8">
<div className="flex flex-wrap items-center">
<label htmlFor="request-files" className="text-base font-semibold text-body">
Files
</label>
<OptionalTag />
</div>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
A Word document (.docx) with the details or the post itself, photos (JPEG or PNG) or a PDF. Up to{" "}
{MAX_FILES}, {MAX_FILE_MB} MB each.
</p>
<input
id="request-files"
type="file"
multiple
accept={ACCEPT}
onChange={(e) => setFiles(Array.from(e.target.files ?? []))}
aria-invalid={Boolean(fileError || fieldErrors.files)}
aria-describedby={fileError || fieldErrors.files ? "request-files-error" : undefined}
className="mt-3 block w-full text-sm text-body file:mr-4 file:border-0 file:bg-tint file:px-4 file:py-2 file:font-semibold file:text-link hover:file:bg-tint-soft"
/>
<FieldError id="request-files-error">{fileError ?? fieldErrors.files}</FieldError>
</div>
)}
</>
)}
<div className="mt-8 border border-dashed border-muted/30 bg-tint/60 p-5 sm:p-6">
<h3 className="text-base font-semibold text-body">How we reach you</h3>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
We use these only to follow up on this request, and we won't add you to any list.
</p>
<div className="mt-5 grid gap-4 sm:grid-cols-2">
<div>
<label htmlFor="request-name" className="block text-sm font-medium text-body">
Name <span className="font-normal text-muted">(optional)</span>
</label>
<input
id="request-name"
type="text"
autoComplete="name"
value={name}
onChange={(e) => setName(e.target.value)}
className={`mt-2 ${fieldClass}`}
/>
</div>
<div>
<label htmlFor="request-email" className="block text-sm font-medium text-body">
Email <span className="font-normal text-muted">(required)</span>
</label>
<input
id="request-email"
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? "request-email-error" : undefined}
className={`mt-2 ${fieldClass} ${fieldErrors.email ? errorFieldClass : ""}`}
/>
<FieldError id="request-email-error">{fieldErrors.email}</FieldError>
</div>
</div>
</div>
{/* Honeypot, as on the feedback form. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<label htmlFor="request-website">Website</label>
<input
id="request-website"
type="text"
tabIndex={-1}
autoComplete="off"
value={website}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
{formError && (
<p role="alert" className="mt-8 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
{formError}
</p>
)}
<div className="mt-6 flex flex-wrap items-center gap-4">
<button
type="submit"
disabled={!ready || sending}
className="btn bg-action px-7 py-3 text-white transition-colors hover:bg-action-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:bg-muted/25 disabled:text-white/80"
>
{sending ? (files.length ? "Uploading…" : "Sending…") : "Send request"}
</button>
{!ready && !sending && (
<p className="text-sm" style={{ color: MUTED }}>
Choose what it's about, give it a name, write at least {MIN_MESSAGE} characters and give an email address to send.
</p>
)}
</div>
</form>
);
}