Show Login and Ask an organizer sent and error states #107

Merged
an.di merged 2 commits from adilallo/feature/CR-303-login-ask-organizer-states into main 2026-11-12 22:17:14 +00:00
31 changed files with 878 additions and 168 deletions

No files matched your search

+5 -4
View File
@@ -28,6 +28,9 @@ function LoginLoadingFallback() {
function LoginWithSearchParams() {
const router = useRouter();
const t = useTranslation("pages.login");
const closeToHome = () => {
router.push("/");
};
return (
<div className={loginPageBgClass}>
@@ -35,9 +38,7 @@ function LoginWithSearchParams() {
isOpen
usePortal={false}
backdropVariant="solid"
onClose={() => {
router.push("/");
}}
onClose={closeToHome}
ariaLabelledBy="login-modal-heading"
belowCard={
<Link
@@ -48,7 +49,7 @@ function LoginWithSearchParams() {
</Link>
}
>
<LoginForm />
<LoginForm onClose={closeToHome} />
</Login>
</div>
);
+1 -1
View File
@@ -104,7 +104,7 @@ export const POST = apiRoute(SCOPE, async (request: NextRequest, _ctx, { request
const verifyUrl = `${origin}/api/auth/magic-link/verify?token=${encodeURIComponent(token)}`;
try {
await sendMagicLinkEmail(email, verifyUrl);
await sendMagicLinkEmail(email, verifyUrl, origin);
} catch (err) {
logRouteError(SCOPE, requestId, err, { phase: "sendMagicLinkEmail" });
await prisma.magicLinkToken.deleteMany({ where: { email } });
@@ -1,8 +1,8 @@
"use client";
/**
* Figma: Community Rule System — Modal / Ask an Organizer (22078-587823)
* File: agv0VBLiBlcnSAaiAORgPR, node 22078-587823
* Figma: Overlay / Modal / Ask an Organizer (22078:587823)
* Sent 25032:48584, send failed 25032:48642
*/
import { memo, useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
@@ -11,6 +11,8 @@ import type { AskOrganizerInquiryModalProps } from "./AskOrganizerInquiryModal.t
import { ORGANIZER_INQUIRY_HONEYPOT_FIELD } from "../../../../lib/organizerInquiryConstants";
import { useTranslation } from "../../../contexts/MessagesContext";
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
({ isOpen, onClose }) => {
const t = useTranslation("modals.askOrganizerInquiry");
@@ -21,12 +23,16 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
description: t("description"),
emailLabel: t("emailLabel"),
emailPlaceholder: t("emailPlaceholder"),
emailInvalid: t("emailInvalid"),
questionLabel: t("questionLabel"),
questionPlaceholder: t("questionPlaceholder"),
questionTooShort: t("questionTooShort"),
submitButton: t("submitButton"),
closeAfterSuccess: t("closeAfterSuccess"),
successTitle: t("successTitle"),
successDescription: t("successDescription"),
sendFailedTitle: t("sendFailedTitle"),
sendFailedDescription: t("sendFailedDescription"),
ariaDialog: t("ariaDialog"),
honeypotLabel: t("honeypotLabel"),
backToHome: tLogin("backToHome"),
@@ -38,7 +44,7 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
const [honeypot, setHoneypot] = useState("");
const [submitting, setSubmitting] = useState(false);
const [success, setSuccess] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [sendFailed, setSendFailed] = useState(false);
const [emailError, setEmailError] = useState(false);
const [questionError, setQuestionError] = useState(false);
@@ -49,18 +55,40 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
setHoneypot("");
setSubmitting(false);
setSuccess(false);
setFormError(null);
setSendFailed(false);
setEmailError(false);
setQuestionError(false);
}
}, [isOpen]);
const onEmailChange = useCallback((value: string) => {
setEmail(value);
setEmailError(false);
}, []);
const onMessageChange = useCallback((value: string) => {
setMessage(value);
setQuestionError(false);
}, []);
const onSubmit = useCallback(
async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setFormError(null);
setSendFailed(false);
setEmailError(false);
setQuestionError(false);
const trimmedEmail = email.trim().toLowerCase();
const trimmedMessage = message.trim();
if (!EMAIL_PATTERN.test(trimmedEmail)) {
setEmailError(true);
return;
}
if (trimmedMessage.length < 10) {
setQuestionError(true);
return;
}
setSubmitting(true);
try {
@@ -68,8 +96,8 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
email,
message,
email: trimmedEmail,
message: trimmedMessage,
[ORGANIZER_INQUIRY_HONEYPOT_FIELD]: honeypot,
}),
});
@@ -81,11 +109,9 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
return;
}
if (res.status === 429) {
setFormError(t("rateLimitedError"));
return;
}
if (res.status === 400) {
let nextEmailError = false;
let nextQuestionError = false;
if (
data &&
typeof data === "object" &&
@@ -98,23 +124,28 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
const msg = (data.error as { message: string }).message;
const lower = msg.toLowerCase();
if (lower.includes("email")) {
setEmailError(true);
nextEmailError = true;
}
if (lower.includes("character") || lower.includes("question")) {
setQuestionError(true);
nextQuestionError = true;
}
}
setEmailError(nextEmailError);
setQuestionError(nextQuestionError);
if (!nextEmailError && !nextQuestionError) {
setSendFailed(true);
}
setFormError(msg);
return;
}
setFormError(t("genericError"));
setSendFailed(true);
} catch {
setFormError(t("genericError"));
setSendFailed(true);
} finally {
setSubmitting(false);
}
},
[email, message, honeypot, t],
[email, message, honeypot],
);
return (
@@ -127,13 +158,14 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
honeypot={honeypot}
submitting={submitting}
success={success}
formError={formError}
sendFailed={sendFailed}
emailError={emailError}
questionError={questionError}
onEmailChange={setEmail}
onMessageChange={setMessage}
onEmailChange={onEmailChange}
onMessageChange={onMessageChange}
onHoneypotChange={setHoneypot}
onSubmit={onSubmit}
onDismissFailed={() => setSendFailed(false)}
/>
);
},
@@ -8,12 +8,16 @@ export interface AskOrganizerInquiryModalCopy {
description: string;
emailLabel: string;
emailPlaceholder: string;
emailInvalid: string;
questionLabel: string;
questionPlaceholder: string;
questionTooShort: string;
submitButton: string;
closeAfterSuccess: string;
successTitle: string;
successDescription: string;
sendFailedTitle: string;
sendFailedDescription: string;
ariaDialog: string;
honeypotLabel: string;
backToHome: string;
@@ -27,11 +31,12 @@ export interface AskOrganizerInquiryModalViewProps
honeypot: string;
submitting: boolean;
success: boolean;
formError: string | null;
sendFailed: boolean;
emailError: boolean;
questionError: boolean;
onEmailChange: (_v: string) => void;
onMessageChange: (_v: string) => void;
onHoneypotChange: (_v: string) => void;
onSubmit: (_e: import("react").FormEvent<HTMLFormElement>) => void;
onDismissFailed: () => void;
}
@@ -5,6 +5,7 @@ import Create from "../Create";
import TextInput from "../../controls/TextInput";
import TextArea from "../../controls/TextArea";
import Button from "../../buttons/Button";
import Alert from "../Alert";
import {
ASK_ORGANIZER_INQUIRY_FORM_ID,
ORGANIZER_INQUIRY_HONEYPOT_FIELD,
@@ -12,7 +13,8 @@ import {
import type { AskOrganizerInquiryModalViewProps } from "./AskOrganizerInquiryModal.types";
/**
* Figma: Community Rule System — Modal / Ask an Organizer (22078-587823)
* Figma: Overlay / Modal / Ask an Organizer (22078:587823)
* Sent 25032:48584, send failed 25032:48642
*/
export function AskOrganizerInquiryModalView({
isOpen,
@@ -23,29 +25,46 @@ export function AskOrganizerInquiryModalView({
honeypot,
submitting,
success,
formError,
sendFailed,
emailError,
questionError,
onEmailChange,
onMessageChange,
onHoneypotChange,
onSubmit,
onDismissFailed,
}: AskOrganizerInquiryModalViewProps) {
const footer = success ? (
<div className="w-full px-1">
const failedToast = sendFailed ? (
<Alert
type="toast"
status="danger"
size="s"
title={copy.sendFailedTitle}
description={copy.sendFailedDescription}
hasLeadingIcon
hasBodyText
hasTrailingIcon={false}
onClose={onDismissFailed}
className="w-full"
/>
) : null;
const footer = (
<div className="flex w-full flex-col gap-4 px-1">
<div className="md:hidden">{failedToast}</div>
{success ? (
<Button
type="button"
buttonType="filled"
palette="default"
size="large"
className="w-full !justify-center"
autoFocus
onClick={onClose}
>
{copy.closeAfterSuccess}
</Button>
</div>
) : (
<div className="w-full px-1">
<Button
type="submit"
form={ASK_ORGANIZER_INQUIRY_FORM_ID}
@@ -57,6 +76,7 @@ export function AskOrganizerInquiryModalView({
>
{copy.submitButton}
</Button>
)}
</div>
);
@@ -64,9 +84,10 @@ export function AskOrganizerInquiryModalView({
<Create
isOpen={isOpen}
onClose={onClose}
presentation="sheet"
backdropVariant="blurredYellow"
title={copy.title}
description={copy.description}
title={success ? copy.successTitle : copy.title}
description={success ? copy.successDescription : copy.description}
showBackButton={false}
showNextButton={false}
stepper={false}
@@ -74,6 +95,9 @@ export function AskOrganizerInquiryModalView({
footerContent={footer}
footerClassName="!h-auto min-h-[112px] shrink-0 flex flex-col justify-end pb-8 pt-3 px-4"
belowCard={
success ? undefined : (
<div className="flex w-full max-w-[546px] flex-col items-center gap-6">
<div className="hidden w-full md:block">{failedToast}</div>
<Link
href="/"
className="text-small-paragraph text-[var(--color-content-invert-tertiary,#2d2d2d)] text-center hover:opacity-90"
@@ -81,33 +105,17 @@ export function AskOrganizerInquiryModalView({
>
{copy.backToHome}
</Link>
</div>
)
}
>
{success ? (
<div className="flex flex-col gap-3 py-2">
<p className="text-large-label text-[var(--color-content-default-primary)]">
{copy.successTitle}
</p>
<p className="text-small-paragraph text-[var(--color-content-default-secondary)]">
{copy.successDescription}
</p>
</div>
) : (
{success ? null : (
<form
id={ASK_ORGANIZER_INQUIRY_FORM_ID}
className="relative flex flex-col gap-6 pb-2"
onSubmit={onSubmit}
noValidate
>
{formError ? (
<p
role="alert"
className="text-small-paragraph text-[var(--color-border-default-negative-primary)]"
>
{formError}
</p>
) : null}
<TextInput
type="email"
name="email"
@@ -117,6 +125,7 @@ export function AskOrganizerInquiryModalView({
value={email}
onChange={(e) => onEmailChange(e.target.value)}
error={emailError}
textHint={emailError ? copy.emailInvalid : false}
inputSize="medium"
showHelpIcon={false}
/>
@@ -128,6 +137,7 @@ export function AskOrganizerInquiryModalView({
value={message}
onChange={(e) => onMessageChange(e.target.value)}
error={questionError}
textHint={questionError ? copy.questionTooShort : false}
size="medium"
appearance="embedded"
rows={4}
@@ -5,6 +5,7 @@
*/
import { memo, useRef } from "react";
import { useVisualViewportHeight } from "../../../hooks";
import { CreateView } from "./Create.view";
import type { CreateProps } from "./Create.types";
import { useCreateModalA11y } from "./useCreateModalA11y";
@@ -43,9 +44,13 @@ const CreateContainer = memo<CreateProps>(
kebabMenuAriaLabel,
kebabMenuItems,
belowCard,
presentation = "dialog",
}) => {
const createRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(null);
const viewport = useVisualViewportHeight(
isOpen && presentation === "sheet",
);
useCreateModalA11y(isOpen, onClose, createRef);
@@ -86,6 +91,9 @@ const CreateContainer = memo<CreateProps>(
kebabMenuAriaLabel={kebabMenuAriaLabel}
kebabMenuItems={kebabMenuItems}
belowCard={belowCard}
presentation={presentation}
viewportHeight={viewport?.height}
viewportOffsetTop={viewport?.offsetTop}
/>
);
},
+10 -1
View File
@@ -1,5 +1,8 @@
import type { RefObject } from "react";
import type { CreateModalBackdropVariant } from "./CreateModalFrame.view";
import type {
CreateModalBackdropVariant,
CreateModalPresentationValue,
} from "./CreateModalFrame.view";
import type { ModalHeaderMenuItem } from "../ModalHeader/ModalHeader.types";
export interface CreateProps {
@@ -51,6 +54,8 @@ export interface CreateProps {
kebabMenuItems?: ModalHeaderMenuItem[];
/** Rendered below the dialog card on the backdrop (e.g. “Back to home”). */
belowCard?: React.ReactNode;
/** `sheet` is the phone full-viewport layout used by Ask an organizer. */
presentation?: CreateModalPresentationValue;
}
export interface CreateViewProps {
@@ -88,4 +93,8 @@ export interface CreateViewProps {
kebabMenuAriaLabel?: string;
kebabMenuItems?: ModalHeaderMenuItem[];
belowCard?: React.ReactNode;
presentation: CreateModalPresentationValue;
viewportHeight?: number;
/** `visualViewport.offsetTop`, so a phone sheet tracks the visible region on iOS. */
viewportOffsetTop?: number;
}
@@ -41,6 +41,9 @@ export function CreateView({
kebabMenuAriaLabel,
kebabMenuItems,
belowCard,
presentation,
viewportHeight,
viewportOffsetTop,
}: CreateViewProps) {
return (
<CreateModalFrameView
@@ -53,6 +56,9 @@ export function CreateView({
overlayRef={overlayRef}
dialogRef={createRef}
belowCard={belowCard}
presentation={presentation}
viewportHeight={viewportHeight}
viewportOffsetTop={viewportOffsetTop}
>
<ModalHeader
onClose={onClose}
@@ -31,6 +31,10 @@ export type CreateModalFrameViewProps = {
* from `md`. `dialog` is the centered card used by Create and Dialog.
*/
presentation?: CreateModalPresentationValue;
/** Visible viewport height so a phone sheet footer rides above the keyboard. */
viewportHeight?: number;
/** `visualViewport.offsetTop`, so the sheet tracks the visible region on iOS. */
viewportOffsetTop?: number;
};
/**
@@ -48,6 +52,8 @@ export function CreateModalFrameView({
children,
belowCard,
presentation = "dialog",
viewportHeight,
viewportOffsetTop,
}: CreateModalFrameViewProps) {
if (!isOpen) return null;
@@ -55,14 +61,26 @@ export function CreateModalFrameView({
const overlayLayout = isSheet
? "flex flex-col items-stretch justify-end overflow-hidden p-0 md:items-center md:justify-center md:gap-6 md:overflow-y-auto md:px-4 md:py-8"
: "flex flex-col items-center justify-center gap-6 overflow-y-auto px-4 py-8";
const sheetHeight =
viewportHeight != null ? "h-full max-h-full" : "h-dvh max-h-dvh";
const dialogShell = isSheet
? "flex h-dvh max-h-dvh min-h-0 w-full shrink-0 flex-col overflow-hidden rounded-none bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] md:h-auto md:max-h-[90vh] md:w-[546px] md:max-w-[546px] md:rounded-[var(--radius-500)]"
? `flex ${sheetHeight} min-h-0 w-full shrink-0 flex-col overflow-hidden rounded-none bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] md:h-auto md:max-h-[90vh] md:w-[546px] md:max-w-[546px] md:rounded-[var(--radius-500)]`
: "flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999]";
const overlayStyle =
isSheet && viewportHeight != null
? {
top: viewportOffsetTop ?? 0,
bottom: "auto" as const,
height: viewportHeight,
maxHeight: viewportHeight,
}
: undefined;
const content = (
<div
ref={overlayRef}
className={`${backdropOverlayClasses[backdropVariant]} ${overlayLayout}`}
style={overlayStyle}
onClick={onOverlayClick}
role="presentation"
>
@@ -78,7 +96,10 @@ export function CreateModalFrameView({
{children}
</div>
{belowCard ? (
<div className="shrink-0" onClick={(e) => e.stopPropagation()}>
<div
className={`shrink-0 ${isSheet ? "hidden md:block" : ""}`}
onClick={(e) => e.stopPropagation()}
>
{belowCard}
</div>
) : null}
@@ -6,6 +6,20 @@ import { useEffect, useLayoutEffect, useRef } from "react";
const FOCUSABLE_SELECTOR =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const FIELD_SELECTOR =
'input:not([type="hidden"]):not([type="checkbox"]):not([disabled]):not([tabindex="-1"]), textarea:not([disabled]):not([tabindex="-1"])';
function initialFocus(dialog: HTMLElement): HTMLElement | undefined {
const email = dialog.querySelector<HTMLElement>(
'input[type="email"]:not([disabled]):not([tabindex="-1"])',
);
if (email) return email;
const field = dialog.querySelector<HTMLElement>(FIELD_SELECTOR);
if (field) return field;
const focusable = dialog.querySelectorAll(FOCUSABLE_SELECTOR);
return focusable[0] as HTMLElement | undefined;
}
let lastInteractedFocusable: HTMLElement | null = null;
let interactionTrackingBound = false;
@@ -118,10 +132,7 @@ export function useCreateModalA11y(
document.body.style.overflow = "hidden";
if (dialogRef.current) {
const focusableElements = dialogRef.current.querySelectorAll(
FOCUSABLE_SELECTOR,
);
const firstElement = focusableElements[0] as HTMLElement | undefined;
const firstElement = initialFocus(dialogRef.current);
if (firstElement) {
firstElement.focus();
} else {
@@ -1,10 +1,12 @@
"use client";
/**
* Figma: "Modal / Login" (see registry)
* Figma: Overlay / Modal / Login (22078:587823)
* Sent 25032:48263, link expired 25032:48370, invalid email 25032:48477
*/
import { memo, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useVisualViewportHeight } from "../../../hooks";
import { LoginView } from "./Login.view";
import type { LoginProps } from "./Login.types";
@@ -24,9 +26,7 @@ const LoginContainer = memo<LoginProps>(
const backdropRef = useRef<HTMLDivElement>(null);
const previousActiveElementRef = useRef<HTMLElement | null>(null);
const [portalReady, setPortalReady] = useState(() => !usePortal);
const [viewportHeight, setViewportHeight] = useState<number | undefined>(
undefined,
);
const viewport = useVisualViewportHeight(isOpen);
// Defer enabling the portal until after the layout commit so we don’t sync-setState
// inside the effect (eslint react-hooks/set-state-in-effect) while still mounting
@@ -39,24 +39,6 @@ const LoginContainer = memo<LoginProps>(
return () => cancelAnimationFrame(id);
}, [usePortal]);
useEffect(() => {
if (!isOpen) return;
const vp = window.visualViewport;
const sync = () => {
const next = vp?.height ?? window.innerHeight;
setViewportHeight(next);
};
sync();
vp?.addEventListener("resize", sync);
vp?.addEventListener("scroll", sync);
window.addEventListener("resize", sync);
return () => {
vp?.removeEventListener("resize", sync);
vp?.removeEventListener("scroll", sync);
window.removeEventListener("resize", sync);
};
}, [isOpen]);
useEffect(() => {
if (!isOpen) return;
if (usePortal && !portalReady) return;
@@ -153,7 +135,8 @@ const LoginContainer = memo<LoginProps>(
portalReady={portalReady}
usePortal={usePortal}
backdropVariant={backdropVariant}
viewportHeight={viewportHeight}
viewportHeight={viewport?.height}
viewportOffsetTop={viewport?.offsetTop}
>
{children}
</LoginView>
@@ -35,4 +35,6 @@ export interface LoginViewProps {
backdropVariant: LoginBackdropVariant;
/** Visible viewport height on phones so the footer rides above the keyboard. */
viewportHeight?: number;
/** `visualViewport.offsetTop`, so the sheet tracks the visible region on iOS. */
viewportOffsetTop?: number;
}
+24 -11
View File
@@ -24,19 +24,34 @@ export function LoginView({
usePortal,
backdropVariant,
viewportHeight,
viewportOffsetTop,
}: LoginViewProps) {
if (!isOpen) return null;
if (usePortal && !portalReady) return null;
const phoneSheetStyle =
viewportHeight != null
? { height: viewportHeight, maxHeight: viewportHeight }
? {
top: viewportOffsetTop ?? 0,
bottom: "auto" as const,
height: viewportHeight,
maxHeight: viewportHeight,
}
: undefined;
const belowCardLink = belowCard ? (
<div
className="shrink-0 text-center"
onClick={(e) => e.stopPropagation()}
>
{belowCard}
</div>
) : null;
const content = (
<div
ref={backdropRef}
className={`fixed inset-0 z-[9998] flex flex-col items-center gap-6 overflow-y-auto px-4 py-8 max-md:justify-end max-md:overflow-hidden max-md:px-0 max-md:py-0 md:justify-center ${backdropClasses[backdropVariant]}`}
className={`fixed inset-0 z-[9998] flex flex-col items-center gap-6 overflow-y-auto px-4 py-8 max-md:items-stretch max-md:justify-end max-md:overflow-hidden max-md:px-0 max-md:py-0 md:justify-center ${backdropClasses[backdropVariant]}`}
style={phoneSheetStyle}
onPointerDown={(event) => {
if (event.target !== event.currentTarget) return;
@@ -50,21 +65,19 @@ export function LoginView({
aria-modal="true"
aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy}
className={`flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] max-md:max-h-full max-md:rounded-b-none ${className}`}
className={`flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] max-md:h-full max-md:max-h-full max-md:max-w-none max-md:rounded-none ${className}`}
onClick={(e) => e.stopPropagation()}
>
<ModalHeader onClose={onClose} showMoreOptionsButton={false} />
<div className="scrollbar-design flex min-h-0 flex-1 flex-col overflow-x-clip overflow-y-auto px-6 pb-8 pt-0">
<div className="flex min-h-0 flex-1 flex-col overflow-hidden px-6 pb-8 pt-0">
{children}
{belowCardLink ? (
<div className="shrink-0 pt-4 md:hidden">{belowCardLink}</div>
) : null}
</div>
</div>
{belowCard ? (
<div
className="shrink-0 max-md:w-full max-md:bg-[var(--color-surface-default-primary)] max-md:px-6 max-md:pb-6"
onClick={(e) => e.stopPropagation()}
>
{belowCard}
</div>
{belowCardLink ? (
<div className="hidden md:block">{belowCardLink}</div>
) : null}
</div>
);
+78 -25
View File
@@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
import { useCallback, useId, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "../../../contexts/MessagesContext";
import Button from "../../buttons/Button";
@@ -11,6 +11,7 @@ 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,
@@ -43,6 +44,7 @@ function MailIconInline() {
}
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const LOGIN_FORM_ID = "login-magic-link-form";
export type LoginFormVariant =
| "default"
@@ -50,13 +52,27 @@ export type LoginFormVariant =
| "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("successBody") };
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 {
@@ -97,30 +113,35 @@ export type LoginFormProps = {
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 emailErrorId = useId();
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, t);
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(() => {
@@ -137,6 +158,7 @@ export default function LoginForm({
setFormError("");
const trimmed = email.trim().toLowerCase();
if (!EMAIL_PATTERN.test(trimmed)) {
setSent(false);
setEmailError(t("errors.emailInvalid"));
return;
}
@@ -152,6 +174,7 @@ export default function LoginForm({
: undefined;
const result = await requestMagicLink(trimmed, nextPath, draft);
if (result.ok === false) {
setSent(false);
if (result.retryAfterMs != null && result.retryAfterMs > 0) {
const seconds = Math.ceil(result.retryAfterMs / 1000);
setFormError(
@@ -166,8 +189,10 @@ export default function LoginForm({
setTransferPendingFlag();
}
setEmail(trimmed);
setLinkExpired(false);
setSent(true);
} catch {
setSent(false);
setFormError(t("errors.network"));
} finally {
setSubmitting(false);
@@ -181,21 +206,25 @@ export default function LoginForm({
variant,
]);
useEffect(() => {
if (isExpiredLinkError(errorParam)) {
setLinkExpired(true);
}
}, [errorParam]);
const urlErrorMessage =
errorParam === "expired_link"
? t("errors.expiredLink")
: errorParam === "stakeholder_wrong_account"
errorParam === "stakeholder_wrong_account"
? t("errors.stakeholderWrongAccount")
: errorParam === "invalid_link" || errorParam === "server"
? errorParam === "server"
: errorParam === "server"
? t("errors.serverError")
: t("errors.invalidLink")
: "";
const titleId = "login-modal-heading";
const submitLabel = linkExpired ? t("sendNewLink") : t("sendMagicLink");
return (
<div className="flex flex-col gap-6 pt-2">
<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 />
@@ -246,6 +275,7 @@ export default function LoginForm({
{!sent ? (
<form
id={LOGIN_FORM_ID}
className="flex flex-col gap-4"
onSubmit={(e) => {
e.preventDefault();
@@ -263,33 +293,56 @@ export default function LoginForm({
value={email}
onChange={(e) => {
setEmail(e.target.value);
setEmailError("");
stripErrorQuery();
}}
disabled={submitting}
error={Boolean(emailError)}
showHelpIcon
textHint={emailError || false}
showHelpIcon={false}
maxLength={EMAIL_MAX_LEN}
/>
{emailError ? (
<p
id={emailErrorId}
role="alert"
aria-live="polite"
className="text-[14px] text-[var(--color-border-default-utility-negative)]"
>
{emailError}
</p>
</form>
) : null}
<div className="flex flex-col gap-4 max-md:sticky max-md:bottom-0 max-md:bg-[var(--color-surface-default-primary)] max-md:pt-2">
</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)]"
>
{t("sendMagicLink")}
{submitLabel}
</Button>
{onDismiss ? (
<Button
@@ -321,9 +374,9 @@ export default function LoginForm({
</Link>
{t("legalSuffix")}
</p>
</>
)}
</div>
</form>
) : null}
</div>
);
}
+1
View File
@@ -94,6 +94,7 @@ export function AuthModalProvider({ children }: { children: ReactNode }) {
variant={opts.variant ?? "default"}
magicLinkNextPath={opts.nextPath}
onDismiss={keepRuleDismiss}
onClose={closeLogin}
/>
</Login>
</AuthModalContext.Provider>
+1
View File
@@ -19,6 +19,7 @@ export { useMediaQuery,
export { useAsyncConfirm } from "./useAsyncConfirm";
export type { AsyncConfirmOptions } from "./useAsyncConfirm";
export { useBeforeUnloadGuard } from "./useBeforeUnloadGuard";
export { useVisualViewportHeight } from "./useVisualViewportHeight";
export type {
SchemaOrganization,
SchemaWebSite,
+51
View File
@@ -0,0 +1,51 @@
import { useEffect, useState } from "react";
/**
* Visible viewport box, including the shrink and offset when a phone keyboard opens.
*
* iOS Safari reports the keyboard by shrinking `visualViewport.height` and
* shifting `offsetTop`. A `fixed` overlay has to use both, or its footer stays
* in the layout viewport behind the keyboard.
*
* @param enabled When false, skip listeners and return `undefined`.
* @returns Height and top offset of `visualViewport`, or `undefined` when disabled.
*
* @example
* const viewport = useVisualViewportHeight(isOpen);
*/
export function useVisualViewportHeight(
enabled: boolean,
): { height: number; offsetTop: number } | undefined {
const [frame, setFrame] = useState<
{ height: number; offsetTop: number } | undefined
>(undefined);
useEffect(() => {
if (!enabled) return;
const vp = window.visualViewport;
const sync = () => {
const next = {
height: vp?.height ?? window.innerHeight,
offsetTop: vp?.offsetTop ?? 0,
};
setFrame((prev) =>
prev &&
prev.height === next.height &&
prev.offsetTop === next.offsetTop
? prev
: next,
);
};
sync();
vp?.addEventListener("resize", sync);
vp?.addEventListener("scroll", sync);
window.addEventListener("resize", sync);
return () => {
vp?.removeEventListener("resize", sync);
vp?.removeEventListener("scroll", sync);
window.removeEventListener("resize", sync);
};
}, [enabled]);
return enabled ? frame : undefined;
}
+123
View File
@@ -0,0 +1,123 @@
import { ASSETS, getAssetPath } from "../assetUtils";
import { MAGIC_LINK_TTL_MINUTES } from "../privacyRetention";
export const MAGIC_LINK_LOGO_PATH = getAssetPath(ASSETS.LOGO_MARK);
export type MagicLinkMailInput = {
verifyUrl: string;
origin: string;
};
export type MagicLinkMailContent = {
subject: string;
previewText: string;
text: string;
html: string;
};
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function originHost(origin: string): string {
try {
return new URL(origin).host;
} catch {
return origin.replace(/^https?:\/\//, "").replace(/\/$/, "");
}
}
export function buildMagicLinkMail(
input: MagicLinkMailInput,
): MagicLinkMailContent {
const origin = input.origin.replace(/\/$/, "");
const minutes = MAGIC_LINK_TTL_MINUTES;
const subject = "Your login link for CommunityRule";
const previewText = `It works once, for ${minutes} minutes.`;
const heading = "Log in to CommunityRule";
const intro = `Use the button to log in. It works once, for ${minutes} minutes.`;
const ignore =
"If you did not ask to log in, ignore this email. Nobody can log in without the link.";
const madeBy =
"CommunityRule is made by the Media Economies Design Lab at the University of Colorado Boulder.";
const privacyUrl = `${origin}/privacy`;
const aboutUrl = `${origin}/about`;
const logoUrl = `${origin}${MAGIC_LINK_LOGO_PATH}`;
const host = originHost(origin);
const text = [
heading,
"",
intro,
"",
`Log in: ${input.verifyUrl}`,
"",
ignore,
"",
madeBy,
`Privacy ${privacyUrl}`,
`About CommunityRule ${aboutUrl}`,
"",
`Sent because you asked to log in at ${host}.`,
].join("\n");
const href = escapeHtml(input.verifyUrl);
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${escapeHtml(subject)}</title>
</head>
<body style="margin:0;padding:0;background:#e4e4e4;">
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">${escapeHtml(
previewText,
)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#e4e4e4;">
<tr>
<td align="center">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:600px;max-width:600px;background:#ffffff;">
<tr>
<td style="background:#000000;padding:24px 32px;">
<table role="presentation" cellpadding="0" cellspacing="0">
<tr>
<td style="font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:22px;line-height:27px;color:#ffffff;padding-right:6px;">CommunityRule</td>
<td>
<img src="${escapeHtml(logoUrl)}" width="27" height="27" alt="" style="display:block;border:0;width:27px;height:27px;" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding:40px 32px 56px;">
<h1 style="margin:0 0 16px;font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:36px;line-height:44px;font-weight:700;color:#000000;">${escapeHtml(heading)}</h1>
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:18px;line-height:24px;color:#303030;">${escapeHtml(intro)}</p>
<p style="margin:0 0 32px;">
<a href="${href}" style="display:inline-block;background:#141414;color:#ffffff;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:20px;font-weight:500;text-decoration:none;border-radius:9999px;padding:12px 16px;">Log in</a>
</p>
<div style="height:1px;background:#e4e4e4;margin:0 0 32px;"></div>
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(ignore)}</p>
<div style="border-top:1px solid #e4e4e4;padding-top:24px;">
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(madeBy)}</p>
<p style="margin:0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
<a href="${escapeHtml(privacyUrl)}" style="color:#464646;text-decoration:underline;">Privacy</a>
&nbsp;&nbsp;
<a href="${escapeHtml(aboutUrl)}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>
</p>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
return { subject, previewText, text, html };
}
+4 -7
View File
@@ -6,6 +6,7 @@ import {
type WorkshopInquiryMailInput,
} from "../workshopSignupMail";
import { MAGIC_LINK_TTL_MINUTES } from "../privacyRetention";
import { buildMagicLinkMail } from "./magicLinkMail";
import { getSmtpUrl } from "./env";
import {
buildRuleStakeholderInviteMail,
@@ -87,16 +88,12 @@ async function sendHtmlMail(opts: {
export async function sendMagicLinkEmail(
to: string,
verifyUrl: string,
origin: string,
): Promise<void> {
const { text, html } = buildVerifyLinkParts(
verifyUrl,
`Open this link to log in (it expires in ${MAGIC_LINK_TTL_MINUTES} minutes):`,
"If you did not request this, you can ignore this email.\n\nSent because you saved a draft at communityrule.info",
"Log in",
);
const { subject, text, html } = buildMagicLinkMail({ verifyUrl, origin });
await sendHtmlMail({
to,
subject: "Log in to Community Rule",
subject,
text,
html,
devLog: `[dev] Magic link for ${to}: ${verifyUrl}`,
+9 -5
View File
@@ -1,15 +1,19 @@
{
"_comment": "CR-107 Ask an organizer modal (Figma 22078-587823)",
"title": "Ask an Organizer",
"_comment": "Ask an organizer modal (Figma 22078-587823, sent/failed 25032:48584 / 25032:48642)",
"title": "Ask an organizer",
"description": "Have a question about organizing? Send it over and an experienced organizer will get back to you.",
"emailLabel": "Email address",
"emailPlaceholder": "you@example.com",
"emailInvalid": "Enter an email address like name@example.org.",
"questionLabel": "Your question",
"questionTooShort": "Please enter at least 10 characters.",
"questionPlaceholder": "What would you like to know?",
"submitButton": "Confirm Question",
"submitButton": "Send question",
"closeAfterSuccess": "Close",
"successTitle": "Thanks, we received your question",
"successDescription": "Check your inbox and an organizer will reply when they can.",
"successTitle": "Thanks",
"successDescription": "One of us will write back within two working days.",
"sendFailedTitle": "We could not send that.",
"sendFailedDescription": "Your question is still here. Try again in a moment.",
"genericError": "Something went wrong. Please try again.",
"rateLimitedError": "Too many attempts. Please wait a bit and try again.",
"ariaDialog": "Ask an organizer",
+9 -3
View File
@@ -1,6 +1,6 @@
{
"title": "Log in to CommunityRule",
"subtitle": "Enter your email and we'll send you a magic link to log in. No password needed!",
"subtitle": "Enter your email and we'll send you a login link. No password needed.",
"saveProgressTitle": "Save your progress?",
"saveProgressSubtitle": "We need your email to save, and we'll send you a magic link to log in. If you don't save now you could lose your progress.",
"keepRuleTitle": "Log in to keep this rule on your profile",
@@ -11,9 +11,15 @@
"continueWithoutSaving": "Continue without saving",
"emailLabel": "Email address",
"emailPlaceholder": "you@example.com",
"sendMagicLink": "Send me a magic link",
"sendMagicLink": "Send login link",
"sendNewLink": "Send a new link",
"sendAgain": "Send it again",
"close": "Close",
"successTitle": "Check your email",
"successBody": "We sent a login link that works for 60 minutes. Open it on this device to continue. If you don't see it, check spam or promotions.",
"sentBody": "We sent a login link to {email}. It works for {minutes} minutes.",
"expiredTitle": "That link has expired",
"expiredBody": "That login link has expired or was already used. Send a new one.",
"legalPrefix": "By continuing, you agree to our ",
"legalAnd": " and ",
"legalSuffix": ".",
@@ -21,7 +27,7 @@
"loadingFallback": "Loading…",
"errors": {
"network": "Something went wrong. Check your connection and try again.",
"emailInvalid": "Enter a valid email address.",
"emailInvalid": "Enter an email address like name@example.org.",
"rateLimited": "Too many requests. Try again in {seconds} seconds.",
"generic": "Something went wrong. Try again.",
"invalidLink": "That login link is not valid. Request a new one from the login page.",
+48 -2
View File
@@ -109,7 +109,7 @@ export const HeaderOverlayBlurred = {
ariaLabelledBy="login-modal-heading"
>
<Suspense fallback={<p className="p-6 text-small-paragraph">Loading…</p>}>
<LoginForm />
<LoginForm onClose={() => {}} />
</Suspense>
</Login>
</FakeMarketingPageBehindOverlay>
@@ -154,7 +154,53 @@ export const FullPageRouteSolid = {
}
>
<Suspense fallback={<p className="p-6 text-small-paragraph">Loading…</p>}>
<LoginForm />
<LoginForm onClose={() => {}} />
</Suspense>
</Login>
),
};
export const LinkExpired = {
name: "Link expired",
parameters: {
nextjs: {
navigation: {
pathname: "/login",
query: { error: "expired_link" },
},
},
docs: {
description: {
story:
"Expired or used login links land on this heading, with Send a new link.",
},
},
},
decorators: [
(Story: () => React.ReactNode) => (
<div className="min-h-[100dvh] bg-[var(--color-surface-invert-brand-primary)]">
<Story />
</div>
),
],
render: () => (
<Login
isOpen
onClose={() => {}}
backdropVariant="solid"
usePortal={false}
ariaLabelledBy="login-modal-heading"
belowCard={
<a
href="/"
className="text-center text-small-paragraph text-[var(--color-content-invert-tertiary)] hover:opacity-90"
>
{backToHome}
</a>
}
>
<Suspense fallback={<p className="p-6 text-small-paragraph">Loading…</p>}>
<LoginForm onClose={() => {}} />
</Suspense>
</Login>
),
@@ -0,0 +1,147 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom/vitest";
import { renderWithProviders } from "../utils/test-utils";
import AskOrganizerInquiryModal from "../../app/components/modals/AskOrganizerInquiry";
describe("AskOrganizerInquiryModal", () => {
const fetchMock = vi.fn();
beforeEach(() => {
fetchMock.mockReset();
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("opens as a phone sheet and sends the question into the sent state", async () => {
const user = userEvent.setup();
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ ok: true }),
});
renderWithProviders(
<AskOrganizerInquiryModal isOpen onClose={vi.fn()} />,
);
await waitFor(() => {
expect(screen.getByRole("dialog")).toHaveClass("h-full", "max-h-full");
});
expect(
screen.getByRole("heading", { name: "Ask an organizer" }),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /send question/i }),
).toBeInTheDocument();
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"rosa@example.org",
);
await user.type(
screen.getByRole("textbox", { name: /your question/i }),
"How do we decide who holds the keys to our shared accounts?",
);
await user.click(screen.getByRole("button", { name: /send question/i }));
expect(
await screen.findByRole("heading", { name: "Thanks" }),
).toBeInTheDocument();
expect(
screen.getByText(/one of us will write back within two working days/i),
).toBeInTheDocument();
expect(
screen.getAllByRole("button", { name: /^close$/i }).length,
).toBeGreaterThan(1);
});
it("keeps the question and shows the danger toast when send fails", async () => {
const user = userEvent.setup();
fetchMock.mockRejectedValue(new Error("network"));
renderWithProviders(
<AskOrganizerInquiryModal isOpen onClose={vi.fn()} />,
);
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"rosa@example.org",
);
await user.type(
screen.getByRole("textbox", { name: /your question/i }),
"How do we decide who holds the keys to our shared accounts?",
);
await user.click(screen.getByRole("button", { name: /send question/i }));
await waitFor(() => {
expect(
screen.getAllByText("We could not send that.").length,
).toBeGreaterThan(0);
});
expect(
screen.getAllByText(/your question is still here/i).length,
).toBeGreaterThan(0);
expect(
screen.getByRole("textbox", { name: /email address/i }),
).toHaveValue("rosa@example.org");
expect(
screen.getByRole("textbox", { name: /your question/i }),
).toHaveValue(
"How do we decide who holds the keys to our shared accounts?",
);
expect(
screen.getByRole("button", { name: /send question/i }),
).toBeInTheDocument();
});
it("shows field hints for an invalid email and a short question, then clears them on edit", async () => {
const user = userEvent.setup();
renderWithProviders(
<AskOrganizerInquiryModal isOpen onClose={vi.fn()} />,
);
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"not-an-email",
);
await user.type(
screen.getByRole("textbox", { name: /your question/i }),
"Too short",
);
await user.click(screen.getByRole("button", { name: /send question/i }));
expect(
await screen.findByText("Enter an email address like name@example.org."),
).toBeInTheDocument();
expect(fetchMock).not.toHaveBeenCalled();
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"@example.org",
);
expect(
screen.queryByText("Enter an email address like name@example.org."),
).not.toBeInTheDocument();
await user.clear(screen.getByRole("textbox", { name: /email address/i }));
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"rosa@example.org",
);
await user.click(screen.getByRole("button", { name: /send question/i }));
expect(
await screen.findByText("Please enter at least 10 characters."),
).toBeInTheDocument();
await user.type(
screen.getByRole("textbox", { name: /your question/i }),
" more",
);
expect(
screen.queryByText("Please enter at least 10 characters."),
).not.toBeInTheDocument();
});
});
+2 -4
View File
@@ -289,12 +289,10 @@ describe("Create", () => {
</Create>,
);
const closeButton = screen.getByLabelText("Close");
screen.getByLabelText("Test Input"); // Verify input is rendered
const input = screen.getByLabelText("Test Input");
// Focus should start on first focusable element (close button)
await waitFor(() => {
expect(closeButton).toHaveFocus();
expect(input).toHaveFocus();
});
// Tab should move focus to next element
+38 -3
View File
@@ -1,14 +1,23 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { screen, fireEvent, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { renderWithProviders } from "../utils/test-utils";
import Login from "../../app/components/modals/Login";
describe("Login", () => {
const originalViewport = window.visualViewport;
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
Object.defineProperty(window, "visualViewport", {
configurable: true,
value: originalViewport,
});
});
it("uses blurredYellow backdrop by default (header overlay)", async () => {
renderWithProviders(
<Login isOpen onClose={vi.fn()} ariaLabelledBy="login-modal-heading">
@@ -156,8 +165,8 @@ describe("Login", () => {
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
expect(
screen.getByRole("link", { name: /back to home/i }),
).toBeInTheDocument();
screen.getAllByRole("link", { name: /back to home/i }).length,
).toBeGreaterThan(0);
});
it("does not render a more-options kebab", async () => {
@@ -172,4 +181,30 @@ describe("Login", () => {
expect(screen.getByLabelText("Close")).toBeInTheDocument();
expect(screen.queryByLabelText("More options")).not.toBeInTheDocument();
});
it("pins the overlay to the visual viewport offset", async () => {
Object.defineProperty(window, "visualViewport", {
configurable: true,
value: {
height: 500,
offsetTop: 80,
addEventListener: () => {},
removeEventListener: () => {},
},
});
renderWithProviders(
<Login isOpen onClose={vi.fn()} ariaLabelledBy="login-modal-heading">
<p id="login-modal-heading">Login content</p>
</Login>,
);
const backdrop = await waitFor(() => {
const dialog = screen.getByRole("dialog");
expect(dialog.parentElement).toHaveStyle({
top: "80px",
height: "500px",
});
return dialog.parentElement;
});
expect(backdrop).toHaveStyle({ bottom: "auto" });
});
});
+76 -16
View File
@@ -73,7 +73,7 @@ describe("LoginForm", () => {
screen.getByRole("textbox", { name: /email address/i }),
).toHaveAttribute("maxLength", String(EMAIL_MAX_LEN));
expect(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
).toBeInTheDocument();
});
@@ -95,10 +95,10 @@ describe("LoginForm", () => {
"not-an-email",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
expect(
await screen.findByText(/enter a valid email address/i),
await screen.findByText(/enter an email address like name@example.org/i),
).toBeInTheDocument();
expect(requestMagicLink).not.toHaveBeenCalled();
});
@@ -112,7 +112,7 @@ describe("LoginForm", () => {
" Pat@Example.COM ",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -124,8 +124,14 @@ describe("LoginForm", () => {
expect(
await screen.findByRole("heading", { name: /check your email/i }),
).toBeInTheDocument();
expect(screen.getByText(/we sent a login link/i)).toBeInTheDocument();
expect(screen.getByText(/check spam or promotions/i)).toBeInTheDocument();
expect(
screen.getByText(/we sent a login link to pat@example.com/i),
).toBeInTheDocument();
expect(screen.getByText(/it works for 60 minutes/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /^close$/i })).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /send it again/i }),
).toBeInTheDocument();
});
it("submits a long email without treating length as invalid", async () => {
@@ -139,7 +145,7 @@ describe("LoginForm", () => {
email,
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(email, "/", undefined);
@@ -162,7 +168,7 @@ describe("LoginForm", () => {
"save@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -199,7 +205,7 @@ describe("LoginForm", () => {
"guest@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -237,7 +243,7 @@ describe("LoginForm", () => {
"guest@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -286,7 +292,7 @@ describe("LoginForm", () => {
"a@b.co",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -309,7 +315,7 @@ describe("LoginForm", () => {
"ok@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
expect(await screen.findByText("Server says no")).toBeInTheDocument();
});
@@ -327,7 +333,7 @@ describe("LoginForm", () => {
"ok@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
expect(
await screen.findByText(/try again in 4 seconds/i),
@@ -338,7 +344,13 @@ describe("LoginForm", () => {
navMock.searchParams = new URLSearchParams("error=expired_link");
renderLoginForm();
expect(
screen.getByText(/that login link has expired/i),
screen.getByRole("heading", { name: /that link has expired/i }),
).toBeInTheDocument();
expect(
screen.getByText(/expired or was already used/i),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /send a new link/i }),
).toBeInTheDocument();
});
@@ -346,7 +358,10 @@ describe("LoginForm", () => {
navMock.searchParams = new URLSearchParams("error=invalid_link");
renderLoginForm();
expect(
screen.getByText(/that login link is not valid/i),
screen.getByRole("heading", { name: /that link has expired/i }),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /send a new link/i }),
).toBeInTheDocument();
});
@@ -383,10 +398,55 @@ describe("LoginForm", () => {
"ok@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
expect(
await screen.findByText(/check your connection/i),
).toBeInTheDocument();
});
it("send it again requests another link from the sent state", async () => {
const user = userEvent.setup();
vi.mocked(requestMagicLink).mockResolvedValue({ ok: true });
renderLoginForm();
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"pat@example.com",
);
await user.click(
screen.getByRole("button", { name: /send login link/i }),
);
expect(
await screen.findByRole("button", { name: /send it again/i }),
).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /send it again/i }));
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledTimes(2);
});
});
it("shows the email field again when send it again fails", async () => {
const user = userEvent.setup();
vi.mocked(requestMagicLink)
.mockResolvedValueOnce({ ok: true })
.mockRejectedValueOnce(new Error("network"));
renderLoginForm();
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"pat@example.com",
);
await user.click(
screen.getByRole("button", { name: /send login link/i }),
);
await user.click(
await screen.findByRole("button", { name: /send it again/i }),
);
expect(
await screen.findByRole("textbox", { name: /email address/i }),
).toHaveValue("pat@example.com");
expect(
screen.getByText(/check your connection/i),
).toBeInTheDocument();
});
});
+5 -5
View File
@@ -177,7 +177,7 @@ describe("AuthModalProvider (header overlay)", () => {
"guest@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -211,7 +211,7 @@ describe("AuthModalProvider (header overlay)", () => {
"guest@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -285,14 +285,14 @@ describe("AuthModalProvider (header overlay)", () => {
screen.getByRole("heading", { name: /log in to invite your members/i }),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /back to your rule/i }),
).toBeInTheDocument();
screen.getAllByRole("button", { name: /back to your rule/i }).length,
).toBeGreaterThan(0);
await user.type(
screen.getByRole("textbox", { name: /email address/i }),
"guest@example.com",
);
await user.click(
screen.getByRole("button", { name: /send me a magic link/i }),
screen.getByRole("button", { name: /send login link/i }),
);
await waitFor(() => {
expect(requestMagicLink).toHaveBeenCalledWith(
@@ -111,6 +111,7 @@ describe("POST /api/auth/magic-link/request", () => {
expect(sendMagicLinkEmailMock).toHaveBeenCalledWith(
"member@example.com",
expect.stringContaining("/api/auth/magic-link/verify?token="),
"https://x.test",
);
});
@@ -130,6 +131,7 @@ describe("POST /api/auth/magic-link/request", () => {
expect(sendMagicLinkEmailMock).toHaveBeenCalledWith(
email,
expect.stringContaining("/api/auth/magic-link/verify?token="),
"https://x.test",
);
});
@@ -0,0 +1,50 @@
import { renderHook, act } from "@testing-library/react";
import { describe, it, expect, afterEach } from "vitest";
import { useVisualViewportHeight } from "../../../app/hooks/useVisualViewportHeight";
describe("useVisualViewportHeight", () => {
const original = window.visualViewport;
afterEach(() => {
Object.defineProperty(window, "visualViewport", {
configurable: true,
value: original,
});
});
it("returns undefined when disabled", () => {
const { result } = renderHook(() => useVisualViewportHeight(false));
expect(result.current).toBeUndefined();
});
it("tracks height and the iOS keyboard offset", () => {
const listeners = new Map<string, Set<() => void>>();
const vp = {
height: 800,
offsetTop: 0,
addEventListener: (type: string, fn: () => void) => {
const set = listeners.get(type) ?? new Set();
set.add(fn);
listeners.set(type, set);
},
removeEventListener: (type: string, fn: () => void) => {
listeners.get(type)?.delete(fn);
},
};
Object.defineProperty(window, "visualViewport", {
configurable: true,
value: vp,
});
const { result } = renderHook(() => useVisualViewportHeight(true));
expect(result.current).toEqual({ height: 800, offsetTop: 0 });
act(() => {
vp.height = 420;
vp.offsetTop = 120;
listeners.get("scroll")?.forEach((fn) => fn());
});
expect(result.current).toEqual({ height: 420, offsetTop: 120 });
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { MAGIC_LINK_TTL_MINUTES } from "../../lib/privacyRetention";
import { buildMagicLinkMail } from "../../lib/server/magicLinkMail";
const VERIFY_URL =
"https://communityrule.info/api/auth/magic-link/verify?token=abc";
describe("buildMagicLinkMail", () => {
const mail = buildMagicLinkMail({
verifyUrl: VERIFY_URL,
origin: "https://communityrule.info",
});
it("uses the drawn subject, once-and-minutes line, and log in button", () => {
expect(mail.subject).toBe("Your login link for CommunityRule");
expect(mail.previewText).toBe(
`It works once, for ${MAGIC_LINK_TTL_MINUTES} minutes.`,
);
expect(mail.text).toContain("Log in to CommunityRule");
expect(mail.text).toContain(VERIFY_URL);
expect(mail.text).toContain(
`It works once, for ${MAGIC_LINK_TTL_MINUTES} minutes.`,
);
expect(mail.html).toContain("background:#000000");
expect(mail.html).toContain(">Log in</a>");
expect(mail.html).toContain(`href="${VERIFY_URL}"`);
expect(mail.html).toContain("/privacy");
expect(mail.html).toContain("/about");
});
it("does not invent a first name", () => {
expect(mail.html).not.toContain("Hi ");
expect(mail.text).not.toContain("Hi ");
});
});
+3 -3
View File
@@ -4,8 +4,8 @@ import { MAGIC_LINK_TTL_MINUTES } from "../../lib/privacyRetention";
describe("privacy retention copy", () => {
it("states the login link lifetime in the sent state", () => {
expect(login.successBody).toContain(
`works for ${MAGIC_LINK_TTL_MINUTES} minutes`,
);
expect(
login.sentBody.replace("{minutes}", String(MAGIC_LINK_TTL_MINUTES)),
).toContain(`works for ${MAGIC_LINK_TTL_MINUTES} minutes`);
});
});