- 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
260 lines
12 KiB
TypeScript
260 lines
12 KiB
TypeScript
"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 || "";
|
|
}
|