Searchable event picker and webhook guide (1.50.2)

- EventPicker replaces the plain event dropdowns on staff/supervisor pages and the kiosk:
  upcoming first, past behind "Show past events", search across all, keyboard support.
- Reports events list can be searched ("Select these N").
- Site settings -> Webhooks: "How webhooks work" guide with headers, signature checking
  (Node.js/PHP) and an example of every event type (EVENT_TYPES[].example, shape-tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
2026-10-29 08:23:09 +02:00
co-authored by Claude Opus 5.5
parent b5c1224b76
commit b6c16a7ec4
48 changed files with 828 additions and 332 deletions
@@ -0,0 +1,172 @@
"use client";
import React, { useState } from "react";
import { BookOpen, ChevronDown, ChevronRight, Copy } from "lucide-react";
type EventType = { type: string; label: string; description: string; example?: unknown };
const RETRIES = "1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours";
const VERIFY_NODE = `// Node.js / Express — check the signature before trusting a request.
const crypto = require("crypto");
const SECRET = process.env.CROSSEVENTS_WEBHOOK_SECRET; // whsec_…
app.post("/crossevents-hook", express.raw({ type: "application/json" }), (req, res) => {
const header = req.get("X-CrossEvents-Signature") || ""; // t=1767225600,v1=5f0c…
const { t, v1 } = Object.fromEntries(header.split(",").map(p => p.split("=")));
const body = req.body.toString("utf8"); // the raw body, unparsed
const expected = crypto.createHmac("sha256", SECRET).update(\`\${t}.\${body}\`).digest("hex");
const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300; // within 5 minutes
if (!fresh || !v1 || !crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected))) {
return res.status(400).send("bad signature");
}
const event = JSON.parse(body);
// Deliveries can repeat: skip an event.id you've already handled.
res.sendStatus(200); // answer quickly, then do the slow work
handle(event);
});`;
const VERIFY_PHP = `<?php // PHP — check the signature before trusting a request.
$secret = getenv('CROSSEVENTS_WEBHOOK_SECRET');
$body = file_get_contents('php://input');
parse_str(str_replace(',', '&', $_SERVER['HTTP_X_CROSSEVENTS_SIGNATURE'] ?? ''), $sig);
$expected = hash_hmac('sha256', $sig['t'] . '.' . $body, $secret);
if (abs(time() - (int) $sig['t']) > 300 || !hash_equals($expected, $sig['v1'] ?? '')) {
http_response_code(400); exit('bad signature');
}
$event = json_decode($body, true);
http_response_code(200);`;
function CopyButton({ text, label = "Copy" }: { text: string; label?: string }) {
const [done, setDone] = useState(false);
return (
<button type="button" className="inline-flex items-center gap-1 px-2 py-0.5 rounded border bg-white text-[11px] hover:bg-gray-50"
onClick={() => { navigator.clipboard?.writeText(text).then(() => { setDone(true); setTimeout(() => setDone(false), 1500); }).catch(() => {}); }}>
<Copy className="w-3 h-3" aria-hidden /> {done ? "Copied" : label}
</button>
);
}
function Code({ text }: { text: string }) {
return (
<div className="relative">
<div className="absolute right-2 top-2"><CopyButton text={text} /></div>
<pre className="max-h-80 overflow-auto rounded-lg bg-gray-900 text-gray-100 p-3 pr-20 text-[11px] leading-relaxed">{text}</pre>
</div>
);
}
const H = ({ children }: { children: React.ReactNode }) => <h4 className="text-sm font-semibold text-gray-900 mt-4 mb-1.5">{children}</h4>;
/**
* Site settings → Webhooks → "How webhooks work": what arrives, when, how to check it's from us,
* and an example of every event type, for whoever builds the receiving side.
*/
export function WebhookGuide({ eventTypes, keepDays, defaultOpen = false }: { eventTypes: EventType[]; keepDays: number; defaultOpen?: boolean }) {
const [open, setOpen] = useState(defaultOpen);
const [openType, setOpenType] = useState<string | null>(null);
const [lang, setLang] = useState<"node" | "php">("node");
const envelope = (t: EventType) => JSON.stringify({ id: "evt_3f9c2a1e-6d4b-4c8e-9a51-2b7d0e6f1c34", type: t.type, createdAt: "2026-10-29T08:16:01.512Z", data: t.example ?? {} }, null, 2);
return (
<section className="border rounded-xl bg-white" data-testid="webhook-guide">
<button type="button" aria-expanded={open} onClick={() => setOpen(o => !o)} className="w-full flex items-center gap-2 px-4 py-3 text-left">
{open ? <ChevronDown className="w-4 h-4 text-gray-500" aria-hidden /> : <ChevronRight className="w-4 h-4 text-gray-500" aria-hidden />}
<BookOpen className="w-4 h-4 text-brand-700" aria-hidden />
<span className="font-medium text-gray-900">How webhooks work</span>
<span className="text-xs text-gray-500">what is sent, the signature, and an example of each event</span>
</button>
{open && (
<div className="px-4 pb-4 text-sm text-gray-700 border-t">
<H>What happens</H>
<ol className="list-decimal pl-5 space-y-1">
<li>Something happens here, such as a registration or a payment, that one of your webhooks is set to send.</li>
<li>A second or two later, an <code>HTTP POST</code> with a JSON body goes to that webhook&apos;s address. Everything is sent from the server; nothing comes from people&apos;s browsers.</li>
<li>Your side answers with any <code>2xx</code> status within 10 seconds, and the delivery is done.</li>
<li>
Anything else counts as a failure: another status, no answer, or a redirect (redirects aren&apos;t followed). The delivery is tried again after {RETRIES}, then marked <em>failed</em>.
You can send any delivery again from its <em>Delivery log</em>.
</li>
</ol>
<H>Using it without writing code</H>
<p>
In Zapier, use <strong>Webhooks by Zapier → Catch Hook</strong>; in Make, use <strong>Webhooks → Custom webhook</strong>. Paste the address it gives you here, choose the events, then click <em>Send test</em>. The fields in the examples below become available to map into ChurchSuite, Planning Center, a spreadsheet, Mailchimp and so on.
</p>
<H>What arrives</H>
<p className="mb-2">Every request has the same envelope. <code>data</code> depends on the type (see the examples below).</p>
<div className="overflow-x-auto">
<table className="min-w-full text-xs border rounded">
<thead className="bg-gray-50 text-left"><tr><th className="px-2 py-1.5">Field</th><th className="px-2 py-1.5">Meaning</th></tr></thead>
<tbody className="divide-y">
<tr><td className="px-2 py-1.5"><code>id</code></td><td className="px-2 py-1.5">The event&apos;s id (<code>evt_…</code>). It stays the same on retries, so use it to skip events you&apos;ve already handled.</td></tr>
<tr><td className="px-2 py-1.5"><code>type</code></td><td className="px-2 py-1.5">The event type, e.g. <code>registration.paid</code>. The <em>Send test</em> button sends <code>webhook.test</code>.</td></tr>
<tr><td className="px-2 py-1.5"><code>createdAt</code></td><td className="px-2 py-1.5">When it happened (ISO 8601, UTC).</td></tr>
<tr><td className="px-2 py-1.5"><code>data</code></td><td className="px-2 py-1.5">The details. Amounts are in rand; dates are ISO 8601 in UTC.</td></tr>
</tbody>
</table>
</div>
<p className="mt-3 mb-2">Headers:</p>
<div className="overflow-x-auto">
<table className="min-w-full text-xs border rounded">
<tbody className="divide-y">
<tr><td className="px-2 py-1.5 whitespace-nowrap"><code>Content-Type</code></td><td className="px-2 py-1.5"><code>application/json</code></td></tr>
<tr><td className="px-2 py-1.5 whitespace-nowrap"><code>User-Agent</code></td><td className="px-2 py-1.5"><code>CrossEvents-Webhooks/1</code></td></tr>
<tr><td className="px-2 py-1.5 whitespace-nowrap"><code>X-CrossEvents-Event</code></td><td className="px-2 py-1.5">The event type, the same as <code>type</code>.</td></tr>
<tr><td className="px-2 py-1.5 whitespace-nowrap"><code>X-CrossEvents-Delivery</code></td><td className="px-2 py-1.5">This delivery&apos;s id. Each webhook gets its own, and it&apos;s the same on retries.</td></tr>
<tr><td className="px-2 py-1.5 whitespace-nowrap"><code>X-CrossEvents-Signature</code></td><td className="px-2 py-1.5"><code>t=&lt;unix seconds&gt;,v1=&lt;signature&gt;</code>, explained below.</td></tr>
</tbody>
</table>
</div>
<H>Checking it came from here</H>
<p className="mb-2">
Anyone who knows the address could post to it, so check the signature before acting on a request. <code>v1</code> is the HMAC-SHA256, in hex, of <code>t</code>, a full stop, and the raw request body (<code>&lt;t&gt;.&lt;body&gt;</code>). It&apos;s keyed with the webhook&apos;s signing secret, the <code>whsec_…</code> shown once when you add the webhook or make a new secret.
Work it out on the raw body before parsing the JSON, compare in constant time, and reject a <code>t</code> more than 5 minutes old.
</p>
<div className="flex gap-1 mb-2" role="group" aria-label="Example language">
{(["node", "php"] as const).map(l => (
<button key={l} type="button" aria-pressed={lang === l} onClick={() => setLang(l)}
className={`px-2 py-0.5 rounded text-xs border ${lang === l ? "bg-brand-600 text-white border-brand-600" : "bg-white hover:bg-gray-50"}`}>
{l === "node" ? "Node.js" : "PHP"}
</button>
))}
</div>
<Code text={lang === "node" ? VERIFY_NODE : VERIFY_PHP} />
<H>Good to know</H>
<ul className="list-disc pl-5 space-y-1">
<li>An event can arrive more than once, for example after a retry or a manual resend, so use <code>id</code> to skip ones you&apos;ve already handled.</li>
<li>Events can arrive out of order. Use <code>createdAt</code> and the record&apos;s <code>status</code>, not the order they arrive in.</li>
<li>Each payload is built about a second after the event, from the record as it is then, and retries send that same payload. If a registration is paid and then changed back within that second, nothing is sent.</li>
<li>Kids check-in and volunteer tickets are never sent. A registration made only of those sends nothing, and those lines are left out of <code>items</code>.</li>
<li>Only <code>https</code> addresses on the public internet are allowed. Each webhook&apos;s log keeps what was sent for {keepDays} days.</li>
<li>Turning a webhook off stops new deliveries to it. Deleting it removes its log too.</li>
</ul>
<H>Event types and examples</H>
<ul className="border rounded-lg divide-y">
{eventTypes.map(t => (
<li key={t.type}>
<button type="button" aria-expanded={openType === t.type} onClick={() => setOpenType(openType === t.type ? null : t.type)}
className="w-full flex items-start gap-2 px-3 py-2 text-left hover:bg-gray-50">
{openType === t.type ? <ChevronDown className="w-4 h-4 mt-0.5 text-gray-500 shrink-0" aria-hidden /> : <ChevronRight className="w-4 h-4 mt-0.5 text-gray-500 shrink-0" aria-hidden />}
<span className="flex-1">
<code className="text-xs font-semibold text-gray-900">{t.type}</code> <span className="text-gray-900">· {t.label}</span>
<span className="block text-xs text-gray-500">{t.description}</span>
</span>
</button>
{openType === t.type && <div className="px-3 pb-3" data-testid={`webhook-example-${t.type}`}><Code text={envelope(t)} /></div>}
</li>
))}
<li className="px-3 py-2 text-xs text-gray-600">
<code className="font-semibold text-gray-900">webhook.test</code> · Sent by <em>Send test</em>. <code>data</code> is <code>{`{ "message": "…" }`}</code>, so your side can answer 2xx and ignore it.
</li>
</ul>
</div>
)}
</section>
);
}
@@ -5,8 +5,9 @@ import { Webhook, Send, RefreshCw, KeyRound, Trash2, Pencil, Copy, ChevronDown,
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { WebhookGuide } from "./WebhookGuide";
type EventType = { type: string; label: string; description: string };
type EventType = { type: string; label: string; description: string; example?: unknown };
type Endpoint = {
id: string; name: string; url: string; events: string[]; isActive: boolean;
lastSuccessAt: string | null; lastFailureAt: string | null; createdAt: string;
@@ -188,7 +189,7 @@ export function WebhooksTab({ active }: { active: boolean }) {
const toggleEvent = (type: string) => setDraft(d => d && ({ ...d, events: d.events.includes(type) ? d.events.filter(t => t !== type) : [...d.events, type] }));
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-400">Loading…</p>;
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
const label = (type: string) => data.eventTypes.find(t => t.type === type)?.label || type;
return (
@@ -207,6 +208,8 @@ export function WebhooksTab({ active }: { active: boolean }) {
Webhooks send personal information (names, email addresses, phone numbers) to the service you choose, so each one is added to your operator register. Make sure you have an agreement with that service. What was sent is kept {data.keepDays} days for the delivery log. Children&apos;s details from kids check-in are never sent.
</p>
<WebhookGuide eventTypes={data.eventTypes} keepDays={data.keepDays} defaultOpen={data.endpoints.length === 0} />
{msg && <div className={`p-3 border rounded text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`} role="status">{msg.text}</div>}
{secret && <SecretBox secret={secret.value} onClose={() => setSecret(null)} />}
@@ -1,14 +1,18 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import { ChevronDown } from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { ChevronDown, Search } from "lucide-react";
// The reports sidebar's events multi-select. With many events, the search box narrows the list
// and "Select all" picks only what matches.
export default function EventsDropdown({ options, value, onChange }: {
options: { value: string; label: string }[];
// `hint`: shown beside the title (the date) and searched too.
options: { value: string; label: string; hint?: string }[];
value: string[];
onChange: (v: string[]) => void;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -19,9 +23,23 @@ export default function EventsDropdown({ options, value, onChange }: {
return () => document.removeEventListener("mousedown", onClick);
}, []);
const shown = useMemo(() => {
const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
if (!words.length) return options;
return options.filter(o => {
const hay = `${o.label} ${o.hint || ""}`.toLowerCase();
return words.every(w => hay.includes(w));
});
}, [options, query]);
const toggle = (v: string) => {
onChange(value.includes(v) ? value.filter(x => x !== v) : [...value, v]);
};
const selectShown = () => onChange(Array.from(new Set([...value, ...shown.map(o => o.value)])));
const clearShown = () => {
const drop = new Set(shown.map(o => o.value));
onChange(query.trim() ? value.filter(v => !drop.has(v)) : []);
};
const summary = value.length === 0
? "No events selected"
@@ -35,25 +53,43 @@ export default function EventsDropdown({ options, value, onChange }: {
<div className="relative" ref={ref}>
<button
type="button"
aria-expanded={open}
aria-label={`Events: ${summary}`}
onClick={() => setOpen(o => !o)}
className="w-full flex items-center justify-between gap-2 border rounded-lg px-3 py-2 text-sm bg-white hover:bg-gray-50"
>
<span className="truncate text-left">{summary}</span>
<ChevronDown className={"w-4 h-4 text-gray-400 shrink-0 transition-transform " + (open ? "rotate-180" : "")} />
<ChevronDown className={"w-4 h-4 text-gray-500 shrink-0 transition-transform " + (open ? "rotate-180" : "")} aria-hidden />
</button>
{open && (
<div className="absolute z-20 mt-1 left-0 right-0 bg-white border rounded-lg shadow-lg max-h-64 overflow-auto p-1">
<div className="flex items-center justify-between px-2 py-1.5 text-xs text-gray-500 border-b mb-1">
<button type="button" className="hover:underline" onClick={() => onChange(options.map(o => o.value))}>Select all</button>
<button type="button" className="hover:underline" onClick={() => onChange([])}>Clear</button>
<div className="absolute z-20 mt-1 left-0 right-0 min-w-[16rem] bg-white border rounded-lg shadow-lg p-1">
<div className="flex items-center gap-2 px-2 border-b">
<Search className="w-3.5 h-3.5 text-gray-500 shrink-0" aria-hidden />
<input
autoFocus
type="text"
aria-label="Search events"
placeholder="Search events…"
className="flex-1 py-1.5 text-sm outline-none bg-transparent"
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => { if (e.key === "Escape") setOpen(false); }}
/>
</div>
<div className="flex items-center justify-between px-2 py-1.5 text-xs text-gray-600 border-b mb-1">
<button type="button" className="hover:underline" onClick={selectShown}>{query.trim() ? `Select these ${shown.length}` : "Select all"}</button>
<button type="button" className="hover:underline" onClick={clearShown}>{query.trim() ? "Clear these" : "Clear"}</button>
</div>
<div className="max-h-64 overflow-auto">
{shown.map(opt => (
<label key={opt.value} className="flex items-center gap-2 px-2 py-1.5 text-sm rounded hover:bg-gray-50 cursor-pointer">
<input type="checkbox" checked={value.includes(opt.value)} onChange={() => toggle(opt.value)} />
<span className="truncate flex-1">{opt.label}</span>
{opt.hint && <span className="shrink-0 text-xs text-gray-500">{opt.hint}</span>}
</label>
))}
{shown.length === 0 && <div className="px-2 py-1.5 text-xs text-gray-500">{options.length ? "No events match." : "No events available."}</div>}
</div>
{options.map(opt => (
<label key={opt.value} className="flex items-center gap-2 px-2 py-1.5 text-sm rounded hover:bg-gray-50 cursor-pointer">
<input type="checkbox" checked={value.includes(opt.value)} onChange={() => toggle(opt.value)} />
<span className="truncate">{opt.label}</span>
</label>
))}
{options.length === 0 && <div className="px-2 py-1.5 text-xs text-gray-400">No events available.</div>}
</div>
)}
</div>
@@ -6,7 +6,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { REPORTS, REPORT_CATEGORIES, type ReportKey, type ReportCategory } from "./ReportCatalog";
import EventsDropdown from "./EventsDropdown";
type EventLite = { id: string; title: string };
type EventLite = { id: string; title: string; startDate?: string };
type DatePreset = "all_time" | "this_month" | "last_month" | "this_year" | "custom";
export default function ReportsShell({
@@ -93,7 +93,7 @@ export default function ReportsShell({
<div>
<div className="text-xs font-medium text-gray-600 mb-1">Events</div>
<EventsDropdown options={events.map(ev => ({ value: ev.id, label: ev.title }))} value={selectedEventIds} onChange={setSelectedEventIds} />
<EventsDropdown options={events.map(ev => ({ value: ev.id, label: ev.title, hint: ev.startDate ? new Date(ev.startDate).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : undefined }))} value={selectedEventIds} onChange={setSelectedEventIds} />
</div>
<div className="space-y-1.5 text-sm">
@@ -0,0 +1,259 @@
"use client";
import React, { useEffect, useId, useMemo, useRef, useState } from "react";
import { ChevronDown, Search, X } from "lucide-react";
export type PickerEvent = {
id: string;
title: string;
startDate: string;
endDate?: string | null;
campus?: { name: string } | null;
isActive?: boolean;
};
// Search results shown at once; typing more narrows them.
const MAX_RESULTS = 60;
const shortDate = (d: string) => new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
const isPast = (ev: PickerEvent, cutoff: number) => new Date(ev.endDate || ev.startDate).getTime() < cutoff;
/**
* A searchable event chooser in place of a long <select>. Opens on upcoming events (soonest
* first); past events (latest first) are one click away, and typing searches every event it
* was given by title, campus or date. `emptyLabel` adds a "no event" choice (e.g. "All events").
*/
export function EventPicker<E extends PickerEvent>({ events, value, onChange, emptyLabel, placeholder = "Choose an event", label = "Event", id, className = "", disabled = false, graceHours = 0, describe }: {
events: E[];
value: string;
onChange: (id: string, event: E | null) => void;
emptyLabel?: string;
placeholder?: string;
// Accessible name (visually hidden unless the page gives its own <label htmlFor={id}>).
label?: string;
id?: string;
className?: string;
disabled?: boolean;
// An event still counts as current this many hours after it ends (e.g. late scanning).
graceHours?: number;
// Extra detail after the date in the list, e.g. "3 roles".
describe?: (ev: E) => string | null | undefined;
}) {
const autoId = useId();
const buttonId = id || `event-picker-${autoId}`;
const listId = `${buttonId}-list`;
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [showPast, setShowPast] = useState(false);
const [active, setActive] = useState(0);
const rootRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLUListElement>(null);
const selected = events.find(e => e.id === value) || null;
const { upcoming, past } = useMemo(() => {
const cutoff = Date.now() - graceHours * 3600e3;
const up: E[] = [];
const old: E[] = [];
for (const ev of events) (isPast(ev, cutoff) ? old : up).push(ev);
up.sort((a, b) => +new Date(a.startDate) - +new Date(b.startDate));
old.sort((a, b) => +new Date(b.startDate) - +new Date(a.startDate));
return { upcoming: up, past: old };
}, [events, graceHours]);
// What the list shows: [heading | event | "none"] rows. Only events and "none" are choosable.
const { rows, hidden } = useMemo(() => {
type Row = { kind: "head"; text: string } | { kind: "none" } | { kind: "event"; ev: E; past: boolean };
const out: Row[] = [];
const q = query.trim().toLowerCase();
if (q) {
const words = q.split(/\s+/);
const hit = (ev: E) => {
const hay = `${ev.title} ${ev.campus?.name || ""} ${shortDate(ev.startDate)}`.toLowerCase();
return words.every(w => hay.includes(w));
};
const up = upcoming.filter(hit);
const old = past.filter(hit);
const all = [...up.map(ev => ({ ev, past: false })), ...old.map(ev => ({ ev, past: true }))];
all.slice(0, MAX_RESULTS).forEach(r => out.push({ kind: "event", ...r }));
return { rows: out, hidden: Math.max(0, all.length - MAX_RESULTS) };
}
if (emptyLabel) out.push({ kind: "none" });
if (upcoming.length) {
if (past.length) out.push({ kind: "head", text: "Upcoming" });
upcoming.forEach(ev => out.push({ kind: "event", ev, past: false }));
}
if (showPast && past.length) {
out.push({ kind: "head", text: "Past" });
past.forEach(ev => out.push({ kind: "event", ev, past: true }));
}
return { rows: out, hidden: 0 };
}, [query, upcoming, past, showPast, emptyLabel]);
const choosable = rows.map((r, i) => (r.kind === "head" ? -1 : i)).filter(i => i >= 0);
// Open on the chosen event; a past one shows the past list too.
const openList = () => {
if (disabled) return;
setQuery("");
const pastPick = !!selected && past.some(e => e.id === selected.id);
setShowPast(pastPick);
setOpen(true);
};
useEffect(() => {
if (!open) return;
inputRef.current?.focus();
const at = rows.findIndex(r => (r.kind === "event" ? r.ev.id === value : r.kind === "none" && !value));
setActive(at >= 0 ? at : (choosable[0] ?? 0));
// Only when it opens.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
useEffect(() => {
listRef.current?.querySelector(`[data-row="${active}"]`)?.scrollIntoView({ block: "nearest" });
}, [active, open]);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => { if (!rootRef.current?.contains(e.target as Node)) setOpen(false); };
document.addEventListener("mousedown", onDown);
return () => document.removeEventListener("mousedown", onDown);
}, [open]);
const close = () => { setOpen(false); buttonRef.current?.focus(); };
const choose = (i: number) => {
const r = rows[i];
if (!r || r.kind === "head") return;
if (r.kind === "none") onChange("", null);
else onChange(r.ev.id, r.ev);
close();
};
const move = (step: number) => {
if (!choosable.length) return;
const at = choosable.indexOf(active);
const next = at < 0 ? 0 : Math.min(choosable.length - 1, Math.max(0, at + step));
setActive(choosable[next]);
};
const onKey = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown") { e.preventDefault(); move(1); }
else if (e.key === "ArrowUp") { e.preventDefault(); move(-1); }
else if (e.key === "PageDown") { e.preventDefault(); move(10); }
else if (e.key === "PageUp") { e.preventDefault(); move(-10); }
else if (e.key === "Enter") { e.preventDefault(); choose(active); }
else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close(); }
else if (e.key === "Tab") setOpen(false);
};
const buttonText = selected ? selected.title : (emptyLabel || placeholder);
return (
<div ref={rootRef} className={`relative inline-block min-w-[16rem] max-w-full ${className}`} data-testid="event-picker">
<button
ref={buttonRef}
id={buttonId}
type="button"
disabled={disabled}
aria-haspopup="listbox"
aria-expanded={open}
aria-label={`${label}: ${buttonText}`}
onClick={() => (open ? setOpen(false) : openList())}
onKeyDown={e => { if (e.key === "ArrowDown" && !open) { e.preventDefault(); openList(); } }}
className="w-full flex items-center gap-2 border rounded-lg px-3 py-2 text-sm bg-white text-left hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
<span className={`flex-1 truncate ${selected ? "text-gray-900" : "text-gray-600"}`}>
{buttonText}
{selected && <span className="text-gray-500"> · {shortDate(selected.startDate)}</span>}
</span>
<ChevronDown className="w-4 h-4 text-gray-500 shrink-0" aria-hidden />
</button>
{open && (
<div className="absolute z-40 mt-1 w-full min-w-[18rem] sm:min-w-[24rem] rounded-lg border bg-white shadow-lg">
<div className="flex items-center gap-2 border-b px-3">
<Search className="w-4 h-4 text-gray-500 shrink-0" aria-hidden />
<input
ref={inputRef}
type="text"
role="combobox"
aria-expanded="true"
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={rows[active] && rows[active].kind !== "head" ? `${listId}-${active}` : undefined}
aria-label={`Search ${label.toLowerCase()}s`}
placeholder="Search by name, campus or date…"
className="flex-1 py-2 text-sm outline-none bg-transparent"
value={query}
onChange={e => { setQuery(e.target.value); setActive(0); }}
onKeyDown={onKey}
/>
{query && (
<button type="button" aria-label="Clear search" className="text-gray-500 hover:text-gray-800" onClick={() => { setQuery(""); inputRef.current?.focus(); }}>
<X className="w-4 h-4" aria-hidden />
</button>
)}
</div>
<ul ref={listRef} id={listId} role="listbox" aria-label={`${label}s`} className="max-h-72 overflow-y-auto py-1">
{rows.map((r, i) => {
if (r.kind === "head") {
return <li key={`h-${r.text}`} role="presentation" className="px-3 pt-2 pb-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{r.text}</li>;
}
const isSel = r.kind === "none" ? !value : r.ev.id === value;
return (
<li
key={r.kind === "none" ? "none" : r.ev.id}
id={`${listId}-${i}`}
data-row={i}
role="option"
aria-selected={isSel}
onMouseDown={e => e.preventDefault()}
onClick={() => choose(i)}
onMouseMove={() => active !== i && setActive(i)}
className={`px-3 py-1.5 text-sm cursor-pointer ${i === active ? "bg-brand-50" : ""} ${isSel ? "font-medium" : ""}`}
>
{r.kind === "none" ? (
<span className="text-gray-700">{emptyLabel}</span>
) : (
<span className="flex items-baseline gap-2">
<span className="flex-1 min-w-0 truncate text-gray-900">{r.ev.title}</span>
<span className="shrink-0 text-xs text-gray-600">
{r.ev.campus?.name ? `${r.ev.campus.name} · ` : ""}{shortDate(r.ev.startDate)}{r.past && query ? " · past" : ""}{r.ev.isActive === false ? " · inactive" : ""}{describe?.(r.ev) ? ` · ${describe(r.ev)}` : ""}
</span>
</span>
)}
</li>
);
})}
{!rows.some(r => r.kind === "event") && (
<li role="presentation" className="px-3 py-2 text-sm text-gray-500">
{query ? "No events match." : past.length ? "No upcoming events." : "No events."}
</li>
)}
</ul>
<div className="flex items-center justify-between gap-2 border-t px-3 py-1.5 text-xs text-gray-600" aria-live="polite">
<span>
{query
? `${rows.filter(r => r.kind === "event").length + hidden} match${rows.filter(r => r.kind === "event").length + hidden === 1 ? "" : "es"}${hidden ? ` · showing the first ${MAX_RESULTS}, keep typing` : ""}`
: `${upcoming.length} upcoming${showPast ? ` · ${past.length} past` : ""}`}
</span>
{!query && past.length > 0 && (
<button type="button" className="text-brand-700 hover:underline" onClick={() => { setShowPast(s => !s); inputRef.current?.focus(); }}>
{showPast ? "Hide past events" : `Show past events (${past.length})`}
</button>
)}
</div>
</div>
)}
</div>
);
}
/** The event a page opens on: the next one coming up, or else the most recent. */
export function defaultEventId(events: PickerEvent[], now = Date.now()): string {
let next: PickerEvent | null = null;
let last: PickerEvent | null = null;
for (const ev of events) {
const start = new Date(ev.startDate).getTime();
if (!isPast(ev, now)) { if (!next || start < new Date(next.startDate).getTime()) next = ev; }
else if (!last || start > new Date(last.startDate).getTime()) last = ev;
}
return (next || last)?.id || "";
}