import { Button, Input, LinkButton } from "@refs/design-system"; import { MIN_PASSWORD_LENGTH } from "@refs/backend/contract"; import { refsErrorCode, type PendingInvitation } from "@refs/backend/contract"; import { Form, data, redirect, useNavigation } from "react-router"; import type { Route } from "./+types/invite"; import { AuthPage } from "../components/shell"; import { failed, formText, found, gate, namespaceCookie, refs, sessionCookie } from "../lib/session"; async function pending(context: Route.LoaderArgs["context"], token: string): Promise { return gate(context) .invitation(token) .catch((error) => { if (refsErrorCode(error) === "not_found") return null; throw error; }); } export const meta: Route.MetaFunction = () => [{ title: "Join ยท refs" }]; export async function loader({ params, context }: Route.LoaderArgs) { const invite = await pending(context, params.token); const viewer = refs(context).viewer.person; return data( { org: invite?.org.name ?? "refs", email: invite?.email ?? null, existingAccount: invite?.existingAccount ?? false, viewer: viewer && { name: viewer.name, email: viewer.email }, token: params.token }, { status: invite ? 200 : 404 }, ); } export async function action({ request, params, context }: Route.ActionArgs) { const invite = await pending(context, params.token); if (!invite) return data({ error: "This invitation is no longer valid.", name: "", handle: "" }, { status: 404 }); const form = await request.formData(); if (formText(form, "intent") === "join") { const joined = await found(refs(context).acceptInvitation(params.token)); if (!joined.ok) return failed(joined.problem, { name: "", handle: "" }); throw redirect(`/${joined.value.slug}`, { headers: { "Set-Cookie": namespaceCookie(joined.value.slug) } }); } const name = formText(form, "name"); const handle = formText(form, "handle").toLowerCase(); const outcome = await invite.accept({ name, handle, password: String(form.get("password") ?? "") }); if (!outcome.ok) return failed(outcome.problem, { name, handle }); throw redirect("/", { headers: { "Set-Cookie": sessionCookie(outcome.value) } }); } export default function Invite({ loaderData, actionData }: Route.ComponentProps) { const submitting = useNavigation().state === "submitting"; if (!loaderData.email) { return ( Go to sign in ); } if (loaderData.viewer) { const matches = loaderData.viewer.email.toLowerCase() === loaderData.email.toLowerCase(); return ( {matches ? (

Join as {loaderData.viewer.name} ({loaderData.viewer.email}).

) : (

This invitation is for {loaderData.email}, and you're signed in as {loaderData.viewer.email}. Sign out, then sign in as {loaderData.email} to accept it.

)}
); } if (loaderData.existingAccount) { return (

{loaderData.email} already has an account. Sign in to accept the invitation.

Sign in to accept
); } return (
); }