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
@@ -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) => {