Files
community-rule/app/components/modals/Login/LoginForm.tsx
T
adilallo 27d74e510c Show Login and Ask an organizer sent and error states.
Connect the live modals to the drawn sent, expired, invalid-email, and send-failed screens, pin the phone footer above the keyboard, and send the light login email.
2026-11-11 16:55:09 -07:00

380 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "../../../contexts/MessagesContext";
import Button from "../../buttons/Button";
import TextInput from "../../controls/TextInput";
import ContentLockup from "../../type/ContentLockup";
import Alert from "../Alert";
import { requestMagicLink } from "../../../../lib/create/api";
import { EMAIL_MAX_LEN } from "../../../../lib/create/isValidCreateFlowSaveEmail";
import { buildCreateFlowDraftPayload } from "../../../../lib/create/buildCreateFlowDraftPayload";
import { MAGIC_LINK_TTL_MINUTES } from "../../../../lib/privacyRetention";
import { safeInternalPath } from "../../../../lib/safeInternalPath";
import {
readAnonymousCreateFlowState,
setTransferPendingFlag,
} from "../../../(app)/create/utils/anonymousDraftStorage";
/** Mail icon for login modal (inline SVG; same pattern as InfoMessageBox ExclamationIconInline). */
function MailIconInline() {
return (
<svg
width={22}
height={22}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="shrink-0"
aria-hidden
data-name="Asset / Icon / mail"
>
<path
fill="#000000"
d="M1.5 8.67v8.58a3 3 0 0 0 3 3h15a3 3 0 0 0 3-3V8.67l-8.928 5.493a3 3 0 0 1-3.144 0L1.5 8.67Z"
/>
<path
fill="#000000"
d="M22.5 6.908V6.75A2.25 2.25 0 0 0 20.25 4.5h-16.5A2.25 2.25 0 0 0 1.5 6.75v.158l9.714 5.978a1.5 1.5 0 0 0 1.572 0L22.5 6.908Z"
/>
</svg>
);
}
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const LOGIN_FORM_ID = "login-magic-link-form";
export type LoginFormVariant =
| "default"
| "saveProgress"
| "keepRule"
| "invite";
function isExpiredLinkError(errorParam: string | null): boolean {
return errorParam === "expired_link" || errorParam === "invalid_link";
}
function loginFormHeading(
variant: LoginFormVariant,
sent: boolean,
linkExpired: boolean,
email: string,
t: (_key: string) => string,
): { title: string; description: string } {
if (sent) {
return {
title: t("successTitle"),
description: t("sentBody")
.replace("{email}", email)
.replace("{minutes}", String(MAGIC_LINK_TTL_MINUTES)),
};
}
if (linkExpired) {
return { title: t("expiredTitle"), description: t("expiredBody") };
}
if (variant === "saveProgress") {
return {
title: t("saveProgressTitle"),
description: t("saveProgressSubtitle"),
};
}
if (variant === "keepRule") {
return {
title: t("keepRuleTitle"),
description: t("keepRuleSubtitle"),
};
}
if (variant === "invite") {
return {
title: t("inviteTitle"),
description: t("inviteSubtitle"),
};
}
return { title: t("title"), description: t("subtitle") };
}
function shouldAttachCreateFlowDraft(
variant: LoginFormVariant,
nextPath: string,
): boolean {
if (variant === "keepRule") return false;
return (
variant === "saveProgress" ||
variant === "invite" ||
nextPath.includes("syncDraft=1")
);
}
export type LoginFormProps = {
variant?: LoginFormVariant;
/** Overrides URL `next` for `requestMagicLink` (e.g. create-flow exit modal). */
magicLinkNextPath?: string;
/** `keepRule`: Continue without saving. */
onDismiss?: () => void;
/** Sent-state Close, and the dialog chrome close. */
onClose?: () => void;
};
export default function LoginForm({
variant = "default",
magicLinkNextPath,
onDismiss,
onClose,
}: LoginFormProps) {
const t = useTranslation("pages.login");
const tFooter = useTranslation("footer");
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [email, setEmail] = useState("");
const [submitting, setSubmitting] = useState(false);
const [emailError, setEmailError] = useState("");
const [formError, setFormError] = useState("");
const [sent, setSent] = useState(false);
const [linkExpired, setLinkExpired] = useState(() =>
isExpiredLinkError(searchParams.get("error")),
);
const nextParam = searchParams.get("next");
const errorParam = searchParams.get("error");
const heading = loginFormHeading(variant, sent, linkExpired, email, t);
/** Drop `error` from the URL so URL-driven messages don’t linger after a new attempt. */
const stripErrorQuery = useCallback(() => {
if (!searchParams.get("error")) return;
const params = new URLSearchParams(searchParams.toString());
params.delete("error");
const q = params.toString();
router.replace(q ? `${pathname}?${q}` : pathname, { scroll: false });
}, [pathname, router, searchParams]);
const sendLink = useCallback(async () => {
stripErrorQuery();
setEmailError("");
setFormError("");
const trimmed = email.trim().toLowerCase();
if (!EMAIL_PATTERN.test(trimmed)) {
setEmailError(t("errors.emailInvalid"));
return;
}
setSubmitting(true);
try {
const rawNext = magicLinkNextPath ?? nextParam;
const nextPath = safeInternalPath(rawNext);
const shouldAttachDraft = shouldAttachCreateFlowDraft(variant, nextPath);
const localDraft = readAnonymousCreateFlowState();
const draft =
shouldAttachDraft && Object.keys(localDraft).length > 0
? buildCreateFlowDraftPayload(localDraft)
: undefined;
const result = await requestMagicLink(trimmed, nextPath, draft);
if (result.ok === false) {
if (result.retryAfterMs != null && result.retryAfterMs > 0) {
const seconds = Math.ceil(result.retryAfterMs / 1000);
setFormError(
t("errors.rateLimited").replace("{seconds}", String(seconds)),
);
} else {
setFormError(result.error || t("errors.generic"));
}
return;
}
if (shouldAttachDraft) {
setTransferPendingFlag();
}
setEmail(trimmed);
setLinkExpired(false);
setSent(true);
} catch {
setFormError(t("errors.network"));
} finally {
setSubmitting(false);
}
}, [
email,
magicLinkNextPath,
nextParam,
stripErrorQuery,
t,
variant,
]);
useEffect(() => {
if (isExpiredLinkError(errorParam)) {
setLinkExpired(true);
}
}, [errorParam]);
const urlErrorMessage =
errorParam === "stakeholder_wrong_account"
? t("errors.stakeholderWrongAccount")
: errorParam === "server"
? t("errors.serverError")
: "";
const titleId = "login-modal-heading";
const submitLabel = linkExpired ? t("sendNewLink") : t("sendMagicLink");
return (
<div className="flex min-h-0 flex-1 flex-col gap-6 pt-2">
<div className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto">
<div className="flex flex-col gap-3">
<div className="relative flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-[var(--color-surface-invert-brand-primary)]">
<MailIconInline />
</div>
<ContentLockup
titleId={titleId}
title={heading.title}
description={heading.description}
variant="login"
alignment="left"
/>
</div>
{(urlErrorMessage || formError) && (
<div className="pointer-events-none fixed inset-x-0 top-4 z-[10000] flex justify-center px-4 md:top-6">
<div className="pointer-events-auto flex w-full max-w-[560px] flex-col gap-2">
{urlErrorMessage ? (
<Alert
type="banner"
status="danger"
size="s"
title={urlErrorMessage}
hasBodyText={false}
hasLeadingIcon
onClose={() => {
stripErrorQuery();
}}
className="w-full"
/>
) : null}
{formError ? (
<Alert
type="banner"
status="danger"
size="s"
title={formError}
hasBodyText={false}
hasLeadingIcon
onClose={() => {
setFormError("");
}}
className="w-full"
/>
) : null}
</div>
</div>
)}
{!sent ? (
<form
id={LOGIN_FORM_ID}
className="flex flex-col gap-4"
onSubmit={(e) => {
e.preventDefault();
void sendLink();
}}
noValidate
>
<TextInput
label={t("emailLabel")}
placeholder={t("emailPlaceholder")}
type="email"
name="email"
autoComplete="email"
inputMode="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
setEmailError("");
stripErrorQuery();
}}
disabled={submitting}
error={Boolean(emailError)}
textHint={emailError || false}
showHelpIcon={false}
maxLength={EMAIL_MAX_LEN}
/>
</form>
) : null}
</div>
<div className="flex shrink-0 flex-col gap-4">
{sent ? (
<>
<Button
type="button"
size="large"
buttonType="filled"
palette="default"
autoFocus
onClick={() => onClose?.()}
className="w-full !justify-center text-center px-[var(--space-400)] py-[var(--space-300)]"
>
{t("close")}
</Button>
<button
type="button"
onClick={() => {
void sendLink();
}}
disabled={submitting}
className="text-center text-small-paragraph text-[var(--color-content-default-tertiary)] underline decoration-solid underline-offset-2"
>
{t("sendAgain")}
</button>
</>
) : (
<>
<Button
type="submit"
form={LOGIN_FORM_ID}
size="large"
buttonType="filled"
palette="default"
disabled={submitting}
className="w-full !justify-center text-center px-[var(--space-400)] py-[var(--space-300)]"
>
{submitLabel}
</Button>
{onDismiss ? (
<Button
type="button"
size="large"
buttonType="ghost"
palette="default"
disabled={submitting}
onClick={onDismiss}
className="w-full !justify-center text-center px-[var(--space-400)] py-[var(--space-300)]"
>
{t("continueWithoutSaving")}
</Button>
) : null}
<p className="text-center text-small-paragraph text-[var(--color-content-default-tertiary)]">
{t("legalPrefix")}
<Link
href={tFooter("legal.termsOfServiceHref")}
className="text-[var(--color-content-default-tertiary)] underline decoration-solid underline-offset-2"
>
{tFooter("legal.termsOfService")}
</Link>
{t("legalAnd")}
<Link
href={tFooter("legal.privacyPolicyHref")}
className="text-[var(--color-content-default-tertiary)] underline decoration-solid underline-offset-2"
>
{tFooter("legal.privacyPolicy")}
</Link>
{t("legalSuffix")}
</p>
</>
)}
</div>
</div>
);
}