File size: 6,198 Bytes
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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>
  );
}