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

530 lines
18 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
WEBSITE FEEDBACK FORM
Posts to /api/feedback, which is the only public write on the
site. The server is the authority on validation; the checks here
exist to stop someone hitting a 422 they could have avoided, and
the two sets are kept deliberately in step (MIN_MESSAGE, and the
ids in FEEDBACK_TYPES).
The page and section options come from navConfig, so adding a
page to the nav adds it to this form too.
With fixedType the type is set and neither picker shows. The
Privacy page uses it for data requests (DATA_REQUEST), which also
need an email, since the answer has to go somewhere.
═══════════════════════════════════════════════════════════════ */
import { CaretDown } from '@phosphor-icons/react';
import { useState } from "react";
import { post, ApiError } from "../../lib/api.ts";
import { PAGE_LINKS } from "../../navConfig.ts";
import { useNavSections, type NavSection } from "../../lib/navSections.ts";
import { DATA_REQUEST, FEEDBACK_TYPES } from "../../data/feedbackTypes.ts";
import { accentText, BRAND } from '../../lib/color.ts'
import { focusOnMount } from '../../lib/focus.ts'
const MUTED = "var(--color-muted)";
const MAX_CHARS = 1500;
const MIN_MESSAGE = 10; // matches the server
// Sentinel for "this isn't about one particular page".
const SITE_WIDE = "site";
// Sentinel for "this page, but not one section of it".
const WHOLE_PAGE = "";
/* ── Shared field chrome ─────────────────────────────────────── */
export const fieldClass =
"w-full border border-muted/50 bg-surface px-4 py-3 text-body "+
"placeholder:text-muted outline-none transition-colors " +
"focus:border-brand focus:ring-2 focus:ring-brand/25";
export const errorFieldClass = "border-danger focus:border-danger focus:ring-danger/20";
const selectClass = `${fieldClass} appearance-none pr-10`;
export function OptionalTag() {
return (
<span className="ml-2 bg-tint px-2 py-0.5 text-xs font-medium text-link">
Optional
</span>
);
}
/* On a field the send button waits for. */
export function RequiredTag() {
return (
<span className="ml-2 bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">
Required
</span>
);
}
/* Under a message box: how many more characters it needs, until it
has them (the send button stays off until then). */
export function MinimumNote({ length, min }: { length: number; min: number }) {
if (length >= min) return null;
return (
<span className="text-xs" style={{ color: MUTED }}>
{length === 0 ? `At least ${min} characters` : `${min - length} more character${min - length === 1 ? "" : "s"} needed`}
</span>
);
}
export function FieldError({ id, children }) {
if (!children) return null;
return (
<p id={id} className="mt-2 text-sm text-danger">
{children}
</p>
);
}
// Native select plus a chevron, since appearance-none strips the default one.
function Select({ id, label, value, onChange, children }) {
return (
<div>
<label htmlFor={id} className="block text-sm font-medium text-body">
{label}
</label>
<div className="relative mt-2">
<select
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
className={selectClass}
>
{children}
</select>
<CaretDown aria-hidden="true" weight="bold" className="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2" style={{ color: MUTED }} />
</div>
</div>
);
}
/* ── Type picker: a tile per option (the Request form's too) ─── */
export function TilePicker({
legend,
blurb,
name,
options,
value,
onChange,
error,
}: {
legend: string;
blurb: string;
name: string;
options: { id: string; label: string; hint: string }[];
value: string | null;
onChange: (id: string) => void;
/** Shown under the tiles and read with each one. */
error?: string;
}) {
const errorId = `${name}-error`;
return (
<fieldset aria-describedby={error ? errorId : undefined}>
<legend className="text-base font-semibold text-body">{legend}</legend>
<p className="mt-1 text-sm" style={{ color: MUTED }}>
{blurb}
</p>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{options.map((type) => {
const selected = value === type.id;
return (
<label key={type.id} className="cursor-pointer">
<input
type="radio"
name={name}
value={type.id}
checked={selected}
onChange={() => onChange(type.id)}
aria-invalid={Boolean(error)}
aria-describedby={error ? errorId : undefined}
className="peer sr-only"
/>
<span
className={
"flex h-full flex-col gap-1 border p-4 transition-colors "+
"peer-focus-visible:ring-2 peer-focus-visible:ring-brand/40 " +
(selected
? "border-brand bg-tint"
: "border-muted/20 bg-surface hover:border-brand/50")
}
>
<span className="flex items-start justify-between gap-2">
<span className="font-semibold text-body">{type.label}</span>
<span
aria-hidden="true"
className={
"mt-0.5 h-4 w-4 shrink-0 rounded-full border-2 transition-colors " +
(selected
? "border-brand bg-action ring-2 ring-inset ring-white"
: "border-muted/30")
}
/>
</span>
<span className="text-sm leading-snug" style={{ color: MUTED }}>
{type.hint}
</span>
</span>
</label>
);
})}
</div>
<FieldError id={errorId}>{error}</FieldError>
</fieldset>
);
}
/* ── Where on the site ───────────────────────────────────────── */
function LocationPicker({ page, section, onPageChange, onSectionChange }) {
const sectionsOf = useNavSections();
const sections = page === SITE_WIDE ? [] : sectionsOf(page);
return (
<div>
<div className="flex flex-wrap items-center">
<h3 className="text-base font-bold text-body">
Where did you run into it?
</h3>
<OptionalTag />
</div>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
Leave this on "Not page-specific" if it applies to the whole site.
</p>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
<Select
id="feedback-page"
label="Page"
value={page}
onChange={(next) => {
onPageChange(next);
onSectionChange(WHOLE_PAGE); // sections belong to a page
}}
>
<option value={SITE_WIDE}>Not page-specific</option>
{PAGE_LINKS.map((p) => (
<option key={p.path} value={p.path}>
{p.label}
</option>
))}
</Select>
{sections.length > 0 && (
<Select
id="feedback-section"
label="Section of that page"
value={section}
onChange={onSectionChange}
>
<option value={WHOLE_PAGE}>The page as a whole</option>
{sections.map((s) => (
<option key={s.hash} value={s.hash}>
{s.label}
</option>
))}
</Select>
)}
</div>
</div>
);
}
// Human-readable version of the picked location, for the thank-you panel.
function describeLocation(page, section, sectionsOf: (path: string) => NavSection[]) {
if (page === SITE_WIDE) return null;
const pageLabel = PAGE_LINKS.find((p) => p.path === page)?.label ?? page;
const sectionLabel = sectionsOf(page).find(
(s) => s.hash === section,
)?.label;
return sectionLabel ? `${pageLabel} → ${sectionLabel}` : pageLabel;
}
/* ── The form ────────────────────────────────────────────────── */
export default function FeedbackForm({ fixedType }: { fixedType?: string } = {}) {
const sectionsOf = useNavSections();
const request = fixedType === DATA_REQUEST.id;
const [type, setType] = useState<any>(fixedType ?? null);
const [page, setPage] = useState(SITE_WIDE);
const [section, setSection] = useState(WHOLE_PAGE);
const [message, setMessage] = useState("");
const [name, setName] = useState("");
const [email, setEmail] = useState("");
// Honeypot: never shown, never filled by a person.
const [website, setWebsite] = useState("");
// idle → sending → sent, or back to idle with an error to show.
const [status, setStatus] = useState("idle");
const [formError, setFormError] = useState<any>(null);
const [fieldErrors, setFieldErrors] = useState<any>({});
const sending = status === "sending";
const ready =
Boolean(type) && message.trim().length >= MIN_MESSAGE && (!request || email.trim() !== "");
async function handleSubmit(event) {
event.preventDefault();
if (!ready || sending) return;
setStatus("sending");
setFormError(null);
setFieldErrors({});
try {
await post("/feedback", {
feedbackType: type,
message: message.trim(),
name: name.trim(),
email: email.trim(),
pagePath: page === SITE_WIDE ? "" : page,
sectionId: section, // server strips the leading '#'
website,
});
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 {
// Network failure, offline, server down.
setFormError("Couldn't reach the server. Try again in a moment.");
}
}
}
function reset() {
setType(fixedType ?? null);
setPage(SITE_WIDE);
setSection(WHOLE_PAGE);
setMessage("");
setName("");
setEmail("");
setWebsite("");
setStatus("idle");
setFormError(null);
setFieldErrors({});
}
if (status === "sent") {
const where = describeLocation(page, section, sectionsOf);
return (
<div
aria-live="polite"
className="border border-brand/20 bg-surface p-8 sm:p-10"
>
<h3
ref={focusOnMount}
tabIndex={-1}
className="text-2xl font-bold outline-none"
style={{ color: accentText(BRAND) }}
>
Thanks, we've got it
</h3>
{where && (
<p className="mt-3 text-sm" style={{ color: MUTED }}>
Filed against {where}.
</p>
)}
<p className="mt-3 max-w-prose" style={{ color: MUTED }}>
{request
? `We'll reply to ${email}. We may ask you to confirm it's you before we change or delete anything.`
: email
? `We'll follow up at ${email} if we have questions.`
: "You sent this anonymously, so we won't be able to reply, but we read everything that comes in."}
</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"
>
{request ? "Send another request" : "Send more feedback"}
</button>
</div>
);
}
return (
<form
onSubmit={handleSubmit}
noValidate
className="border border-brand/20 bg-surface p-6 sm:p-8"
>
{!fixedType && (
<>
<TilePicker
legend="What kind of feedback is this?"
blurb="Pick the closest fit. It helps us route it to the right person."
name="feedbackType"
options={FEEDBACK_TYPES}
value={type}
onChange={setType}
/>
<div className="mt-10">
<LocationPicker
page={page}
section={section}
onPageChange={setPage}
onSectionChange={setSection}
/>
</div>
</>
)}
{/* Message */}
<div className={fixedType ? "" : "mt-10"}>
<label
htmlFor="feedback-message"
className="text-base font-semibold text-body"
>
{request ? "Your request" : "Tell us more"}
<RequiredTag />
</label>
<p className="mt-1 text-sm" style={{ color: MUTED }}>
{request
? "Say what you'd like: to see the information we hold about you, to correct it, or to have it deleted. Tell us how you've been in touch with NGU (a retreat, a group, this site) so we can find it."
: "What you expected to happen, and what happened instead, is the most useful thing you can give us."}
</p>
<textarea
id="feedback-message"
rows={7}
maxLength={MAX_CHARS}
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder={
request
? "Please delete the details I gave when I registered for…"
: "I was looking for the summer retreat dates and…"
}
aria-invalid={Boolean(fieldErrors.message)}
aria-describedby={fieldErrors.message ? "feedback-message-error" : undefined}
className={`mt-4 resize-y ${fieldClass} ${
fieldErrors.message ? errorFieldClass : ""
}`}
/>
<div className="mt-2 flex items-start justify-between gap-4">
<FieldError id="feedback-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>
{/* Optional contact details */}
<div className="notice mt-8 p-5 sm:p-6">
<div className="flex flex-wrap items-center">
<h3 className="text-base font-bold text-body">
{request ? "How we reach you" : "Your details"}
</h3>
{!request && <OptionalTag />}
</div>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
{request
? "We use these only to answer this request, and we won't add you to any list."
: "Leave these blank and your feedback comes through anonymously. Fill them in only if you'd like a reply, we won't add you to any list."}
</p>
<div className="mt-5 grid gap-4 sm:grid-cols-2">
<div>
<label
htmlFor="feedback-name"
className="block text-sm font-medium text-body"
>
Name <span className="font-normal text-muted">(optional)</span>
</label>
<input
id="feedback-name"
type="text"
autoComplete="name"
value={name}
onChange={(e) => setName(e.target.value)}
className={`mt-2 ${fieldClass}`}
/>
</div>
<div>
<label
htmlFor="feedback-email"
className="block text-sm font-medium text-body"
>
Email{" "}
<span className="font-normal text-muted">{request ? "(required)" : "(optional)"}</span>
</label>
<input
id="feedback-email"
type="email"
autoComplete="email"
required={request}
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? "feedback-email-error" : undefined}
className={`mt-2 ${fieldClass} ${
fieldErrors.email ? errorFieldClass : ""
}`}
/>
<FieldError id="feedback-email-error">{fieldErrors.email}</FieldError>
</div>
</div>
</div>
{/* Honeypot. Off-screen rather than display:none, since bots
skip hidden inputs. Never announced, never tabbable. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<label htmlFor="feedback-website">Website</label>
<input
id="feedback-website"
type="text"
tabIndex={-1}
autoComplete="off"
value={website}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
{/* Submit */}
{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 ? "Sending…" : request ? "Send request" : "Send feedback"}
</button>
{!ready && !sending && (
<p className="text-sm" style={{ color: MUTED }}>
{request
? `Write at least ${MIN_MESSAGE} characters and give an email address to send.`
: `Choose a type and write at least ${MIN_MESSAGE} characters to send.`}
</p>
)}
</div>
</form>
);
}