xonecas.io
8058
Ir

irvc / files

irvc / web / src / views / Join.tsx

2.0 KB
1import { useEffect, useState, type FormEvent } from "react";
2import { Button, Centered, Spinner, TextInput } from "@/ui";
3import AuthShell from "../components/AuthShell";
4import { api } from "../lib/api";
5import type { User } from "../lib/types";
6
7export default function Join({ onJoin }: { onJoin: (u: User) => void }) {
8  const token = new URLSearchParams(window.location.search).get("token") ?? "";
9  const [valid, setValid] = useState<boolean | null>(null);
10  const [error, setError] = useState("");
11
12  useEffect(() => {
13    api(`/invites/${token}`)
14      .then(() => setValid(true))
15      .catch(() => setValid(false));
16  }, [token]);
17
18  async function submit(e: FormEvent<HTMLFormElement>) {
19    e.preventDefault();
20    const form = new FormData(e.currentTarget);
21    setError("");
22    try {
23      onJoin(
24        await api<User>("/claim", {
25          method: "POST",
26          body: JSON.stringify({
27            token,
28            username: form.get("username"),
29            password: form.get("password"),
30          }),
31        }),
32      );
33    } catch (err) {
34      setError((err as Error).message);
35    }
36  }
37
38  if (valid === null) {
39    return (
40      <div className="flex min-h-dvh">
41        <Centered>
42          <Spinner />
43        </Centered>
44      </div>
45    );
46  }
47  if (!valid) {
48    return (
49      <div className="flex min-h-dvh bg-bg">
50        <Centered>this invite is invalid or has expired</Centered>
51      </div>
52    );
53  }
54
55  return (
56    <AuthShell subtitle="create your account" onSubmit={submit}>
57      <TextInput
58        name="username"
59        placeholder="username"
60        autoFocus
61        autoComplete="username"
62      />
63      <TextInput
64        name="password"
65        type="password"
66        placeholder="password (min 8 characters)"
67        autoComplete="new-password"
68      />
69      {error && <p className="px-1 text-xs text-danger">{error}</p>}
70      <Button variant="primary" size="lg" type="submit" className="w-full">
71        join
72      </Button>
73    </AuthShell>
74  );
75}