WIP 2.0.0: React Compiler lint rules back to errors; docs

- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

e2e 102/102 (PayFast sandbox skipped); production build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 17:45:25 +02:00
co-authored by Claude Opus 5.5
parent 3f59164ab2
commit abd2c36e97
102 changed files with 613 additions and 354 deletions
+6 -9
View File
@@ -8,16 +8,13 @@ const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
{
// React Compiler-era rules that eslint-plugin-react-hooks 7 (with Next 16) turns on as
// errors. They flag patterns the app uses on purpose and that work (mostly loading data in
// useEffect), so they're warnings while the code is moved off them screen by screen —
// see HANDOVER, "Next.js 16". New code should follow them.
// The React Compiler rules (set-state-in-effect, purity, immutability, refs,
// static-components) are errors, as eslint-plugin-react-hooks 7 sets them (back on in 2.0).
// Loading data or reading the browser in an effect: useExternalEffect; state that follows
// other state: useStateSync (both in lib/hooks.ts) — see HANDOVER, "Next.js 16".
rules: {
"react-hooks/set-state-in-effect": "warn",
"react-hooks/purity": "warn",
"react-hooks/immutability": "warn",
"react-hooks/static-components": "warn",
"react-hooks/refs": "warn",
// Those two take deps like useEffect; check them the same way.
"react-hooks/exhaustive-deps": ["warn", { additionalHooks: "^(useExternalEffect|useStateSync)$" }],
},
},
globalIgnores([".next/**", ".next-*/**", "out/**", "build/**", "next-env.d.ts", "src/lib/api-v2/schema.d.ts"]),
@@ -9,6 +9,7 @@ import { appName } from "@/lib/siteConfig";
import { ShieldCheck } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { hardNavigate } from "@/lib/navigation";
function ActivateAccountContent() {
const search = useSearchParams();
@@ -34,7 +35,7 @@ function ActivateAccountContent() {
// dashboard fresh so the new session is picked up.
if (data?.token) saveToken(data.token);
setStatus("Your account is now active. Redirecting…");
setTimeout(() => { window.location.href = "/dashboard"; }, 1500);
setTimeout(() => hardNavigate("/dashboard"), 1500);
} catch (err) {
setStatus(errorMessage(err) || "Activation failed. The link may have expired.");
} finally {
@@ -43,6 +43,8 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
if (!campus) notFound();
const events = await apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } });
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
const upcoming = (events || [])
.filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now)
@@ -9,6 +9,7 @@ import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const ACTION_LABELS: Record<string, string> = {
refund_created: "Refund created",
@@ -231,7 +232,7 @@ export default function AdminAuditLogPage() {
}, [token, buildQuery, setError]);
// load changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes.
useEffect(() => { if (token) load(1); }, [token, load]);
useExternalEffect(() => { if (token) load(1); }, [token, load]);
return (
<div className="max-w-6xl mx-auto w-full p-6">
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import React, { useCallback, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { fetchEvent } from "@/lib/api";
@@ -11,6 +11,7 @@ import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { createCost, updateCost, deleteCost } from "@/lib/eventSetup";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const METHOD_LABELS: Record<CashupMethod, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"];
@@ -55,7 +56,7 @@ export default function EventCashupPage() {
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
return (
<div className="max-w-4xl mx-auto space-y-4">
@@ -317,7 +318,7 @@ function CashByUserSection({ eventId, token, onCashSummaryChange }: {
}, [eventId, token, onCashSummaryChange]);
// onCashSummaryChange is a state setter in the parent, so this only reruns when the event/token change.
useEffect(load, [load]);
useExternalEffect(() => load(), [load]);
const rows = data?.rows || [];
const sumOf = (m: "cash" | "card" | "eft" | "other", key: "total" | "count") =>
@@ -947,7 +948,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
// CashByUserSection below; when there is one, cash on hand is whatever wasn't deposited.
const [cashSummary, setCashSummary] = useState<{ actualTotal: number | null; denominations: PersonDenom[] }>({ actualTotal: null, denominations: [] });
useEffect(() => { setLines(initialLines); }, [initialLines]);
useExternalEffect(() => { setLines(initialLines); }, [initialLines]);
const setLine = (method: CashupMethod, next: SettlementInput) => setLines(prev => ({ ...prev, [method]: next }));
@@ -12,6 +12,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { AttendeeFormModal, type AttendeeFormDef } from "@/components/shared/AttendeeFormModal";
import type { Event } from "@/types";
import { useExternalEffect } from "@/lib/hooks";
// GET /api/v2/corrections/events/{id} (services/corrections.ts)
type CorrectionTicket = {
@@ -265,7 +266,7 @@ function CorrectionsContent() {
}
}, [token, eventId, setMessage]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
useEffect(() => {
if (!eventId) return;
fetchEvent<Event>(eventId, { authToken: token || undefined })
@@ -9,6 +9,7 @@ import { Inbox, AlertTriangle } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type RequestType = "access" | "correction" | "deletion";
type RequestStatus = "open" | "completed" | "rejected" | "cancelled";
@@ -144,10 +145,9 @@ export default function DataRequestsPage() {
// Search once typing pauses; a new search or tab starts at page 1.
useEffect(() => {
const t = setTimeout(() => setSearch(searchInput.trim()), 350);
const t = setTimeout(() => { setSearch(searchInput.trim()); setPage(1); }, 350);
return () => clearTimeout(t);
}, [searchInput]);
useEffect(() => { setPage(1); }, [view, search]);
const [msg, setMsg] = useDismissingState<Msg>(null);
const load = useCallback(async () => {
@@ -163,7 +163,7 @@ export default function DataRequestsPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load requests." });
}
}, [token, view, page, search, setMsg]);
useEffect(() => { setRequests(null); load(); }, [load]);
useExternalEffect(() => { setRequests(null); load(); }, [load]);
return (
<div className="max-w-4xl mx-auto w-full">
@@ -181,7 +181,7 @@ export default function DataRequestsPage() {
<div className="flex flex-wrap items-center gap-2 mb-4">
{(["open", "closed"] as const).map(v => (
<button key={v} onClick={() => setView(v)} aria-pressed={view === v} className={`px-3 py-1.5 rounded-lg text-sm font-medium ${view === v ? "bg-brand-600 text-white" : "bg-white border text-gray-700 hover:bg-gray-50"}`}>
<button key={v} onClick={() => { setView(v); setPage(1); }} aria-pressed={view === v} className={`px-3 py-1.5 rounded-lg text-sm font-medium ${view === v ? "bg-brand-600 text-white" : "bg-white border text-gray-700 hover:bg-gray-50"}`}>
{v === "open" ? `Open${openCount ? ` (${openCount})` : ""}` : "Closed"}
</button>
))}
@@ -19,6 +19,7 @@ import { CampusFilter } from "@/components/shared/CampusFilter";
import { TodayPanel } from "@/components/dashboard/TodayPanel";
import { CommandPaletteButton } from "@/components/shared/CommandPalette";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`;
@@ -108,7 +109,7 @@ export default function AdminDashboardPage() {
}
}, [token, campus, setPaymentStats, setOverview]);
useEffect(() => {
useExternalEffect(() => {
if (!token) return;
loadStats();
}, [token, loadStats]);
@@ -13,6 +13,7 @@ import { RegistrationBulkBar } from "@/components/admin/RegistrationBulkBar";
import { SavedFilters } from "@/components/shared/SavedFilters";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const;
@@ -60,7 +61,8 @@ export default function AdminRegistrationsPage() {
// Deep links (the dashboard's "Waiting for you" list and the Ctrl+K palette): ?q=, ?status=, ?event=.
// A search by reference may be for a past event's registration, so past events are included then.
useEffect(() => {
// Deep links (the command palette, other pages): read the URL once.
useExternalEffect(() => {
const params = new URLSearchParams(window.location.search);
const q = params.get("q");
if (q) { setQuery(q); setIncludePastEvents(true); }
@@ -103,11 +105,11 @@ export default function AdminRegistrationsPage() {
} catch {}
}, [token, includePastEvents, includeInactiveEvents]);
useEffect(() => {
useExternalEffect(() => {
loadRegistrations();
}, [loadRegistrations]);
useEffect(() => {
useExternalEffect(() => {
loadEvents();
}, [loadEvents]);
@@ -23,6 +23,7 @@ import { mapsSearchUrl } from "@/lib/maps";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { uploadImage } from "@/lib/eventSetup";
import { useExternalEffect } from "@/lib/hooks";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai";
@@ -896,7 +897,7 @@ function WhatsAppTab({ active }: { active: boolean }) {
}
}, [token]);
useEffect(() => { if (active) fetchConfig(); }, [fetchConfig, active]);
useExternalEffect(() => { if (active) fetchConfig(); }, [fetchConfig, active]);
const fetchStatus = useCallback(async () => {
if (!token || step !== 3) return;
@@ -911,7 +912,7 @@ function WhatsAppTab({ active }: { active: boolean }) {
}
}, [token, step, fetchConfig]);
useEffect(() => { if (active && step === 3) fetchStatus(); }, [step, fetchStatus, active]);
useExternalEffect(() => { if (active && step === 3) fetchStatus(); }, [step, fetchStatus, active]);
// Auto-poll status when not stable — only while this tab is active.
useEffect(() => {
@@ -931,7 +932,7 @@ function WhatsAppTab({ active }: { active: boolean }) {
}
}, [token]);
useEffect(() => {
useExternalEffect(() => {
if (active && status === "SCAN_QR_CODE") { fetchQr(); }
else { setQrSrc(null); }
}, [status, fetchQr, active]);
@@ -13,6 +13,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { useCampuses } from "@/hooks/useCampuses";
import { SavedFilters } from "@/components/shared/SavedFilters";
import { apiV2Data, apiV2 } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
interface UserItem {
id: string;
@@ -60,7 +61,7 @@ export default function AdminUsersPage() {
const [activeFilter, setActiveFilter] = useState<"" | "true" | "false">("");
// ?q= (the Ctrl+K palette links here with a person's email).
useEffect(() => {
useExternalEffect(() => {
const q = new URLSearchParams(window.location.search).get("q");
if (q) { setQuery(q); setDebouncedQuery(q); }
}, []);
@@ -113,7 +114,7 @@ export default function AdminUsersPage() {
// Initial load, and back to page 1 whenever a filter or the page size changes
// (loadUsers is recreated when any of them do).
useEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]);
useExternalEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]);
const goToPage = (p: number) => loadUsers(p);
@@ -14,6 +14,7 @@ import type { Event, Ticket as TicketRecord } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
function EventTicketsContent() {
const { token, user } = useAuth();
@@ -60,7 +61,8 @@ function EventTicketsContent() {
}, [token, setError]);
// No event in the URL: default to the first upcoming one once the list arrives.
useEffect(() => {
// No event in the URL: pick the first and put it there.
useExternalEffect(() => {
if (paramEventId || events.length === 0) return;
setEventId(events[0].id);
router.replace(
@@ -71,7 +73,7 @@ function EventTicketsContent() {
}, [events, paramEventId, router, selectedUserId]);
// Sync params → state (setting the value it already has is a no-op)
useEffect(() => {
useStateSync(() => {
if (paramEventId) setEventId(paramEventId);
if (paramUserId) setSelectedUserId(paramUserId);
}, [paramEventId, paramUserId]);
@@ -19,6 +19,7 @@ import {
FAMILY_QR_PREFIX, QR_PREFIX, deviceId, loadOffline, offlineCheckIn, saveOffline, stickerAlert, suggestRoom,
type CheckInResult, type KidsBoard, type KidsFamily, type OfflineState,
} from "@/lib/kids";
import { useExternalEffect } from "@/lib/hooks";
type Tab = "in" | "out" | "rooms";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -78,7 +79,7 @@ export default function KidsDeskPage() {
}
}, [token, eventId, sessionId, working]);
useEffect(() => {
useExternalEffect(() => {
setBoard(null);
setFamily(null);
setResult(null);
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
@@ -11,6 +11,7 @@ import { KidsEventPicker } from "@/components/kids/KidsEventPicker";
import { RoomBoard, RoomStatusBadges } from "@/components/kids/RoomBoard";
import type { KidsBoard } from "@/lib/kids";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const ROOM_KEY = "hope_events_kids_room";
@@ -24,7 +25,7 @@ export default function KidsRoomsPage() {
const [error, setError] = useState<string | null>(null);
const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
useEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []);
useExternalEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []);
const load = useCallback(async (log = false) => {
if (!token || !eventId) return;
@@ -37,7 +38,7 @@ export default function KidsRoomsPage() {
}
}, [token, eventId, sessionId]);
useEffect(() => { load(true); }, [load]);
useExternalEffect(() => { load(true); }, [load]);
useVisiblePolling(() => { load(); }, 5000, !!token && !!eventId);
const pickRoom = (id: string) => {
@@ -13,6 +13,7 @@ import { CampusScopeNote } from "@/components/shared/CampusFilter";
import { TodayPanel } from "@/components/dashboard/TodayPanel";
import { CommandPaletteButton } from "@/components/shared/CommandPalette";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const QUICK_ACTIONS = [
{ href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode },
@@ -63,7 +64,7 @@ export default function StaffDashboardPage() {
}
}, [token, setStats, setRecentScans]);
useEffect(() => {
useExternalEffect(() => {
if (!token) return;
loadStats();
}, [token, loadStats]);
@@ -16,6 +16,7 @@ import { activeSessions, currentSessionLabel, formatSessionWhen, sessionLabel }
import { BackLink } from "@/components/shared/BackLink";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { listSections } from "@/lib/eventSetup";
import { useStateSync } from "@/lib/hooks";
// What the confirm step needs, from GET /api/v2/checkin/{qrCode}. Offline scans build the
// same shape from the downloaded ticket list.
@@ -109,7 +110,6 @@ export default function TicketScanningPage() {
const selectedEvent = useMemo(() => allEvents.find(ev => ev.id === selectedEventId) || null, [allEvents, selectedEventId]);
const eventSessions = useMemo(() => selectedEvent?.scheduleType === "sessions" ? activeSessions(selectedEvent.sessions) : [], [selectedEvent]);
useEffect(() => { setSelectedSessionId("auto"); }, [selectedEventId]);
const sessionParam = selectedEventId !== "all" && selectedSessionId !== "auto" ? selectedSessionId : null;
useEffect(() => {
@@ -133,13 +133,16 @@ export default function TicketScanningPage() {
}, [selectedEventId, token]);
// In offline mode the event and section are fixed to the locked scope.
useEffect(() => {
// An offline lock fixes the event and section this device scans for.
useStateSync(() => {
if (!offline.lock) return;
setSelectedEventId(offline.lock.eventId);
setSelectedSessionId("auto");
}, [offline.lock]);
useEffect(() => {
if (!offline.lock) return;
setSelectedSectionId(offline.lock.sectionId || "all");
// Again when the sections load (the picker needs the locked one in its list).
useStateSync(() => {
void sections;
if (offline.lock) setSelectedSectionId(offline.lock.sectionId || "all");
}, [offline.lock, sections]);
// Bug fix: stop the scanner when the event or section filter changes so stale scan
@@ -377,7 +380,7 @@ export default function TicketScanningPage() {
className="w-full sm:w-72"
events={pickerEvents}
value={selectedEventId === "all" ? "" : selectedEventId}
onChange={id => setSelectedEventId(id || "all")}
onChange={id => { setSelectedEventId(id || "all"); setSelectedSessionId("auto"); }}
emptyLabel="All events"
graceHours={12}
disabled={!!offline.lock}
@@ -12,6 +12,7 @@ import type { Event } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data, apiV2Raw } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Group = { id: string; name: string; capacity: number | null; gender: "male" | "female" | null; leaderUserId: string | null; leader?: { id: string; name: string } | null };
type AllocSet = { id: string; name: string; showOnTicket: boolean; groups: Group[]; assignments: { attendeeId: string; groupId: string }[] };
@@ -115,7 +116,7 @@ export default function AllocationsPage() {
setError(errorMessage(e) || "Failed to load allocations");
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const current = board?.sets.find(s => s.id === setId) || null;
const groupOf = useMemo(() => new Map((current?.assignments || []).map(a => [a.attendeeId, a.groupId])), [current]);
@@ -21,6 +21,7 @@ import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRe
import { EventPicker } from "@/components/shared/EventPicker";
import { AttendeeFormModal, formsStillNeeded } from "@/components/shared/AttendeeFormModal";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" };
@@ -1103,7 +1104,7 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo, onF
}, [token, eventId]);
// Again when the registration changes: its tickets may have just been issued.
useEffect(() => { load(); }, [load, registration]);
useExternalEffect(() => { void registration; load(); }, [load, registration]);
if (!registration) {
return (
@@ -1572,7 +1573,8 @@ function SendTicketsModal({ open, onClose, token, registration }: {
const [localError, setLocalError] = useDismissingState("");
const [localInfo, setLocalInfo] = useState("");
useEffect(() => {
// Each time it opens: start from the registration's details.
useStateSync(() => {
if (open && registration) {
setPhone(registration.user?.phoneNumber || "");
setEmail(registration.user?.email?.endsWith("@guest.local") ? "" : registration.user?.email || "");
@@ -1706,7 +1708,7 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded
const [saving, setSaving] = useState(false);
const [localError, setLocalError] = useDismissingState("");
useEffect(() => {
useStateSync(() => {
if (open) { setAmount(""); setReason(""); setLocalError(""); }
}, [open, setLocalError]);
@@ -1842,7 +1844,7 @@ function DoorRefundPanel({ token, eventId, setInfo }: {
}
}, [token, eventId]);
useEffect(() => {
useExternalEffect(() => {
load();
}, [load]);
@@ -2004,7 +2006,7 @@ function NewAttendeeModal({ open, onClose, seed, onConfirm }: {
const [err, setErr] = useState("");
// Pre-fill name from whatever was typed in search
useEffect(() => {
useStateSync(() => {
if (open) {
setName(seed || "");
setEmail("");
@@ -12,6 +12,7 @@ import type { AttendanceRegister, AttendanceRow, Event } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data, apiV2Raw } from "@/lib/apiV2";
import { useExternalEffect, useNow } from "@/lib/hooks";
type Filter = "all" | "completed" | "not_completed" | "missed_recent";
@@ -65,12 +66,13 @@ function AttendancePageInner() {
setBusy(false);
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const columns = useMemo(() => (reg?.columns || []).filter(c => showCancelled || !c.cancelled), [reg, showCancelled]);
const multi = reg?.event.scheduleType === "sessions";
// Sessions already held (for "missed the last two").
const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < Date.now()).map(c => c.id), [reg]);
const now = useNow();
const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < now).map(c => c.id), [reg, now]);
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -11,6 +11,7 @@ import { BackLink } from "@/components/shared/BackLink";
import type { BundleGroupPricing, BundleKind, EventBundle } from "@/types";
import { EventPicker, defaultEventId } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] };
type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] };
@@ -108,7 +109,7 @@ export default function BundlesPage() {
}, [token, canView, setError]);
// Start on the next upcoming event (or the latest one).
useEffect(() => {
useStateSync(() => {
if (!allEvents.some(e => e.id === eventId)) setEventId(defaultEventId(allEvents));
}, [allEvents, eventId]);
@@ -127,7 +128,7 @@ export default function BundlesPage() {
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const toggleActive = async (b: EventBundle) => {
try {
@@ -13,6 +13,7 @@ import type { Event, ConsentRow, MedicalRow } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker, defaultEventId } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const STATUS_STYLE: Record<ConsentRow["status"], { label: string; cls: string }> = {
@@ -70,7 +71,7 @@ export default function ConsentTrackerPage() {
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const rows = useMemo(() => {
const all = data?.rows || [];
@@ -9,6 +9,7 @@ import { TicketPercent, Plus, X, Search, Pencil, Power, Users, CalendarClock, Li
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type CouponType = "percent" | "fixed" | "comp";
type Role = "user" | "staff" | "supervisor" | "admin";
@@ -176,7 +177,7 @@ export default function CouponsPage() {
}
}, [token, setError]);
useEffect(() => { if (token && canView) load(); }, [token, canView, load]);
useExternalEffect(() => { if (token && canView) load(); }, [token, canView, load]);
// Codes that can still be used first; off, expired and used-up ones only when asked for.
const visible = useMemo(() => {
@@ -422,7 +423,10 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: {
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [userQuery, setUserQuery] = useState("");
const [userResults, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]);
const [foundUsers, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]);
const searchingUsers = d.restrictTo === "users" && userQuery.trim().length >= 2;
// Only while there's a search (a shorter query clears the list without another render).
const userResults = searchingUsers ? foundUsers : [];
const [eventQuery, setEventQuery] = useState("");
const [showPast, setShowPast] = useState(false);
const set = <K extends keyof Draft>(key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value }));
@@ -443,7 +447,7 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: {
const scopedEvents = useMemo(() => events.filter(e => d.eventIds.includes(e.id)), [events, d.eventIds]);
useEffect(() => {
if (d.restrictTo !== "users" || userQuery.trim().length < 2) { setUserResults([]); return; }
if (!searchingUsers) return;
const t = setTimeout(async () => {
try {
const res = await (apiV2Data("get", "/users", { query: { search: userQuery.trim(), limit: "8" }, authToken: token }) as Promise<{ data: { id: string; name: string; email: string }[] }>);
@@ -451,7 +455,7 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: {
} catch { setUserResults([]); }
}, 300);
return () => clearTimeout(t);
}, [userQuery, d.restrictTo, token]);
}, [userQuery, searchingUsers, token]);
const toggleEvent = (id: string) => {
const eventIds = d.eventIds.includes(id) ? d.eventIds.filter(x => x !== id) : [...d.eventIds, id];
@@ -16,6 +16,7 @@ import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { AiDraftMessage } from "@/components/shared/AiDraftMessage";
import { AiImprove } from "@/components/shared/AiImprove";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
type Attendee = { id: string; name: string; email: string; pref: string };
type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets';
@@ -211,10 +212,12 @@ function EmailAttendeesPageInner() {
}, [token, setError]);
// Reload when the signed-in user changes too (e.g. after an impersonation switch).
useEffect(() => { loadEvents(); }, [user, loadEvents]);
useExternalEffect(() => { void user; loadEvents(); }, [user, loadEvents]);
const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]);
const [loadingUsers, setLoadingUsers] = useState(false);
// Load users for broadcasts
useEffect(() => {
useExternalEffect(() => {
const run = async () => {
try {
if (!token) return;
@@ -236,7 +239,7 @@ function EmailAttendeesPageInner() {
// Form state
const [eventId, setEventId] = useState<string>(preselectEventId);
useEffect(() => {
useStateSync(() => {
if (preselectEventId) setEventId(preselectEventId);
}, [preselectEventId]);
@@ -245,8 +248,6 @@ function EmailAttendeesPageInner() {
const [showInfo, setShowInfo] = useState(false);
// Broadcasts state
const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]);
const [loadingUsers, setLoadingUsers] = useState(false);
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
const [broadcastEventId, setBroadcastEventId] = useState<string>("");
const [broadcastSubject, setBroadcastSubject] = useState("");
@@ -291,7 +292,7 @@ function EmailAttendeesPageInner() {
}
}, [token]);
useEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]);
useExternalEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]);
const openEdit = (job: ScheduledJob) => {
setEditing(job);
@@ -353,7 +354,8 @@ function EmailAttendeesPageInner() {
// Event helper to prefill templates
const currentEvent = useMemo(() => (events || []).find(e => e.id === eventId), [events, eventId]);
useEffect(() => {
// A template fills in the subject and message, unless they were typed over.
useStateSync(() => {
const title = currentEvent?.title || 'the event';
if (templateKey === 'payment_reminder') {
if (!subjectDirty) setSubject(`Payment reminder: ${title}`);
@@ -1025,7 +1027,7 @@ With gratitude`);
const [promoEventId, setPromoEventId] = React.useState<string>('');
// Compute defaults when event changes or finalHours change
React.useEffect(() => {
useStateSync(() => {
if (!currentEvent) { setPreWhen(''); setFinalWhen(''); setThanksWhen(''); setPromoWhen(''); return; }
try {
const start = new Date(currentEvent.startDate);
@@ -11,6 +11,7 @@ import type { Event, EventOption } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { createTicketOption, updateTicketOption, deleteTicketOption } from "@/lib/eventSetup";
import { useExternalEffect } from "@/lib/hooks";
// Format a Date (or date-like input) to the value expected by <input type="datetime-local">
// This returns local time (browser timezone) as YYYY-MM-DDTHH:mm
@@ -34,14 +35,17 @@ function EarlyBirdTiersEditor({ option, onSave }: { option: EventOption; onSave:
const [open, setOpen] = React.useState(false);
const [saving, setSaving] = React.useState(false);
React.useEffect(() => {
// Start the rows again whenever another option (or a fresh copy of its tiers) comes in — set
// while rendering, React's way to reset state from a prop without an effect.
const [rowsFrom, setRowsFrom] = React.useState<unknown>(undefined);
if (rowsFrom !== option?.earlyBirdTiers) {
setRowsFrom(option?.earlyBirdTiers);
const tiers = Array.isArray(option?.earlyBirdTiers) ? option.earlyBirdTiers : [];
const normalized = tiers
setRows(tiers
.slice()
.sort((a, b) => new Date(a.deadline).getTime() - new Date(b.deadline).getTime() || (a.order || 0) - (b.order || 0))
.map((t, i) => ({ id: t.id, deadline: toLocalDateTimeInputValue(t.deadline), price: String(t.price ?? ''), order: typeof t.order === 'number' ? t.order : i }));
setRows(normalized);
}, [option?.id, option?.earlyBirdTiers]);
.map((t, i) => ({ id: t.id, deadline: toLocalDateTimeInputValue(t.deadline), price: String(t.price ?? ''), order: typeof t.order === 'number' ? t.order : i })));
}
const addRow = () => {
setRows((r) => [...r, { deadline: '', price: '', order: (r.length || 0) }]);
@@ -120,7 +124,10 @@ function EventOptionsContent() {
const [events, setEvents] = useState<Event[]>([]);
const [selectedEventId, setSelectedEventId] = useState<string>("");
const [options, setOptions] = useState<EventOption[]>([]);
const options = useMemo<EventOption[]>(() => {
const ev = events.find(e => e.id === selectedEventId);
return ev ? ev.options || ev.eventOptions || [] : [];
}, [selectedEventId, events]);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null);
@@ -134,24 +141,16 @@ function EventOptionsContent() {
}
}, [token]);
useEffect(() => { loadEvents(); }, [loadEvents]);
useExternalEffect(() => { loadEvents(); }, [loadEvents]);
// Preselect event from query (?eventId=)
useEffect(() => {
useExternalEffect(() => {
const q = search?.get("eventId");
if (!q) return;
// if events already loaded, ensure it exists then set; otherwise, set directly and let options hook handle
setSelectedEventId(q);
}, [search]);
useEffect(() => {
const ev = events.find(e => e.id === selectedEventId);
if (ev) {
setOptions(ev.options || ev.eventOptions || []);
} else {
setOptions([]);
}
}, [selectedEventId, events]);
const [newOpt, setNewOpt] = useState({ name: "", price: "", isMainTicket: false });
@@ -26,6 +26,7 @@ import { AiEventDraft, type AiEventDraftFields } from "@/components/events/AiEve
import { AiImprove } from "@/components/shared/AiImprove";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { createTicketOption, updateTicketOption, listSections, createSection, updateSection, deleteSection, listAttachments, uploadAttachment, deleteAttachment, uploadImage } from "@/lib/eventSetup";
import { useExternalEffect, useStateSync, useNow } from "@/lib/hooks";
// ─── helpers ────────────────────────────────────────────────────────────────
@@ -513,7 +514,7 @@ function SectionsManager({ eventId }: { eventId: string }) {
setEventOptions(evFull?.eventOptions || []);
} catch {} finally { setLoading(false); }
}, [eventId, token]);
useEffect(() => { if (eventId) load(); }, [eventId, load]);
useExternalEffect(() => { if (eventId) load(); }, [eventId, load]);
const create = async () => {
if (!newName.trim() || !token) return;
@@ -597,7 +598,7 @@ function AttachmentsManager({ eventId }: { eventId: string }) {
const load = useCallback(async () => {
setItems(await listAttachments(eventId));
}, [eventId]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const upload: React.ChangeEventHandler<HTMLInputElement> = async e => {
const file = e.target.files?.[0];
@@ -652,8 +653,9 @@ type NotifyUser = { id: string; name: string; email: string };
function useAnchorRect(anchorRef: React.RefObject<HTMLElement | null>, active: boolean) {
const [rect, setRect] = useState<{ top: number; left: number; width: number; bottom: number } | null>(null);
// Measured before paint (useLayoutEffect), so the dropdown never shows in the wrong place.
useLayoutEffect(() => {
if (!active) { setRect(null); return; }
if (!active) return;
const update = () => {
const el = anchorRef.current;
if (!el) return;
@@ -669,7 +671,7 @@ function useAnchorRect(anchorRef: React.RefObject<HTMLElement | null>, active: b
};
}, [anchorRef, active]);
return rect;
return active ? rect : null;
}
/** Presentational picker — pure controlled component, no API persistence of its own.
@@ -681,15 +683,16 @@ function NotifyRecipientsPicker({ selected, onChange, disabled }: { selected: No
const [searching, setSearching] = useState(false);
const anchorRef = useRef<HTMLDivElement>(null);
const visibleResults = results.filter(u => !selected.some(s => s.id === u.id));
// Only while there's a search (clearing the box clears the list without another render).
const visibleResults = (search.trim() ? results : []).filter(u => !selected.some(s => s.id === u.id));
const dropdownOpen = visibleResults.length > 0;
const rect = useAnchorRect(anchorRef, dropdownOpen);
useEffect(() => {
if (!search.trim()) { setResults([]); return; }
if (!search.trim()) return;
let cancelled = false;
setSearching(true);
const t = setTimeout(async () => {
setSearching(true);
try {
const res = await (apiV2Data("get", "/users", { query: { search: search.trim(), limit: "10" }, authToken: token }) as Promise<Paginated<NotifyUser>>);
if (!cancelled) setResults(Array.isArray(res?.data) ? res.data : []);
@@ -947,15 +950,17 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
// A campus-scoped person's new event starts at their (first) campus — they can't make
// events for all campuses — with that campus's default location if the field is still default.
useEffect(() => {
if (mode !== "create" || !campusInfo.scoped || !campusInfo.campuses.length) return;
// (Keyed on the first campus's id: the campus list is a new array each render.)
const firstCampusId = campusInfo.scoped ? campusInfo.campuses[0]?.id : undefined;
const firstCampusLocation = campusInfo.scoped ? campusInfo.campuses[0]?.defaultLocation : undefined;
useStateSync(() => {
if (mode !== "create" || !firstCampusId) return;
setDraft(d => {
if (d.campusId) return d;
const first = campusInfo.campuses[0];
const isDefault = !d.location.trim() || d.location === (settings.org_address || "");
return { ...d, campusId: first.id, ...(first.defaultLocation && isDefault ? { location: first.defaultLocation } : {}) };
return { ...d, campusId: firstCampusId, ...(firstCampusLocation && isDefault ? { location: firstCampusLocation } : {}) };
});
}, [mode, campusInfo.scoped, campusInfo.campuses, settings.org_address]);
}, [mode, firstCampusId, firstCampusLocation, settings.org_address]);
// Series to choose from (Basic Details).
const [seriesList, setSeriesList] = useState<EventSeries[]>([]);
@@ -1174,7 +1179,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
// user directly edits that option's price — then it becomes independent). A copy keeps its
// own option prices. ──
const [mainPriceTouched, setMainPriceTouched] = useState(cloning);
useEffect(() => {
useStateSync(() => {
if (mode !== "create" || mainPriceTouched) return;
setOptions(prev => {
if (prev.length === 0 || prev[0].price === draft.price) return prev;
@@ -2064,7 +2069,7 @@ export default function ManageEventsPage() {
}, [token, setError]);
// Reload when the signed-in user changes too (e.g. after an impersonation switch).
useEffect(() => { loadEvents(); }, [user, loadEvents]);
useExternalEffect(() => { void user; loadEvents(); }, [user, loadEvents]);
const [modalMode, setModalMode] = useState<"create" | "edit" | null>(null);
const [editingEvent, setEditingEvent] = useState<Event | null>(null);
@@ -2074,7 +2079,7 @@ export default function ManageEventsPage() {
const [search, setSearch] = useState("");
const [campus, setCampus] = useState("");
const isAdmin = user?.role === "admin";
const now = Date.now();
const now = useNow();
const filtered = useMemo(() => events.filter(ev => {
if (!showInactive && ev.isActive === false) return false;
@@ -2109,7 +2114,7 @@ export default function ManageEventsPage() {
// Deep links (the Ctrl+K palette): ?edit=<eventId> opens that event, ?new=1 a new one.
const deepLinked = useRef(false);
useEffect(() => {
useExternalEffect(() => {
if (deepLinked.current || !token) return;
deepLinked.current = true;
const params = new URLSearchParams(window.location.search);
@@ -12,6 +12,7 @@ import type { Event, EventForm, FormResponse, Registration, User } from "@/types
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useStateSync, useNow } from "@/lib/hooks";
type FormFieldType = 'yes_no' | 'text' | 'date' | 'numeric' | 'statement' | 'paragraph' | 'rating' | 'multiple_choice';
@@ -176,7 +177,7 @@ export default function FormsBrowserPage() {
setAllEvents(Array.isArray(sorted) ? sorted : []);
} catch {}
}, [token]);
useEffect(() => { loadEvents(); }, [loadEvents]);
useExternalEffect(() => { loadEvents(); }, [loadEvents]);
useEffect(() => {
if (!token) return;
@@ -199,8 +200,8 @@ export default function FormsBrowserPage() {
const isAdmin = user?.role === "admin";
const now = useNow();
const events = useMemo(() => {
const now = Date.now();
return allEvents.filter(ev => {
if (!evIncludeInactive && ev.isActive === false) return false;
if (!evIncludePast) {
@@ -209,7 +210,7 @@ export default function FormsBrowserPage() {
}
return true;
});
}, [allEvents, evIncludePast, evIncludeInactive]);
}, [allEvents, evIncludePast, evIncludeInactive, now]);
const search = async (append = false) => {
if (!token) return;
@@ -317,7 +318,7 @@ export default function FormsBrowserPage() {
}
}, [setError]);
useEffect(() => {
useExternalEffect(() => {
if (mode === 'manage' && selectedEventId && selectedEventId !== formLoadedFor) {
loadFormForEvent(selectedEventId);
}
@@ -359,11 +360,11 @@ export default function FormsBrowserPage() {
}
}, [token]);
useEffect(() => {
useStateSync(() => {
if (mode === 'fill') setFillEventId(prev => prev || selectedEventId || "");
}, [mode, selectedEventId]);
useEffect(() => {
useExternalEffect(() => {
if (mode !== 'fill') return;
if (fillEventId) loadRegsForEvent(fillEventId);
setFillRegistrationId(""); setFillRegistration(null); setExistingResponses([]); setFillForm({ isRequired: false, fields: [] });
@@ -393,7 +394,8 @@ export default function FormsBrowserPage() {
}, [fillRegistration]);
const [editableResponses, setEditableResponses] = useState<{ answers: Record<string,string> }[]>([]);
useEffect(() => {
// One editable set of answers per main ticket, started from what was saved.
useStateSync(() => {
if (mode !== 'fill') return;
const fields = (fillForm.fields || []).filter(f => f.type !== 'statement' && f.type !== 'paragraph');
const mapped: { answers: Record<string,string> }[] = (existingResponses || []).map((r)=>{
@@ -9,6 +9,7 @@ import { Baby, Plus, Trash2 } from "lucide-react";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Room = { id: string; name: string; capacity: number | null; minAge: number | null; maxAge: number | null; ratio: number | null; order: number };
type Settings = {
@@ -48,7 +49,7 @@ export default function KidsSetupPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the settings" });
}
}, [token, eventId, setMsg]);
useEffect(() => { setS(null); load(); }, [load]);
useExternalEffect(() => { setS(null); load(); }, [load]);
const run = async (fn: () => Promise<unknown>, ok: string) => {
setBusy(true);
@@ -19,6 +19,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { AttendeeFormModal, type AttendeeFormDef } from "@/components/shared/AttendeeFormModal";
import { useExternalEffect } from "@/lib/hooks";
// ─── Pricing helpers ─────────────────────────────────────────────────────────
@@ -264,7 +265,7 @@ export default function ManualRegistrationPage() {
})();
}, [token]);
useEffect(() => {
useExternalEffect(() => {
const ev = events.find(e => e.id === selectedEventId);
if (ev) {
const opts = ev.options || ev.eventOptions || [];
@@ -287,7 +288,7 @@ export default function ManualRegistrationPage() {
// The events list doesn't carry bundle deals or places per session; the single-event
// response does.
const [fullEvent, setFullEvent] = useState<Event | null>(null);
useEffect(() => {
useExternalEffect(() => {
if (!selectedEventId) { setBundles([]); setFullEvent(null); return; }
let cancelled = false;
fetchEvent<Event>(selectedEventId, { authToken: token || undefined })
@@ -298,7 +299,6 @@ export default function ManualRegistrationPage() {
// "Pick sessions" options: the sessions chosen per quantity key.
const [picks, setPicks] = useState<Record<string, string[]>>({});
useEffect(() => { setPicks({}); }, [selectedEventId]);
const pickOpt = (optionId: string) => {
const o = (fullEvent?.eventOptions || []).find(x => x.id === optionId);
return fullEvent && o && isPickOption(fullEvent, o) ? o : null;
@@ -444,7 +444,7 @@ export default function ManualRegistrationPage() {
<div className="grid md:grid-cols-2 gap-6">
<div className="border rounded-xl p-4 bg-white shadow-sm">
<div className="text-lg font-semibold mb-3">1) Choose event</div>
<EventPicker className="w-full" events={events} value={selectedEventId} onChange={setSelectedEventId} placeholder="Select an event" />
<EventPicker className="w-full" events={events} value={selectedEventId} onChange={id => { setSelectedEventId(id); setPicks({}); }} placeholder="Select an event" />
{selectedEventId && (
<div className="mt-3 text-xs text-gray-600">
{(() => {
@@ -11,6 +11,7 @@ import type { Event } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Lock = { id: string; sectionName: string | null; deviceName: string | null; user: { name: string }; lockedAt: string; snapshotAt: string | null; lastSyncAt: string | null };
type Report = {
@@ -65,7 +66,7 @@ export default function OfflineScansPage() {
setError(errorMessage(e) || "Failed to load offline scanning");
}
}, [token, eventId, onlyOpen, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const forceRelease = async (l: Lock) => {
try {
@@ -19,6 +19,7 @@ import { CampusFilter, CampusScopeNote } from "@/components/shared/CampusFilter"
import { TodayPanel } from "@/components/dashboard/TodayPanel";
import { CommandPaletteButton } from "@/components/shared/CommandPalette";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`;
@@ -107,7 +108,7 @@ export default function SupervisorDashboardPage() {
}
}, [token, campus, setScanStats, setPaymentStats, setRecentScans, setOverview]);
useEffect(() => {
useExternalEffect(() => {
if (!token) return;
loadStats();
}, [token, loadStats]);
@@ -15,6 +15,7 @@ import { useOnlinePayments } from "@/lib/onlinePayments";
import { WaitingForPayment } from "@/components/payments/WaitingForPayment";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
// A donation is never mutated once created — assigning it to a registration creates a separate
// "leg" Payment row (isDonation:false, originalPaymentId -> the donation, amount > 0) instead.
@@ -99,7 +100,7 @@ function UserSearchField({ allUsers, value, onChange, placeholder = "Search by n
const ref = useRef<HTMLDivElement>(null);
// Sync display name when value changes externally (e.g. pre-fill from metadata)
useEffect(() => {
useStateSync(() => {
const u = allUsers.find(u => String(u.id) === String(value));
setQuery(u?.name || "");
}, [value, allUsers]);
@@ -208,7 +209,7 @@ function PaymentsContent() {
}
}, [token, setError]);
useEffect(() => { loadPayments(); }, [loadPayments]);
useExternalEffect(() => { loadPayments(); }, [loadPayments]);
// Registrations still owing (not paid or cancelled), for the dropdowns. GET /api/v2/registrations
// embeds each registration's `payments`, so balances come from that in one pass. Refunds load
@@ -230,10 +231,12 @@ function PaymentsContent() {
}
}, [token]);
useEffect(() => { loadRegistrations(); }, [loadRegistrations]);
useExternalEffect(() => { loadRegistrations(); }, [loadRegistrations]);
const [allUsers, setAllUsers] = useState<User[]>([]);
const [loadingUsers, setLoadingUsers] = useState(false);
// Load all users for Refund section
useEffect(() => {
useExternalEffect(() => {
(async () => {
if (!token) return;
try {
@@ -259,8 +262,6 @@ function PaymentsContent() {
// Backdate field
const [paidAtLocal, setPaidAtLocal] = useState<string>("");
// Users for Refund section (load all users with supervisor rights)
const [allUsers, setAllUsers] = useState<User[]>([]);
const [loadingUsers, setLoadingUsers] = useState(false);
// New: user selection states for split dropdowns
const [selectedUserId, setSelectedUserId] = useState<string>("");
@@ -288,7 +289,7 @@ function PaymentsContent() {
return outstandingRegs.filter((r) => (String(r.user?.id || r.userId) === String(linkUserId)));
}, [outstandingRegs, linkUserId]);
useEffect(() => {
useStateSync(() => {
if (!linkRegistrationId) return;
const out = regOutstanding[linkRegistrationId]?.outstanding ?? 0;
setLinkAmount(out > 0 ? out.toFixed(2) : "");
@@ -355,13 +356,13 @@ function PaymentsContent() {
}
};
useEffect(() => {
useStateSync(() => {
const regQ = search?.get("registrationId");
if (regQ) setRegistrationId(regQ);
}, [search]);
// If a registration is preselected via query, infer and set its user
useEffect(() => {
useStateSync(() => {
if (!registrationId) return;
const reg = registrations.find((r) => String(r.id) === String(registrationId));
const uid = reg?.user?.id || reg?.userId;
@@ -381,7 +382,7 @@ function PaymentsContent() {
})();
}, [token, eventsIncludeInactive]);
useEffect(() => {
useStateSync(() => {
// Keep inputs sensible when toggling donation
if (isDonation) {
setRegistrationId("");
@@ -455,7 +456,7 @@ function PaymentsContent() {
setTxLoading(false);
}
}, [token]);
useEffect(() => { loadUnreconciled(); }, [loadUnreconciled]);
useExternalEffect(() => { loadUnreconciled(); }, [loadUnreconciled]);
// Inline reconcile form state per-row
const [reconcileForm, setReconcileForm] = useState<{ txId: string | null; type: 'reg' | 'don' | null; userId: string; registrationId: string; eventId: string; submitting: boolean }>({ txId: null, type: null, userId: '', registrationId: '', eventId: '', submitting: false });
@@ -883,7 +884,7 @@ function RefundSection({ allUsers, onDone }: RefundSectionProps) {
const [payments, setPayments] = useState<Payment[]>([]);
const [regs, setRegs] = useState<Registration[]>([]);
const [loadingUser, setLoadingUser] = useState(false);
useEffect(() => {
useExternalEffect(() => {
setPayments([]); setRegs([]);
if (!userId || !token) return;
let cancelled = false;
@@ -903,14 +904,15 @@ function RefundSection({ allUsers, onDone }: RefundSectionProps) {
const paymentsForUser = useMemo(() => payments.filter(p => (p.amount || 0) > 0), [payments]);
useEffect(() => {
// Reset dependent fields on changes
useStateSync(() => {
// Another person or refund type: start the dependent fields again.
void userId; void target;
setPaymentId("");
setRegistrationId("");
setAmount("");
}, [userId, target]);
useEffect(() => {
useStateSync(() => {
// If a payment selected, default amount and refund method to that payment's own —
// still editable, but staff shouldn't have to remember to change it manually.
if (target === 'payment') {
@@ -1175,8 +1177,6 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
const [sponsorshipsOnly, setSponsorshipsOnly] = useState(false);
const [err, setErr] = useState<string | null>(null);
useEffect(() => { setRegistrationId(""); setPaymentId(""); }, [userId]);
useEffect(() => { setPaymentId(""); }, [registrationId]);
// Registrations for the selected user that can actually receive a donation: an outstanding
// balance to apply it to, and an event that isn't closed.
@@ -1247,8 +1247,9 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
// Default to "apply as much as needed" whenever a new donation is picked — the common
// case needs no typing, but the field stays editable for a deliberate partial allocation.
useEffect(() => {
useStateSync(() => {
setAmountStr(maxAllocatable > 0 ? maxAllocatable.toFixed(2) : "");
// Only when another donation is picked, not as the amounts move.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [paymentId]);
@@ -1282,13 +1283,13 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
{err && <div className="p-2 mb-2 text-xs bg-red-50 text-red-700 border rounded">{err}</div>}
<div className="grid gap-2">
<label className="text-xs text-gray-600">1. User</label>
<UserSearchField allUsers={allUsers} value={userId} onChange={setUserId} />
<UserSearchField allUsers={allUsers} value={userId} onChange={uid => { setUserId(uid); setRegistrationId(""); setPaymentId(""); }} />
<label className="text-xs text-gray-600 mt-2">2. Registration</label>
<select
className="w-full max-w-full border rounded px-3 py-2 text-sm truncate"
value={registrationId}
onChange={e => setRegistrationId(e.target.value)}
onChange={e => { setRegistrationId(e.target.value); setPaymentId(""); }}
disabled={!userId}
>
<option value="">Select registration…</option>
@@ -11,6 +11,7 @@ import { CampusBadge } from "@/components/shared/CampusFilter";
import { SeasonPassesPanel } from "@/components/series/SeasonPassesPanel";
import type { EventSeries } from "@/types";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useNow } from "@/lib/hooks";
type Draft = { id?: string; name: string; slug: string; description: string; picture: string };
const blank: Draft = { name: "", slug: "", description: "", picture: "" };
@@ -62,6 +63,7 @@ export default function SeriesPage() {
const [list, setList] = useState<EventSeries[]>([]);
const [error, setError] = useState<string | null>(null);
const now = useNow();
const [notice, setNotice] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [saving, setSaving] = useState(false);
@@ -74,7 +76,7 @@ export default function SeriesPage() {
setError(errorMessage(e) || "Couldn't load the series");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const save = async () => {
if (!draft) return;
@@ -105,7 +107,6 @@ export default function SeriesPage() {
}
};
const now = Date.now();
return (
<div className="max-w-4xl mx-auto w-full p-6">
@@ -11,6 +11,7 @@ import { HandHeart } from "lucide-react";
import { hoursText, type HoursRow, type RosterEvent } from "@/lib/volunteers";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Settings = {
event: { id: string; title: string; volunteerOptionId: string | null };
@@ -56,9 +57,9 @@ export default function VolunteerRostersPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the settings" });
}
}, [token, eventId, setMsg]);
useEffect(() => { loadSettings(); }, [loadSettings]);
useExternalEffect(() => { loadSettings(); }, [loadSettings]);
useEffect(() => {
useExternalEffect(() => {
if (!token || tab !== "hours") return;
setHours(null);
(apiV2Data("get", "/volunteering/hours", { query: { eventId: !hoursAll && eventId ? eventId : undefined }, authToken: token }) as Promise<HoursRow[]>)
@@ -14,6 +14,7 @@ import type { Event } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Entry = {
id: string;
@@ -80,7 +81,7 @@ export default function WaitlistPage() {
setBusy(false);
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const act = async (id: string, action: "offer" | "move" | "remove", body: { direction?: "up" | "down" } = {}) => {
setBusy(true);
@@ -1,6 +1,6 @@
"use client";
import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter, useSearchParams } from "next/navigation";
import { fetchAllUsers, fetchManagedEvents } from "@/lib/api";
@@ -16,6 +16,7 @@ import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { AiDraftMessage } from "@/components/shared/AiDraftMessage";
import { AiImprove } from "@/components/shared/AiImprove";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
// Attendee with preference info
type Attendee = { id: string; name: string; phone: string; pref: string };
@@ -222,7 +223,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: Event[
const [promoWhen, setPromoWhen] = React.useState<string>("");
const [promoEventId, setPromoEventId] = React.useState<string>("");
React.useEffect(() => {
useStateSync(() => {
if (!currentEvent) { setPreWhen(""); setFinalWhen(""); setThanksWhen(""); setPromoWhen(""); return; }
try {
const start = new Date(currentEvent.startDate);
@@ -394,13 +395,14 @@ function WhatsAppAttendeesPageInner() {
// ── Attendees tab ──────────────────────────────────────────────────────────
const [eventId, setEventId] = useState<string>(preselectEventId);
useEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]);
useExternalEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]);
const [templateKey, setTemplateKey] = useState<TemplateKey>("custom");
const [messageKind, setMessageKind] = useState<MessageKind>("update");
const [message, setMessage] = useState("");
// Set once the supervisor edits the message, so picking a template doesn't overwrite it.
// A ref, not state: it only gates the template effect below and is never rendered.
const messageDirtyRef = useRef(false);
// Typed over (or drafted with AI): a template no longer replaces it.
const [messageDirty, setMessageDirty] = useState(false);
const [status, setStatus] = useState<StatusFilter>("any");
const [groupId, setGroupId] = useState("");
const [attendees, setAttendees] = useState<Attendee[]>([]);
@@ -414,16 +416,16 @@ function WhatsAppAttendeesPageInner() {
const currentEvent = useMemo(() => (events || []).find((e) => e.id === eventId), [events, eventId]);
useEffect(() => {
useStateSync(() => {
const title = currentEvent?.title || "the event";
if (templateKey === "payment_reminder") {
if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`);
if (!messageDirty) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`);
} else if (templateKey === "event_reminder") {
if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`);
if (!messageDirty) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`);
} else if (templateKey === "tickets") {
messageDirtyRef.current = false; setMessage("");
setMessageDirty(false); setMessage("");
}
}, [templateKey, currentEvent]);
}, [templateKey, currentEvent, messageDirty]);
useEffect(() => {
const run = async () => {
@@ -473,7 +475,7 @@ function WhatsAppAttendeesPageInner() {
};
const resetAttendeesForm = () => {
setTemplateKey("custom"); setMessageKind("update"); setMessage(""); messageDirtyRef.current = false;
setTemplateKey("custom"); setMessageKind("update"); setMessage(""); setMessageDirty(false);
setStatus("any"); setScheduledAtLocal(""); setPreviewCount(null); setPreviewSample(null);
setSelectedAttendeeIds(attendees.map((a) => a.id));
};
@@ -562,7 +564,7 @@ function WhatsAppAttendeesPageInner() {
} catch { } finally { setLoadingScheduled(false); }
}, [token]);
useEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, loadScheduled]);
useExternalEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, loadScheduled]);
const saveEdit = async () => {
if (!editing) return;
@@ -719,13 +721,13 @@ function WhatsAppAttendeesPageInner() {
{templateKey !== "tickets" ? (
<div>
<div className="mb-2">
<AiDraftMessage channel="whatsapp" eventId={eventId || undefined} onUse={d => { setMessage(d.body); messageDirtyRef.current = true; }} />
<AiDraftMessage channel="whatsapp" eventId={eventId || undefined} onUse={d => { setMessage(d.body); setMessageDirty(true); }} />
</div>
<label className="block text-xs text-gray-600 mb-1">Message</label>
<textarea className="w-full border rounded px-3 py-2 text-sm" rows={8} value={message}
onChange={(e) => { setMessage(e.target.value); messageDirtyRef.current = true; }}
onChange={(e) => { setMessage(e.target.value); setMessageDirty(true); }}
placeholder="Write your WhatsApp message to attendees..." />
<AiImprove text={message} onChange={t => { setMessage(t); messageDirtyRef.current = true; }} where="message" />
<AiImprove text={message} onChange={t => { setMessage(t); setMessageDirty(true); }} where="message" />
</div>
) : (
<div className="p-3 border rounded bg-gray-50 text-sm text-gray-700">
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
@@ -11,6 +11,7 @@ import { QrImage } from "@/components/shared/QrImage";
import { ChildForm, type ChildInput } from "@/components/kids/ChildForm";
import { FAMILY_QR_PREFIX, type KidsAdult, type KidsChild, type KidsFamily } from "@/lib/kids";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type ActiveCode = { code: string; qr: string; event: { id: string; title: string }; children: { name: string; room: string | null; checkedInAt: string }[] };
type Mine = { family: KidsFamily | null; qrToken: string | null; codes: ActiveCode[]; pages: { id: string; message: string; createdAt: string }[] };
@@ -37,7 +38,7 @@ export default function MyKidsPage() {
}
}, [token, setMsg]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// Codes and pages change while children are checked in.
useVisiblePolling(() => { if (data?.codes.length) load(); }, 15000, !!token);
@@ -22,6 +22,7 @@ import { MyCertificates } from "@/components/events/MyCertificates";
import { isPickOption } from "@/lib/sessions";
import type { Event, EventOption, Payment, Registration, RegistrationOption, Ticket as TicketRecord } from "@/types";
import { ModalOverlay } from "@/components/shared/ModalOverlay";
import { useExternalEffect, useNow } from "@/lib/hooks";
// Helper formatters
const formatRand = (n: number) => `R ${n.toFixed(2)}`;
@@ -35,12 +36,13 @@ const isEventOver = (ev: EventStatusFields | null | undefined) =>
// Status badge for an event, shown wherever an event title is displayed on this page.
// Precedence when more than one applies: Closed > Past > Inactive.
function EventStatusBadge({ event }: { event: EventStatusFields | null | undefined }) {
const now = useNow();
if (!event) return null;
let label: string | null = null;
let className = '';
if (event.cashupStatus === 'closed') {
label = 'Closed'; className = 'bg-rose-50 text-rose-700';
} else if (event.endDate && new Date(event.endDate).getTime() < Date.now()) {
} else if (event.endDate && new Date(event.endDate).getTime() < now) {
label = 'Past'; className = 'bg-amber-50 text-amber-700';
} else if (event.isActive === false) {
label = 'Inactive'; className = 'bg-gray-100 text-gray-500';
@@ -369,7 +371,7 @@ export default function UserDashboardPage() {
const activeBill = activeRegId ? billing[activeRegId] : undefined;
// When a registration is opened, determine whether its event has attendee forms
useEffect(() => {
useExternalEffect(() => {
setActiveEventHasForm(null);
if (!activeRegId) return;
const ar = registrations.find(r => r.id === activeRegId);
@@ -10,6 +10,7 @@ import { errorMessage } from "@/lib/utils";
import type { Paginated } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
interface PaymentItem {
id: string;
@@ -98,7 +99,7 @@ export default function UserPaymentsPage() {
}, [token, buildQuery, setError]);
// loadPayments changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes.
useEffect(() => { if (token) loadPayments(1); }, [token, loadPayments]);
useExternalEffect(() => { if (token) loadPayments(1); }, [token, loadPayments]);
const goToPage = (p: number) => loadPayments(p);
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
import { API_BASE } from "@/lib/api";
@@ -9,6 +9,7 @@ import { Megaphone, Download, PencilLine, Trash2, ListChecks, type LucideIcon }
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type RequestType = "access" | "correction" | "deletion";
type RequestStatus = "open" | "completed" | "rejected" | "cancelled";
@@ -88,7 +89,7 @@ export default function PrivacyCentrePage() {
setLoadError(errorMessage(e) || "Could not load your privacy settings.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// ── News & announcements ──────────────────────────────────────────────────
const [newsMsg, setNewsMsg] = useDismissingState<Msg>(null);
@@ -12,6 +12,7 @@ import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { useCampuses } from "@/hooks/useCampuses";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { useStateSync } from "@/lib/hooks";
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
@@ -25,6 +26,25 @@ const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | nu
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp" };
// Shared bits of the page (outside the component, so they aren't new components each render).
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
<div className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{msg.text}
</div>
);
const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof User; title: string; tone?: "brand" | "amber" | "red" }) => {
const toneCls = tone === "amber" ? "bg-amber-50 text-amber-600" : tone === "red" ? "bg-red-50 text-red-600" : "bg-brand-50 text-brand-600";
return (
<div className="flex items-center gap-2 mb-4">
<div className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${toneCls}`}>
<Icon className="w-5 h-5" />
</div>
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
</div>
);
};
export default function UserProfilePage() {
const { user, token, logout, updateToken } = useAuth();
const router = useRouter();
@@ -45,7 +65,7 @@ export default function UserProfilePage() {
const hasValidPhone = isValidZAPhone(phone);
useEffect(() => {
useStateSync(() => {
if (user) {
setName(user.name || "");
setEmail(user.email || "");
@@ -177,7 +197,7 @@ export default function UserProfilePage() {
// Admins and supervisors must keep 2FA on; they can only change the channel.
const tfRequired = !!user?.twoFactorRequired;
useEffect(() => {
useStateSync(() => {
if (user) {
setTfEnabled(!!user.twoFactorEnabled);
setTfMethod(user.twoFactorMethod || "email");
@@ -284,25 +304,9 @@ export default function UserProfilePage() {
};
// ── Shared helpers ────────────────────────────────────────────────────────
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
<div className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{msg.text}
</div>
);
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof User; title: string; tone?: "brand" | "amber" | "red" }) => {
const toneCls = tone === "amber" ? "bg-amber-50 text-amber-600" : tone === "red" ? "bg-red-50 text-red-600" : "bg-brand-50 text-brand-600";
return (
<div className="flex items-center gap-2 mb-4">
<div className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${toneCls}`}>
<Icon className="w-5 h-5" />
</div>
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
</div>
);
};
return (
<div className="max-w-4xl mx-auto w-full">
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { formatDate } from "@/lib/date";
@@ -9,6 +9,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { CheckCircle2, HandHeart, QrCode, Repeat } from "lucide-react";
import type { CoverRequest, MySlot, Roster, ServingEvent } from "@/lib/volunteers";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Mine = { slots: MySlot[]; cover: CoverRequest[]; events: ServingEvent[] };
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -32,9 +33,9 @@ export default function ServingPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load your shifts" });
}
}, [token, setMsg]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// ?event=<id>: the sign-up link a supervisor shares (works for hidden events too).
useEffect(() => {
useExternalEffect(() => {
const wanted = new URLSearchParams(window.location.search).get("event");
if (wanted) setOpenEvent(wanted);
}, []);
@@ -47,7 +48,7 @@ export default function ServingPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the roles" });
}
}, [token, setMsg]);
useEffect(() => { loadRoster(openEvent); }, [openEvent, loadRoster]);
useExternalEffect(() => { loadRoster(openEvent); }, [openEvent, loadRoster]);
const call = async (fn: () => Promise<unknown>, ok: string) => {
setBusy(true);
+3 -1
View File
@@ -33,7 +33,9 @@ type Event = {
export default async function EventsPage() {
const events = await apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } });
const now = Date.now();
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
const upcoming = (events || []).filter(e => {
if (e.cashupStatus === "closed") return false;
const t = new Date(e.endDate || e.startDate).getTime();
@@ -1,6 +1,6 @@
"use client";
import { Suspense, useEffect, useMemo, useState } from "react";
import { Suspense, useMemo, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
@@ -10,6 +10,7 @@ import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { ApiError } from "@/lib/api";
import { apiV2Data } from "@/lib/apiV2";
import { PrivacyNoticeSection, type PublicNotice } from "@/components/shared/PrivacyNoticeSection";
import { useExternalEffect } from "@/lib/hooks";
const fmtDate = (d: string) => new Date(d).toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" });
@@ -26,7 +27,7 @@ function PrivacyNotice() {
const sectionIds = useMemo(() => (notice?.sections || []).map(s => s.id), [notice]);
const activeId = useScrollSpy(sectionIds);
useEffect(() => {
useExternalEffect(() => {
setNotice(null);
setError(null);
(apiV2Data("get", "/privacy/notice", { query: { version: versionParam || undefined } }) as Promise<PublicNotice>)
+3 -1
View File
@@ -52,7 +52,9 @@ export default async function HomePage() {
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
getOrgName(),
]);
const now = Date.now();
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
const upcoming = (events || []).filter(e => {
const t = new Date(e.endDate || e.startDate).getTime();
return !isNaN(t) && t > now;
@@ -13,6 +13,8 @@ import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload,
import { JoinWaitlistButton } from "@/components/events/JoinWaitlistButton";
import { analyticsSessionId } from "@/lib/analytics";
import { errorMessage } from "@/lib/utils";
import { useStateSync, useExternalEffect } from "@/lib/hooks";
import { useRouter } from "next/navigation";
// Tiered low-stock threshold — mirrors events/[id]/page.tsx
function lowStockThreshold(stockLimit: number): number {
@@ -381,6 +383,7 @@ function DonationPicker({
}
export default function RegisterForm({ event: baseEvent }: { event: RegisterEvent }) {
const router = useRouter();
const { token, user } = useAuth();
const online = useOnlinePayments();
const eventId = baseEvent.id;
@@ -390,18 +393,6 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
const [waitlistToken, setWaitlistToken] = useState<string | null>(null);
const [offer, setOffer] = useState<WaitlistOffer | null>(null);
const [offerError, setOfferError] = useState<string | null>(null);
useEffect(() => {
const t = new URLSearchParams(window.location.search).get("waitlist");
if (!t) return;
(apiV2Data("get", "/waitlist/claims/{token}", { params: { token: t } }) as Promise<WaitlistOffer & { status: string }>)
.then(res => {
if (res.status !== "offered") { setOfferError("This waitlist offer has expired."); return; }
setWaitlistToken(t);
setOffer(res);
setQuantities(q => ({ ...q, [res.variantId ? `${res.eventOptionId}:${res.variantId}` : res.eventOptionId]: res.quantity }));
})
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
}, []);
const event = useMemo<RegisterEvent>(() => {
const priced = withLatePrices(baseEvent);
if (!offer) return priced;
@@ -433,6 +424,19 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
});
return initial;
});
// A waitlist offer link (?waitlist=…): load the offer and book its places.
useExternalEffect(() => {
const t = new URLSearchParams(window.location.search).get("waitlist");
if (!t) return;
(apiV2Data("get", "/waitlist/claims/{token}", { params: { token: t } }) as Promise<WaitlistOffer & { status: string }>)
.then(res => {
if (res.status !== "offered") { setOfferError("This waitlist offer has expired."); return; }
setWaitlistToken(t);
setOffer(res);
setQuantities(q => ({ ...q, [res.variantId ? `${res.eventOptionId}:${res.variantId}` : res.eventOptionId]: res.quantity }));
})
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
}, []);
const [error, setError] = useState<string | null>(null);
const [creatingRegistration, setCreatingRegistration] = useState(false);
const [coupon, setCoupon] = useState<AppliedCoupon | null>(null);
@@ -474,7 +478,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
const choosing = choosesSessions(event);
const pickFor = (opt: EventOption) => isPickOption(event, opt);
// A waitlist offer for one session: that session is ticked for them.
useEffect(() => {
useStateSync(() => {
if (!offer?.sessionId) return;
const key = offer.variantId ? `${offer.eventOptionId}:${offer.variantId}` : offer.eventOptionId;
setPicks(p => ({ ...p, [key]: [offer.sessionId as string] }));
@@ -569,7 +573,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
setError(null);
setCreatingRegistration(true);
const res = await register({ waitlistToken });
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent(Math.max(0, res.balance).toFixed(2))}`;
router.push(`/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent(Math.max(0, res.balance).toFixed(2))}`);
} catch (e) {
setError(errorMessage(e) || "Registration failed");
} finally {
@@ -581,7 +585,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
if (isLoggedIn) {
if (!token) {
setError("Session expired — please log in again.");
window.location.href = `/login?redirect=/register/${eventId}`;
router.push(`/login?redirect=/register/${eventId}`);
return;
}
try {
@@ -613,7 +617,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
if (!showGuestForm) {
setError("Please log in to register for this event.");
window.location.href = `/login?redirect=/register/${eventId}`;
router.push(`/login?redirect=/register/${eventId}`);
return;
}
@@ -627,9 +631,9 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
{
const hasForm = !!(event?.form && Array.isArray(event.form.fields) && event.form.fields.length > 0);
if (hasForm) {
window.location.href = `/forms?registrationId=${encodeURIComponent(res.id)}`;
router.push(`/forms?registrationId=${encodeURIComponent(res.id)}`);
} else {
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=0.00`;
router.push(`/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=0.00`);
}
}
} catch (e) {
@@ -15,6 +15,7 @@ import { ModalOverlay } from "@/components/shared/ModalOverlay";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data, apiV2 } from "@/lib/apiV2";
import { toAuthResponse } from "@/contexts/AuthContext";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
// ─── Types ────────────────────────────────────────────────────────────────────
type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null };
@@ -220,7 +221,7 @@ export default function SelfServicePage() {
// The events list doesn't carry bundle deals or places per session; the single-event
// response does.
const [kioskFull, setKioskFull] = useState<Event | null>(null);
useEffect(() => {
useExternalEffect(() => {
if (!selectedEventId) { setKioskBundles([]); setKioskFull(null); return; }
let cancelled = false;
fetchEvent<Event>(selectedEventId, { authToken: supervisorToken || undefined })
@@ -231,7 +232,6 @@ export default function SelfServicePage() {
// "Pick sessions" options: the sessions chosen per quantity key.
const [picks, setPicks] = useState<Record<string, string[]>>({});
useEffect(() => { setPicks({}); }, [selectedEventId]);
const pickOpt = (optionId: string) => {
const o = (kioskFull?.eventOptions || []).find(x => x.id === optionId);
return kioskFull && o && isPickOption(kioskFull, o) ? o : null;
@@ -417,6 +417,7 @@ export default function SelfServicePage() {
setShowChangeModal(false);
setScreen("setup");
setSelectedEventId("");
setPicks({});
resetForm();
} catch (err) {
setChangeError(errorMessage(err) || "Incorrect password.");
@@ -613,7 +614,6 @@ export default function SelfServicePage() {
setShowVisitorPassword(false);
setEmailMatch(null);
setPhoneMatch(null);
appliedMatchIdRef.current = null;
setShowUpdateConfirm(false);
setLookupMessage(null);
setFormError(null);
@@ -683,18 +683,19 @@ export default function SelfServicePage() {
// object identity instead of id made it re-fire and stomp every field — including
// ones the operator had already deliberately edited — back to the account's
// original values on every unrelated tap.
const appliedMatchIdRef = useRef<string | null>(null);
useEffect(() => {
if (!matchedAccount || appliedMatchIdRef.current === matchedAccount.id) return;
appliedMatchIdRef.current = matchedAccount.id;
// Fill the form in once per matched account (not again when the same account comes back as a
// new object, which would undo what the visitor typed). Starting over clears the match.
useStateSync(() => {
if (!matchedAccount) return;
setVisitorName(matchedAccount.name);
if (matchedAccount.email) setVisitorEmail(matchedAccount.email);
if (matchedAccount.phoneNumber) setVisitorPhone(matchedAccount.phoneNumber);
setNotificationPref(matchedAccount.notificationPreference);
}, [matchedAccount]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [matchedAccount?.id]);
// Existing accounts are linked automatically — never show the "create account" toggle for them
useEffect(() => {
useExternalEffect(() => {
if (accountExists && createAccount) {
setCreateAccount(false);
setVisitorPassword("");
@@ -854,7 +855,7 @@ export default function SelfServicePage() {
) : (
<div>
<label htmlFor="kiosk-event" className="block text-sm font-medium text-gray-700 mb-1">Event</label>
<EventPicker id="kiosk-event" className="w-full text-base" events={events} value={selectedEventId} onChange={setSelectedEventId} placeholder="Select an event" />
<EventPicker id="kiosk-event" className="w-full text-base" events={events} value={selectedEventId} onChange={id => { setSelectedEventId(id); setPicks({}); }} placeholder="Select an event" />
</div>
)}
{selectedEvent && (
@@ -48,6 +48,8 @@ export default async function SeriesPage({ params }: { params: Promise<{ slug: s
if (!series) notFound();
const events = await apiFetchListForPrerender<Event>(`/api/v2/event-listing?series=${encodeURIComponent(series.slug)}`, { nextOptions: { next: { revalidate } } });
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
const upcoming = (events || [])
.filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now)
@@ -17,6 +17,14 @@ const TYPE_LABELS: Record<BannerType, string> = {
danger: "Danger (red)",
};
function toLocalInput(iso: string) {
const d = new Date(iso);
if (isNaN(d.getTime())) return "";
// datetime-local wants "YYYY-MM-DDTHH:MM"
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
export default function SetBannerPage() {
const { user, token, loading } = useAuth();
const router = useRouter();
@@ -51,14 +59,6 @@ export default function SetBannerPage() {
.catch(() => {});
}, []);
function toLocalInput(iso: string) {
const d = new Date(iso);
if (isNaN(d.getTime())) return "";
// datetime-local wants "YYYY-MM-DDTHH:MM"
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
@@ -1,12 +1,13 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { API_BASE } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { DatabaseBackup, Download } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
interface BackupEntry {
filename: string;
@@ -60,7 +61,7 @@ export function BackupsTab({ active }: { active: boolean }) {
}
};
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const runBackup = async () => {
if (!token) return;
@@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
import { reloadCampuses, type Campus } from "@/hooks/useCampuses";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Person = { id: string; name: string; email: string };
type AdminCampus = Campus & {
@@ -36,7 +37,7 @@ function RecipientsField({ value, onChange }: { value: Person[]; onChange: (v: P
const [search, setSearch] = useState("");
const [results, setResults] = useState<Person[]>([]);
useEffect(() => {
if (!search.trim()) { setResults([]); return; }
if (!search.trim()) return;
let cancelled = false;
const t = setTimeout(async () => {
try {
@@ -46,7 +47,8 @@ function RecipientsField({ value, onChange }: { value: Person[]; onChange: (v: P
}, 300);
return () => { cancelled = true; clearTimeout(t); };
}, [search, token]);
const shown = results.filter(r => !value.some(v => v.id === r.id));
// Only while there's a search (clearing the box clears the list without another render).
const shown = (search.trim() ? results : []).filter(r => !value.some(v => v.id === r.id));
return (
<div className="space-y-2">
{value.length > 0 && (
@@ -134,7 +136,7 @@ export function CampusesTab({ active }: { active: boolean }) {
setCampuses(res.campuses);
} catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Could not load campuses." }); }
}, [token, setMsg]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const run = async (fn: () => Promise<unknown>, ok?: string) => {
setBusy(true);
@@ -1,11 +1,12 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { Timer, Play, RefreshCw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type JobRun = { state: string; createdOn?: string; startedOn: string | null; completedOn: string | null; output: unknown };
type JobInfo = { name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[] };
@@ -58,7 +59,7 @@ export function JobsTab({ active }: { active: boolean }) {
}
}, [token, setMessage]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const runNow = async (job: JobInfo) => {
if (!token) return;
@@ -1,10 +1,11 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { KeyRound, RefreshCw, ShieldCheck, ShieldAlert, ArrowUpCircle, Undo2, BellOff, BellRing, Megaphone } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { apiV2Data, apiV2Raw } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
export type HubStatus = {
state: "active" | "grace" | "suspended" | "revoked" | "unlicensed";
@@ -109,7 +110,7 @@ export function LicenceTab({ active }: { active: boolean }) {
if (!token) return;
try { setStatus(await (apiV2Data("get", "/hub/status", { authToken: token }) as Promise<HubStatus>)); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Could not load the licence." }); }
}, [token]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const checkNow = async () => {
setBusy(true);
@@ -1,11 +1,12 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Wallet } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
interface PayFastConfig {
merchantId: string;
@@ -50,7 +51,7 @@ export function PayFastSettings({ active, onChanged }: { active: boolean; onChan
}
}, [token, setMessage]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const save = async (e: React.FormEvent) => {
e.preventDefault();
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { ArrowDown, ArrowUp, Wallet } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
@@ -8,6 +8,7 @@ import { errorMessage } from "@/lib/utils";
import { YocoTab } from "@/components/admin/YocoTab";
import { PayFastSettings } from "@/components/admin/PayFastSettings";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type ProviderSetting = { id: string; label: string; enabled: boolean; configured: boolean };
@@ -33,7 +34,7 @@ export function PaymentsTab({ active }: { active: boolean }) {
}
}, [token, setMessage]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const save = async (next: ProviderSetting[]) => {
if (!token) return;
@@ -1,12 +1,13 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import React, { useMemo, useState } from "react";
import { CheckSquare, X, Download } from "lucide-react";
import { API_BASE } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { downloadReportExcel } from "@/lib/export";
import type { Event, Registration } from "@/types";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Action = "" | "message" | "markPaid" | "moveOption" | "allocate" | "cancel" | "export";
type Result = { id: string; ok: boolean; skipped?: boolean; message: string };
@@ -54,7 +55,7 @@ export function RegistrationBulkBar({ selected, events, token, onClear, onDone }
const options = useMemo(() => (oneEvent?.eventOptions || []).filter(o => o.id !== oneEvent?.kidsOptionId && o.id !== oneEvent?.volunteerOptionId), [oneEvent]);
const totalOwing = useMemo(() => selected.filter(r => r.status !== "cancelled").reduce((s, r) => s + owing(r), 0), [selected]);
useEffect(() => {
useExternalEffect(() => {
if (action !== "allocate" || !oneEvent) { setSets([]); return; }
(apiV2Data("get", "/events/{id}/allocations", { params: { id: oneEvent.id }, authToken: token }) as Promise<{ sets?: AllocationSet[] }>)
.then(b => setSets((b.sets || []).filter(s => s.groups.length)))
@@ -1,11 +1,12 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { Webhook, Send, RefreshCw, KeyRound, Trash2, Pencil, Copy, ChevronDown, ChevronRight, RotateCcw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { WebhookGuide } from "./WebhookGuide";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type EventType = { type: string; label: string; description: string; example?: unknown };
type Endpoint = {
@@ -67,7 +68,7 @@ function Deliveries({ endpointId, token }: { endpointId: string; token: string }
setRows(page);
setMore(page.length === PAGE);
}, [fetchPage]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const loadOlder = async () => {
if (!rows?.length) return;
const page = await fetchPage(rows[rows.length - 1].createdAt);
@@ -141,7 +142,7 @@ export function WebhooksTab({ active }: { active: boolean }) {
if (!token) return;
try { setData(await (apiV2Data("get", "/outbound-webhooks", { authToken: token }) as Promise<ListResponse>)); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Couldn't load webhooks" }); }
}, [token]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const run = async (fn: () => Promise<void>) => {
setBusy(true); setMsg(null);
@@ -1,11 +1,12 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Copy, CreditCard, KeyRound, Trash2, Webhook } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Source = "db" | "env" | "none";
@@ -123,7 +124,7 @@ export function YocoTab({ active, onChanged }: { active: boolean; onChanged?: ()
}
}, [token, loadHooks, setMessage]);
useEffect(() => { if (active) load(); }, [active, load]);
useExternalEffect(() => { if (active) load(); }, [active, load]);
const run = async (label: string, fn: () => Promise<string>) => {
setBusy(label);
@@ -1,10 +1,11 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { Plus, Copy, Pencil } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Status = "open" | "contained" | "closed";
type Breach = {
@@ -95,7 +96,7 @@ export function BreachesPanel({ token }: { token: string }) {
setError(errorMessage(e) || "Could not load the register.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const send = async (id: string | "new", body: Record<string, unknown>) => {
setBusy(true);
@@ -1,8 +1,9 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const fmt = (d: string | null) => (d ? new Date(d).toLocaleString(undefined, { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
const selectCls = "border rounded-lg px-3 py-2 text-sm bg-white";
@@ -50,7 +51,7 @@ export function ConsentLogPanel({ token }: { token: string }) {
setError(errorMessage(e) || "Could not load the consent log.");
}
}, [token, type, page, query]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
return (
<div className="space-y-3">
@@ -143,7 +144,7 @@ export function AccessLogPanel({ token }: { token: string }) {
setError(errorMessage(e) || "Could not load the access log.");
}
}, [token, action, actorId, sensitiveOnly, page]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
return (
<div className="space-y-3">
@@ -1,11 +1,12 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import Link from "next/link";
import { ArrowUp, ArrowDown, Trash2, Plus, RotateCcw, Eye, PencilLine, Sparkles } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { PrivacyNoticeSection, type NoticeSection } from "@/components/shared/PrivacyNoticeSection";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Version = { version: number; publishedAt: string; changeSummary: string | null; requiresAcceptance: boolean; publishedBy: string | null; acceptances: number };
// Changes to the built-in text since this site last reviewed them (only once it has published its own).
@@ -49,7 +50,7 @@ export function NoticeEditor({ token }: { token: string }) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the notice." });
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const change = (next: NoticeSection[]) => { setSections(next); setDirty(true); };
const update = (i: number, patch: Partial<NoticeSection>) => change(sections.map((s, j) => (j === i ? { ...s, ...patch } : s)));
@@ -1,9 +1,10 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Operator = { id: string; name: string; purpose: string; dataShared: string; location: string | null; website: string | null; active: boolean; order: number };
type Form = { name: string; purpose: string; dataShared: string; location: string; website: string; active: boolean };
@@ -46,7 +47,7 @@ export function OperatorsPanel({ token }: { token: string }) {
setError(errorMessage(e) || "Could not load operators.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const save = async (f: Form) => {
setBusy(true);
@@ -1,10 +1,11 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import Link from "next/link";
import { CheckCircle2, Circle, ArrowRight } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Check = { key: string; label: string; ok: boolean; detail: string; href: string | null; applies: boolean };
type Readiness = { score: number; passed: number; total: number; checks: Check[] };
@@ -21,7 +22,7 @@ export function ReadinessPanel({ token }: { token: string }) {
setError(errorMessage(e) || "Could not load the checklist.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
if (error) return <p className="text-sm text-red-700">{error}</p>;
if (!data) return <p className="text-sm text-gray-400">Loading…</p>;
@@ -1,9 +1,10 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import Link from "next/link";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Policy = { enabled: boolean; months: number };
type Definition = { label: string; description: string; minMonths: number; defaults: Policy };
@@ -44,7 +45,7 @@ export function RetentionPanel({ token }: { token: string }) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load retention settings." });
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const save = async () => {
const inactive = policies.inactive_accounts;
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import Link from "next/link";
import { CalendarClock, ArrowRight, Baby, HandHeart, UserCheck, Banknote, Inbox, CheckCircle2 } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
@@ -8,6 +8,7 @@ import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import { CampusBadge } from "@/components/shared/CampusFilter";
import type { Event } from "@/types";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type TodayEvent = {
id: string; title: string; location: string | null; campus: Event["campus"]; isHidden: boolean; kidsCheckIn: boolean;
@@ -37,7 +38,7 @@ export function TodayPanel({ supervisor }: { supervisor: boolean }) {
if (!token) return;
try { setData(await (apiV2Data("get", "/dashboard/today", { authToken: token }) as Promise<Today>)); } catch { /* keep what's shown */ }
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
useVisiblePolling(load, 30000, !!token);
if (!data) return null;
@@ -1,11 +1,12 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { CalendarX } from "lucide-react";
import { EventCard } from "@/components/events/EventCard";
import { CampusFilter } from "@/components/shared/CampusFilter";
import { useCampuses } from "@/hooks/useCampuses";
import { useAuth } from "@/hooks/useAuth";
import { useExternalEffect } from "@/lib/hooks";
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null };
@@ -28,7 +29,7 @@ export function EventsGrid({ events }: { events: GridEvent[] }) {
const { user } = useAuth();
const [campus, setCampus] = useState("");
useEffect(() => {
useExternalEffect(() => {
if (!enabled) return;
const stored = readStored();
const start = stored ?? user?.homeCampusId ?? "";
@@ -140,7 +140,8 @@ export function SessionsEditor({ sessions, onChange, defaultLocation, showCapaci
onChange([...sessions, keyed({ label: "", startsAt: fmt(start), endsAt: fmt(new Date(start.getTime() + dur)), location: "", cancelled: false, capacity: last?.capacity || "" })]);
};
let position = 0;
// Each active session's number (cancelled ones don't count).
const positions = sorted.map((s, i) => (s.cancelled ? 0 : sorted.slice(0, i + 1).filter(x => !x.cancelled).length));
return (
<div className="space-y-3">
{showPattern
@@ -156,8 +157,8 @@ export function SessionsEditor({ sessions, onChange, defaultLocation, showCapaci
<div className="px-3 py-2 text-xs text-gray-500 bg-gray-50 rounded-t-lg">
{activeCount} session{activeCount === 1 ? "" : "s"} — edit any date, add a label, or cancel one (e.g. a public holiday).
</div>
{sorted.map((s) => {
if (!s.cancelled) position += 1;
{sorted.map((s, i) => {
const position = positions[i];
return (
<div key={s.key} className={`p-3 space-y-2 ${s.cancelled ? "bg-gray-50" : ""}`}>
<div className="flex items-center gap-2">
@@ -5,6 +5,8 @@ import { activeSessions, formatSessionWhen, sessionLabel } from "@/lib/sessions"
// The schedule of a multi-day event on its public page: past sessions greyed out,
// cancelled ones struck through, and the next one highlighted.
export function SessionSchedule({ sessions, defaultLocation }: { sessions: EventSession[]; defaultLocation?: string | null }) {
// A server component renders once per request (or revalidation): this is that render's time.
// eslint-disable-next-line react-hooks/purity
const now = Date.now();
const sorted = [...sessions].sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime());
const next = activeSessions(sessions).find(s => new Date(s.endsAt).getTime() > now);
@@ -1,12 +1,13 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { HeartHandshake, X } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { useOnlinePayments } from "@/lib/onlinePayments";
import { ModalOverlay } from "@/components/shared/ModalOverlay";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Sponsorship = { enabled: boolean; open?: boolean; spotPrice?: number | null; showProgress?: boolean; goalSpots?: number | null; spotsFunded?: number | null; sponsors?: number | null };
@@ -34,7 +35,7 @@ export function SponsorSpot({ eventId, eventTitle }: { eventId: string; eventTit
const [returned, setReturned] = useState<string | null>(null);
const online = useOnlinePayments();
useEffect(() => {
useExternalEffect(() => {
(apiV2Data("get", "/events/{id}/sponsorship", { params: { id: eventId } }) as Promise<Sponsorship>).then(setData).catch(() => setData(null));
try {
const s = new URLSearchParams(window.location.search).get("sponsored");
@@ -5,6 +5,7 @@ import { usePathname } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { Home, Calendar, Phone, LogIn, UserPlus, LayoutDashboard, LogOut } from "lucide-react";
import { useBrandColorVar } from "@/lib/theme";
import { hardNavigate } from "@/lib/navigation";
export const BottomNav = () => {
const { user, loading: authLoading, logout } = useAuth();
@@ -15,7 +16,7 @@ export const BottomNav = () => {
const handleLogout = () => {
logout();
window.location.href = "/";
hardNavigate("/"); // a full load, so nothing of the old session stays in memory
};
const isActive = (href: string) => {
@@ -9,6 +9,7 @@ import { BottomNav } from "./BottomNav";
import churchLogo from "@/app/church_logo.jpg";
import { appName } from "@/lib/siteConfig";
import { resolveToApiOrigin } from "@/lib/api";
import { hardNavigate } from "@/lib/navigation";
type NavLink = {
href: string;
@@ -31,7 +32,7 @@ export const Navbar = () => {
const handleLogout = () => {
logout();
window.location.href = "/";
hardNavigate("/"); // a full load, so nothing of the old session stays in memory
};
const navLinks: NavLink[] = [
@@ -1,8 +1,9 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type OpenCheckout = {
id: string;
@@ -46,7 +47,7 @@ export function WaitingForPayment({ token, onRecorded }: { token: string | null;
setMessage({ ok: false, text: errorMessage(e) || "Couldn't load waiting payments" });
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const check = async (ids?: string[]) => {
if (!token) return;
@@ -1,10 +1,11 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { Wifi, WifiOff, CloudUpload, Lock } from "lucide-react";
import type { OtherLock } from "./useOfflineScanning";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Offline = ReturnType<typeof import("./useOfflineScanning").useOfflineScanning>;
@@ -26,7 +27,7 @@ export function OfflineScanPanel({ offline, token, eventId, eventTitle, sectionI
const [busy, setBusy] = useState(false);
const { lock, pending, online, syncing } = offline;
useEffect(() => {
useExternalEffect(() => {
if (!token || !eventId || eventId === "all" || !online) { setLocks([]); return; }
(apiV2Data("get", "/scan-locks", { query: { eventId: eventId }, authToken: token }) as Promise<OtherLock[]>)
.then(setLocks).catch(() => setLocks([]));
@@ -1,11 +1,12 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useRef, useState } from "react";
import { apiV2Data } from "@/lib/apiV2";
import {
OfflineLock, SnapshotTicket, clearOffline, deviceId, deviceName, findTicket, getOfflineLock,
queuedScans, recordScan, removeQueued, startOffline,
} from "@/lib/offlineScan";
import { useExternalEffect } from "@/lib/hooks";
export type OtherLock = { id: string; sectionId: string | null; sectionName: string | null; deviceId: string; deviceName: string | null; user: { name: string } };
@@ -26,7 +27,7 @@ export function useOfflineScanning(token: string | null) {
try { setPending((await queuedScans()).length); } catch { setPending(0); }
}, []);
useEffect(() => {
useExternalEffect(() => {
setLock(getOfflineLock());
refreshPending();
setOnline(typeof navigator === "undefined" ? true : navigator.onLine);
@@ -78,7 +79,7 @@ export function useOfflineScanning(token: string | null) {
}, [token, refreshPending]);
// Sync as soon as the connection is back, and every 30 seconds while online.
useEffect(() => {
useExternalEffect(() => {
if (!online || !token) return;
sync().catch(() => {});
const t = setInterval(() => { if (navigator.onLine) sync().catch(() => {}); }, 30000);
@@ -8,6 +8,7 @@ import { errorMessage } from "@/lib/utils";
import { formatDateTimeRange } from "@/lib/date";
import type { SeasonPassPurchase, SeasonPassView } from "@/types";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const rand = (n: number) => `R ${n.toFixed(2)}`;
type BuyResult = { purchaseId: string; total: number; paid: boolean; redirectUrl: string | null; message: string | null };
@@ -35,12 +36,12 @@ export function SeasonPassOffers({ slug, passes: initial }: { slug: string; pass
const list = await (apiV2Data("get", "/me/season-passes", { authToken: token }) as Promise<SeasonPassPurchase[]>).catch(() => [] as SeasonPassPurchase[]);
setMine(list.filter(p => p.pass.series.slug === slug && p.status !== "cancelled"));
}, [token, slug]);
useEffect(() => { loadMine(); }, [loadMine]);
useExternalEffect(() => { loadMine(); }, [loadMine]);
const returned = params.get("pass");
const go = (res: BuyResult | { redirectUrl: string | null; message: string | null }) => {
if (res.redirectUrl) { window.location.href = res.redirectUrl; return; }
if (res.redirectUrl) { window.location.assign(res.redirectUrl); return; }
setNotice(res.message || "Done.");
loadMine();
};
@@ -1,12 +1,13 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import React, { useCallback, useMemo, useState } from "react";
import { Ticket } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { fetchManagedEvents } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import type { Event, SeasonPassView } from "@/types";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type ItemDraft = { eventId: string; on: boolean; eventOptionId: string; variantId: string };
type Draft = { id?: string; name: string; description: string; price: string; saleEndsAt: string; isActive: boolean; items: ItemDraft[] };
@@ -41,7 +42,7 @@ export function SeasonPassesPanel({ seriesId, seriesSlug }: { seriesId: string;
setEvents((all || []).filter(e => e.seriesId === seriesId && e.requiresRegistration !== false && !e.requiresParentalConsent).sort((a, b) => a.startDate.localeCompare(b.startDate)));
setLoaded(true);
}, [token, seriesId]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// A pass's own events; events without a row yet (a new pass, or still loading) take the default:
// ticked on a new pass, with the first ticket that can be sold.
@@ -1,7 +1,8 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type SetWithGroups = { id: string; name: string; groups: { id: string; name: string }[] };
@@ -17,7 +18,7 @@ export function AllocationGroupFilter({ token, eventId, value, onChange }: {
}) {
const [sets, setSets] = useState<SetWithGroups[]>([]);
useEffect(() => {
useExternalEffect(() => {
onChange("");
if (!token || !eventId) { setSets([]); return; }
(apiV2Data("get", "/events/{id}/allocations", { params: { id: eventId }, authToken: token }) as Promise<{ sets: SetWithGroups[] }>)
@@ -2,6 +2,7 @@
import React from "react";
import { resolveToApiOrigin } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Props = {
src?: string | null;
@@ -14,7 +15,7 @@ export function ApiImage({ src, alt = "", className, style }: Props) {
const hasSrc = !!(src || "").trim();
const [resolved, setResolved] = React.useState<string | null>(null);
React.useEffect(() => {
useExternalEffect(() => {
const raw = (src || "").trim();
if (!raw) { setResolved(null); return; }
// Compute in the browser so that localhost origins are swapped to the actual device hostname.
@@ -2,6 +2,7 @@
import React, { useEffect, useState } from "react";
import { apiV2Data } from "@/lib/apiV2";
import { useNow } from "@/lib/hooks";
type BannerType = "info" | "warning" | "success" | "danger";
@@ -26,6 +27,8 @@ function dismissKey(banner: Banner) {
export function BannerBar() {
const [banner, setBanner] = useState<Banner | null>(null);
const [dismissed, setDismissed] = useState(false);
// Refreshed every minute, so the banner appears and goes at its times without a reload.
const now = useNow();
useEffect(() => {
(apiV2Data("get", "/banner") as Promise<Banner>)
@@ -42,7 +45,6 @@ export function BannerBar() {
if (!banner || !banner.message || dismissed) return null;
const now = Date.now();
const from = banner.liveFrom ? new Date(banner.liveFrom).getTime() : null;
const till = banner.liveTill ? new Date(banner.liveTill).getTime() : null;
@@ -1,10 +1,11 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { Gift } from "lucide-react";
import type { BundleItem, BundleQuote, PublicBundle } from "@/types";
import type { BasketItem } from "@/components/shared/CouponCodeField";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const fmt = (n: number) => `R${n.toFixed(2)}`;
@@ -27,7 +28,7 @@ export function useBundleQuote({ eventId, basket, token, forUserId, enabled = tr
const items = basket.filter(b => b.quantity > 0);
const key = JSON.stringify(items);
useEffect(() => {
useExternalEffect(() => {
const options = JSON.parse(key) as BasketItem[];
if (!enabled || !eventId || options.length === 0) { setQuote(null); return; }
let cancelled = false;
@@ -6,6 +6,7 @@ import { Search, Calendar, User, Banknote, ClipboardList, CornerDownLeft, Zap, F
import { useAuth } from "@/hooks/useAuth";
import { matchPages, type CommandPage } from "@/lib/commandPages";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
type Result = { type: "event" | "payment" | "person" | "registration"; id: string; title: string; subtitle: string; href: string };
type Item = { key: string; group: string; title: string; subtitle?: string; href: string; icon: React.ElementType };
@@ -49,12 +50,16 @@ export function CommandPalette() {
return () => { window.removeEventListener("keydown", onKey); window.removeEventListener(OPEN_PALETTE_EVENT, onOpen); };
}, [allowed]);
// Each time it opens: empty, with the search box focused.
useStateSync(() => {
if (open) { setQuery(""); setResults([]); setActive(0); }
}, [open]);
useEffect(() => {
if (open) { setQuery(""); setResults([]); setActive(0); setTimeout(() => inputRef.current?.focus(), 0); }
if (open) setTimeout(() => inputRef.current?.focus(), 0);
}, [open]);
// Search as they type (after a short pause); pages are matched here, instantly.
useEffect(() => {
useExternalEffect(() => {
if (!open || !token) return;
const q = query.trim();
if (q.length < 2) { setResults([]); return; }
@@ -72,7 +77,7 @@ export function CommandPalette() {
return query.trim() ? [...found, ...pages] : pages;
}, [role, query, results]);
useEffect(() => { setActive(a => Math.min(a, Math.max(0, items.length - 1))); }, [items.length]);
useStateSync(() => { setActive(a => Math.min(a, Math.max(0, items.length - 1))); }, [items.length]);
useEffect(() => { listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); }, [active]);
const go = useCallback((item: Item | undefined) => {
@@ -90,7 +95,6 @@ export function CommandPalette() {
else if (e.key === "Enter") { e.preventDefault(); go(items[active]); }
};
let lastGroup = "";
return (
<div className="fixed inset-0 z-[60] flex items-start justify-center bg-black/40 p-4 pt-[12vh]" onMouseDown={() => setOpen(false)}>
<div role="dialog" aria-modal="true" aria-label="Go to or search" className="w-full max-w-xl rounded-xl bg-white shadow-2xl overflow-hidden" onMouseDown={e => e.stopPropagation()}>
@@ -107,8 +111,8 @@ export function CommandPalette() {
<ul id="palette-results" ref={listRef} role="listbox" className="max-h-[55vh] overflow-y-auto py-1" data-testid="palette-results">
{items.length === 0 && <li className="px-4 py-6 text-sm text-gray-500 text-center">{query.trim().length < 2 ? "Type to search." : "Nothing found."}</li>}
{items.map((item, i) => {
const header = item.group !== lastGroup ? item.group : null;
lastGroup = item.group;
// A heading above the first item of each group.
const header = i === 0 || items[i - 1].group !== item.group ? item.group : null;
const Icon = item.icon;
return (
<React.Fragment key={item.key}>
@@ -4,6 +4,7 @@ import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Cookie } from "lucide-react";
import { getConsent, setConsent } from "@/lib/analytics";
import { useExternalEffect } from "@/lib/hooks";
/**
* Asks once whether we may use a cookie-like identifier to count visits (our own
@@ -12,7 +13,7 @@ import { getConsent, setConsent } from "@/lib/analytics";
export function CookieConsent() {
const [show, setShow] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => { setShow(getConsent() === null); }, []);
useExternalEffect(() => { setShow(getConsent() === null); }, []);
// Publishes the banner's height as --cookie-banner-h so HelpFab can sit above it.
useEffect(() => {
const el = ref.current;
@@ -1,9 +1,10 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import React, { useRef, useState } from "react";
import { TicketPercent, X } from "lucide-react";
import { ApiError } from "@/lib/api";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
export type BasketItem = { eventOptionId: string; variantId?: string | null; quantity: number };
@@ -72,7 +73,7 @@ export function CouponCodeField({
};
// Basket changed after a code was applied: check it again for the new items.
useEffect(() => {
useExternalEffect(() => {
if (lastKey.current === basketKey) return;
lastKey.current = basketKey;
if (applied) check(applied.code);
@@ -80,7 +81,7 @@ export function CouponCodeField({
}, [basketKey]);
// Staff switched attendee: restricted codes depend on who it's for.
useEffect(() => {
useExternalEffect(() => {
if (applied) check(applied.code);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [forUserId]);
@@ -2,6 +2,7 @@
import React, { useEffect, useId, useMemo, useRef, useState } from "react";
import { ChevronDown, Search, X } from "lucide-react";
import { useStateSync, useNow } from "@/lib/hooks";
export type PickerEvent = {
id: string;
@@ -52,15 +53,16 @@ export function EventPicker<E extends PickerEvent>({ events, value, onChange, em
const listRef = useRef<HTMLUListElement>(null);
const selected = events.find(e => e.id === value) || null;
const now = useNow();
const { upcoming, past } = useMemo(() => {
const cutoff = Date.now() - graceHours * 3600e3;
const cutoff = 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]);
}, [events, graceHours, now]);
// What the list shows: [heading | event | "none"] rows. Only events and "none" are choosable.
const { rows, hidden } = useMemo(() => {
@@ -101,14 +103,18 @@ export function EventPicker<E extends PickerEvent>({ events, value, onChange, em
setShowPast(pastPick);
setOpen(true);
};
useEffect(() => {
// When it opens: the chosen event (or the first choice) is the active row, and the search
// box has focus.
useStateSync(() => {
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(() => {
if (open) inputRef.current?.focus();
}, [open]);
useEffect(() => {
listRef.current?.querySelector(`[data-row="${active}"]`)?.scrollIntoView({ block: "nearest" });
}, [active, open]);
@@ -4,6 +4,7 @@ import React, { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { Eye } from "lucide-react";
import { currentImpersonation, endImpersonation, logImpersonatedPage, type Impersonation } from "@/lib/impersonation";
import { useExternalEffect } from "@/lib/hooks";
/** Bright bar on every page while an admin is viewing the site as someone else. */
export function ImpersonationBanner() {
@@ -12,7 +13,7 @@ export function ImpersonationBanner() {
const [left, setLeft] = useState("");
const [ending, setEnding] = useState(false);
useEffect(() => { setImp(currentImpersonation()); }, []);
useExternalEffect(() => { setImp(currentImpersonation()); }, []);
// Every page viewed goes into the session's audit trail.
useEffect(() => {
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
const FOCUSABLE =
'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
@@ -26,8 +26,9 @@ export function ModalOverlay({
children: React.ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
// The latest onClose, for the key handler (kept in step after each render, not during it).
const closeRef = useRef(onClose);
closeRef.current = onClose;
useLayoutEffect(() => { closeRef.current = onClose; });
// Taken while rendering: an autoFocus inside moves focus before the effect runs.
const [opener] = useState(() => (typeof document === "undefined" ? null : (document.activeElement as HTMLElement | null)));
@@ -1,10 +1,11 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { Info, Wrench, AlertTriangle, X } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import type { HubNotice } from "@/components/admin/LicenceTab";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
const DISMISSED_KEY = "cross_events_dismissed_notices";
@@ -32,7 +33,7 @@ export function ProviderNotices() {
const [dismissed, setDismissed] = useState<string[]>([]);
const canSee = user?.role === "admin" || user?.role === "supervisor";
useEffect(() => {
useExternalEffect(() => {
if (!canSee || !token) return;
setDismissed(readDismissed());
(apiV2Data("get", "/hub/notices", { authToken: token }) as Promise<HubNotice[]>).then(setNotices).catch(() => {});
@@ -5,6 +5,7 @@ import { Bookmark, Star, Trash2, Check } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
export type FilterValues = Record<string, string | number | boolean | string[]>;
type Saved = { id: string; name: string; params: FilterValues; isDefault: boolean };
@@ -47,7 +48,7 @@ export function SavedFilters({ page, value, onApply, skipDefault = false, classN
// onApply/skipDefault are read once, for the default.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [token, page]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// Close when clicking elsewhere.
useEffect(() => {
@@ -1,18 +1,19 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { errorMessage } from "@/lib/utils";
import { QrImage } from "@/components/shared/QrImage";
import { Printer } from "lucide-react";
import { checkInUrl } from "@/lib/volunteers";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
/** The event's volunteer check-in QR code, to show on a screen or print and put up at the venue. */
export function CheckInQr({ token, eventId, title }: { token: string | null; eventId: string; title: string }) {
const [qr, setQr] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
useExternalEffect(() => {
if (!token || !eventId) return;
setQr(null);
(apiV2Data("get", "/events/{id}/volunteers/qr", { params: { id: eventId }, authToken: token }) as Promise<{ qr: string }>)
@@ -1,11 +1,12 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import { errorMessage } from "@/lib/utils";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import { CheckCircle2, Pencil, Plus, Printer, Trash2, UserPlus, X } from "lucide-react";
import { fromLocalInput, toLocalInput, type Roster, type ServingRole } from "@/lib/volunteers";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Msg = { type: "ok" | "err"; text: string };
type Props = {
@@ -46,7 +47,7 @@ export function RosterSheet({ token, eventId, canEdit, kidsRooms = [], onMessage
}
}, [token, eventId, onMessage]);
// Opening the roster writes the access log (it shows contact details); refreshes don't.
useEffect(() => { setRoster(null); load(true); }, [load]);
useExternalEffect(() => { setRoster(null); load(true); }, [load]);
useVisiblePolling(() => { load(); }, 30000, !!token && !!eventId);
const run = async (fn: () => Promise<unknown>, ok: string) => {
@@ -1,7 +1,8 @@
"use client";
import React, { createContext, useContext, useEffect, useState } from "react";
import React, { createContext, useContext, useState } from "react";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
export type SiteSettings = {
org_name?: string;
@@ -63,7 +64,7 @@ export function SiteSettingsProvider({
// Always refreshes in the background (cheap, 60s-cached server-side) even
// when seeded from initialSettings — self-heals if the SSR fetch in
// layout.tsx failed, and picks up any change since that request.
useEffect(() => { load(); }, []);
useExternalEffect(() => { load(); }, []);
return (
<SiteSettingsContext.Provider value={{ settings, loading, reload: load }}>
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Event, Paginated, Payment, Registration, User } from "@/types";
import { hardNavigate } from "@/lib/navigation";
export type ApiOptions = {
method?: string;
@@ -142,7 +143,7 @@ export async function apiFetch<T = unknown>(path: string, options: ApiOptions =
localStorage.removeItem("hope_events_user_cache");
if (!window.location.pathname.startsWith("/login")) {
const back = window.location.pathname + window.location.search;
window.location.href = `/login?reason=2fa&redirect=${encodeURIComponent(back)}`;
hardNavigate(`/login?reason=2fa&redirect=${encodeURIComponent(back)}`);
}
}
throw new ApiError(res.status, message, data);
+53
View File
@@ -0,0 +1,53 @@
"use client";
import { useEffect, useState, type DependencyList } from "react";
/**
* Hooks for the effect patterns the React Compiler lint rules flag (2.0, when those rules went
* back to errors). Which one:
*
* - Nothing to store? Compute it while rendering (or `useMemo`).
* - State that follows other state or props ("when the event changes, start the form again")?
* `useStateSync`.
* - Reading or subscribing to something outside React — the API, localStorage, the URL, browser
* events — and setting state from what comes back? `useExternalEffect`.
*
* Both take a deps array, checked by exhaustive-deps like useEffect's (eslint.config.mjs).
*/
/**
* `useEffect` for effects that read from or subscribe to the outside world (the API, the
* browser) and set state from it — which the lint can't tell apart from state derived from
* other state. Runs after render and when `deps` change; a returned function is the clean-up.
*/
export function useExternalEffect(run: () => void | (() => void) | Promise<unknown>, deps: DependencyList) {
useEffect(() => {
const out = run();
return typeof out === "function" ? out : undefined;
// The caller's deps, checked at the call site by exhaustive-deps (additionalHooks).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
/**
* Updates this component's own state when `deps` change (and on the first render), while
* rendering — React's "adjusting state when a prop changes", without an effect's extra render
* and flash of the old state. `update` may only set state of this component, and the deps must
* be stable (state, props, memoised values): a new object each render would loop.
*/
export function useStateSync(update: () => void, deps: DependencyList) {
const [seen, setSeen] = useState<DependencyList | null>(null);
if (seen === null || seen.length !== deps.length || seen.some((d, i) => !Object.is(d, deps[i]))) {
setSeen(deps);
update();
}
}
/** The current time in ms, refreshed every `everyMs` (default a minute), so "is it over yet?" stays right. */
export function useNow(everyMs = 60_000): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), everyMs);
return () => clearInterval(t);
}, [everyMs]);
return now;
}
@@ -7,6 +7,7 @@
* browser sends.
*/
import { API_BASE } from "@/lib/api";
import { hardNavigate } from "@/lib/navigation";
const TOKEN_KEY = "hope_events_token";
const USER_CACHE_KEY = "hope_events_user_cache";
@@ -38,7 +39,7 @@ export function beginImpersonation(res: ImpersonationStart) {
localStorage.removeItem(USER_CACHE_KEY);
localStorage.setItem(IMP_KEY, JSON.stringify({ sessionId: res.session.id, expiresAt: res.session.expiresAt, name: res.session.target.name, email: res.session.target.email }));
} catch { /* storage unavailable */ }
window.location.href = "/dashboard/user";
hardNavigate("/dashboard/user");
}
/** Puts the admin's own session back (no server call). */
@@ -52,7 +53,7 @@ export function restoreAdmin(redirect = true) {
localStorage.removeItem(ADMIN_CACHE_KEY);
localStorage.removeItem(IMP_KEY);
} catch { /* storage unavailable */ }
if (redirect) window.location.href = "/dashboard/admin/users";
if (redirect) hardNavigate("/dashboard/admin/users");
}
/** Ends the session on the server (audited), then restores the admin. */
@@ -0,0 +1,8 @@
/**
* Goes to another page with a full page load. Only for when the whole app must start again —
* after signing out or switching who is signed in — or from code outside a component; anywhere
* else use `useRouter().push()`.
*/
export function hardNavigate(path: string) {
window.location.assign(new URL(path, window.location.origin).href);
}
+3 -2
View File
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { useState } from "react";
import { useExternalEffect } from "@/lib/hooks";
/**
* Static fallback for BRAND_600 — used as the initial value before the
@@ -21,7 +22,7 @@ const BRAND_600_FALLBACK = "#4F46E5";
export function useBrandColorVar(cssVar: string, fallback: string = BRAND_600_FALLBACK): string {
const [color, setColor] = useState(fallback);
useEffect(() => {
useExternalEffect(() => {
const value = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
if (value) setColor(value);
}, [cssVar]);