loopable / web /src /signup /JoinPage.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
98c8696 verified
Raw History Blame Contribute Delete
6.2 kB
import { useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import { Brand } from "../shell/Brand";
import "./signup.css";
type Invite = { company: string; phone: string; expiresAt: string };
type Phase = "loading" | "ready" | "expired" | "used" | "success" | "error";
type JoinError = { error?: { code?: string; message?: string } };
// Keep consumed links recognizable in this tab without persisting invitation tokens.
const consumed = new Set<string>();
const EXPIRED = "This link has expired. Text Loopy again.";
export default function JoinPage({ token }: { token: string }) {
const [phase, setPhase] = useState<Phase>("loading");
const [invite, setInvite] = useState<Invite | null>(null);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [message, setMessage] = useState("");
const [weak, setWeak] = useState(false);
const [busy, setBusy] = useState(false);
const [attempt, setAttempt] = useState(0);
const submitting = useRef(false);
const endpoint = `${API_V1}/join/${encodeURIComponent(token)}`;
useEffect(() => {
if (consumed.has(token)) { setPhase("used"); return; }
const controller = new AbortController();
setPhase("loading");
setMessage("");
void (async () => {
try {
const response = await fetch(endpoint, { credentials: CREDENTIALS, signal: controller.signal });
const body = await response.json() as Invite & JoinError;
if (controller.signal.aborted) return;
if (response.status === 404) { setPhase("expired"); return; }
if (!response.ok) {
setMessage(body.error?.message || "This link could not be loaded. Try again.");
setPhase("error");
return;
}
if (typeof body.company !== "string" || typeof body.phone !== "string" || typeof body.expiresAt !== "string")
throw new Error("Unreadable invitation");
setInvite({ company: body.company, phone: body.phone, expiresAt: body.expiresAt });
setPhase("ready");
} catch {
if (controller.signal.aborted) return;
setMessage("This link could not be loaded. Try again.");
setPhase("error");
}
})();
return () => controller.abort();
}, [token, endpoint, attempt]);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (submitting.current || phase !== "ready") return;
submitting.current = true;
setBusy(true);
setMessage("");
setWeak(false);
try {
const response = await fetch(endpoint, {
method: "POST", credentials: CREDENTIALS,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: name.trim(), email: email.trim(), password }),
});
const body = await response.json() as JoinError & { ok?: boolean };
if (response.status === 404) { setPhase("expired"); return; }
if (body.error?.code === "join_used") { setPhase("used"); return; }
if (!response.ok) {
setWeak(body.error?.code === "weak_password");
setMessage(body.error?.message || "Your account could not be created. Try again.");
return;
}
if (body.ok !== true) throw new Error("Unreadable signup result");
consumed.add(token);
setPassword("");
setPhase("success");
} catch {
setMessage("The server could not be reached. Try again.");
} finally {
submitting.current = false;
setBusy(false);
}
}
return (
<main className="signup-page signed-out" data-state={phase} aria-labelledby="join-title">
<div className="signup-form-wrap signed-out-panel">
<Brand size={44} className="signup-brand" />
<h1 id="join-title">Join{invite ? ` ${invite.company}` : ""}</h1>
{phase === "loading" ? (
<div className="signup-loading" role="status" aria-label="Loading invitation">
<div /><div /><div />
</div>
) : phase === "ready" && invite ? (
<>
<p className="signup-phone">{invite.phone}</p>
<form className="signup-form" onSubmit={submit}>
<label htmlFor="join-name">Name</label>
<input id="join-name" name="name" autoComplete="name" required maxLength={120}
value={name} onChange={(event) => setName(event.target.value)} disabled={busy} />
<label htmlFor="join-email">Email</label>
<input id="join-email" name="email" type="email" autoComplete="email" required maxLength={254}
value={email} onChange={(event) => setEmail(event.target.value)} disabled={busy} />
<label htmlFor="join-password">Password</label>
<input id="join-password" name="password" type="password" autoComplete="new-password" required
value={password} onChange={(event) => setPassword(event.target.value)} disabled={busy}
aria-invalid={weak} aria-describedby="join-message" />
<p id="join-message" className="signup-error" role="alert">{message}</p>
<button className="signup-primary" type="submit" disabled={busy} aria-busy={busy}>Join</button>
</form>
</>
) : phase === "expired" ? (
<p className="signup-status" role="status">{EXPIRED}</p>
) : phase === "used" ? (
<>
<p className="signup-status" role="status">This link has already been used. Sign in to continue.</p>
<a className="signup-signin" href="#/login">Sign in</a>
</>
) : phase === "success" ? (
<>
<p className="signup-status" role="status">You are in. Sign in to finish setup.</p>
<a className="signup-signin" href="#/login">Sign in</a>
</>
) : (
<>
<p className="signup-error" role="alert">{message}</p>
<button className="signup-primary" type="button" onClick={() => setAttempt((value) => value + 1)}>Try again</button>
</>
)}
</div>
</main>
);
}