diff --git a/app/(app)/login/page.tsx b/app/(app)/login/page.tsx index 54f18f3..d9f0241 100644 --- a/app/(app)/login/page.tsx +++ b/app/(app)/login/page.tsx @@ -28,6 +28,9 @@ function LoginLoadingFallback() { function LoginWithSearchParams() { const router = useRouter(); const t = useTranslation("pages.login"); + const closeToHome = () => { + router.push("/"); + }; return (
@@ -35,9 +38,7 @@ function LoginWithSearchParams() { isOpen usePortal={false} backdropVariant="solid" - onClose={() => { - router.push("/"); - }} + onClose={closeToHome} ariaLabelledBy="login-modal-heading" belowCard={ } > - +
); diff --git a/app/api/auth/magic-link/request/route.ts b/app/api/auth/magic-link/request/route.ts index 33b7cd0..4bda5b1 100644 --- a/app/api/auth/magic-link/request/route.ts +++ b/app/api/auth/magic-link/request/route.ts @@ -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 } }); diff --git a/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.container.tsx b/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.container.tsx index e624da0..0c999ad 100644 --- a/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.container.tsx +++ b/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.container.tsx @@ -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( ({ isOpen, onClose }) => { const t = useTranslation("modals.askOrganizerInquiry"); @@ -21,12 +23,16 @@ const AskOrganizerInquiryModalContainer = memo( 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( const [honeypot, setHoneypot] = useState(""); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(false); - const [formError, setFormError] = useState(null); + const [sendFailed, setSendFailed] = useState(false); const [emailError, setEmailError] = useState(false); const [questionError, setQuestionError] = useState(false); @@ -49,18 +55,40 @@ const AskOrganizerInquiryModalContainer = memo( 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) => { 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( method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ - email, - message, + email: trimmedEmail, + message: trimmedMessage, [ORGANIZER_INQUIRY_HONEYPOT_FIELD]: honeypot, }), }); @@ -81,40 +109,43 @@ const AskOrganizerInquiryModalContainer = memo( return; } - if (res.status === 429) { - setFormError(t("rateLimitedError")); + if (res.status === 400) { + let nextEmailError = false; + let nextQuestionError = false; + if ( + data && + typeof data === "object" && + "error" in data && + data.error && + typeof data.error === "object" && + "message" in data.error && + typeof (data.error as { message: unknown }).message === "string" + ) { + const msg = (data.error as { message: string }).message; + const lower = msg.toLowerCase(); + if (lower.includes("email")) { + nextEmailError = true; + } + if (lower.includes("character") || lower.includes("question")) { + nextQuestionError = true; + } + } + setEmailError(nextEmailError); + setQuestionError(nextQuestionError); + if (!nextEmailError && !nextQuestionError) { + setSendFailed(true); + } return; } - if ( - data && - typeof data === "object" && - "error" in data && - data.error && - typeof data.error === "object" && - "message" in data.error && - typeof (data.error as { message: unknown }).message === "string" - ) { - const msg = (data.error as { message: string }).message; - const lower = msg.toLowerCase(); - if (lower.includes("email")) { - setEmailError(true); - } - if (lower.includes("character") || lower.includes("question")) { - setQuestionError(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( 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)} /> ); }, diff --git a/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.types.ts b/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.types.ts index 4ee5055..a66d8a3 100644 --- a/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.types.ts +++ b/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.types.ts @@ -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) => void; + onDismissFailed: () => void; } diff --git a/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.view.tsx b/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.view.tsx index 8023adf..e3212fb 100644 --- a/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.view.tsx +++ b/app/components/modals/AskOrganizerInquiry/AskOrganizerInquiryModal.view.tsx @@ -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,40 +25,58 @@ export function AskOrganizerInquiryModalView({ honeypot, submitting, success, - formError, + sendFailed, emailError, questionError, onEmailChange, onMessageChange, onHoneypotChange, onSubmit, + onDismissFailed, }: AskOrganizerInquiryModalViewProps) { - const footer = success ? ( -
- -
- ) : ( -
- + const failedToast = sendFailed ? ( + + ) : null; + + const footer = ( +
+
{failedToast}
+ {success ? ( + + ) : ( + + )}
); @@ -64,9 +84,10 @@ export function AskOrganizerInquiryModalView({ onClose()} - > - {copy.backToHome} - + success ? undefined : ( +
+
{failedToast}
+ onClose()} + > + {copy.backToHome} + +
+ ) } > - {success ? ( -
-

- {copy.successTitle} -

-

- {copy.successDescription} -

-
- ) : ( + {success ? null : (
- {formError ? ( -

- {formError} -

- ) : null} - 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} diff --git a/app/components/modals/Create/Create.container.tsx b/app/components/modals/Create/Create.container.tsx index 1e4f151..87affc3 100644 --- a/app/components/modals/Create/Create.container.tsx +++ b/app/components/modals/Create/Create.container.tsx @@ -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( kebabMenuAriaLabel, kebabMenuItems, belowCard, + presentation = "dialog", }) => { const createRef = useRef(null); const overlayRef = useRef(null); + const viewport = useVisualViewportHeight( + isOpen && presentation === "sheet", + ); useCreateModalA11y(isOpen, onClose, createRef); @@ -86,6 +91,9 @@ const CreateContainer = memo( kebabMenuAriaLabel={kebabMenuAriaLabel} kebabMenuItems={kebabMenuItems} belowCard={belowCard} + presentation={presentation} + viewportHeight={viewport?.height} + viewportOffsetTop={viewport?.offsetTop} /> ); }, diff --git a/app/components/modals/Create/Create.types.ts b/app/components/modals/Create/Create.types.ts index ee7d690..6563114 100644 --- a/app/components/modals/Create/Create.types.ts +++ b/app/components/modals/Create/Create.types.ts @@ -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; } diff --git a/app/components/modals/Create/Create.view.tsx b/app/components/modals/Create/Create.view.tsx index 351e78a..63f79c1 100644 --- a/app/components/modals/Create/Create.view.tsx +++ b/app/components/modals/Create/Create.view.tsx @@ -41,6 +41,9 @@ export function CreateView({ kebabMenuAriaLabel, kebabMenuItems, belowCard, + presentation, + viewportHeight, + viewportOffsetTop, }: CreateViewProps) { return ( @@ -78,7 +96,10 @@ export function CreateModalFrameView({ {children}
{belowCard ? ( -
e.stopPropagation()}> +
e.stopPropagation()} + > {belowCard}
) : null} diff --git a/app/components/modals/Create/useCreateModalA11y.ts b/app/components/modals/Create/useCreateModalA11y.ts index 4ffeca1..25ca06a 100644 --- a/app/components/modals/Create/useCreateModalA11y.ts +++ b/app/components/modals/Create/useCreateModalA11y.ts @@ -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( + 'input[type="email"]:not([disabled]):not([tabindex="-1"])', + ); + if (email) return email; + const field = dialog.querySelector(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 { diff --git a/app/components/modals/Login/Login.container.tsx b/app/components/modals/Login/Login.container.tsx index f343e4c..13210cd 100644 --- a/app/components/modals/Login/Login.container.tsx +++ b/app/components/modals/Login/Login.container.tsx @@ -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( const backdropRef = useRef(null); const previousActiveElementRef = useRef(null); const [portalReady, setPortalReady] = useState(() => !usePortal); - const [viewportHeight, setViewportHeight] = useState( - 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( 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( portalReady={portalReady} usePortal={usePortal} backdropVariant={backdropVariant} - viewportHeight={viewportHeight} + viewportHeight={viewport?.height} + viewportOffsetTop={viewport?.offsetTop} > {children} diff --git a/app/components/modals/Login/Login.types.ts b/app/components/modals/Login/Login.types.ts index 310a178..f2884b1 100644 --- a/app/components/modals/Login/Login.types.ts +++ b/app/components/modals/Login/Login.types.ts @@ -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; } diff --git a/app/components/modals/Login/Login.view.tsx b/app/components/modals/Login/Login.view.tsx index 74fec90..3136f03 100644 --- a/app/components/modals/Login/Login.view.tsx +++ b/app/components/modals/Login/Login.view.tsx @@ -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 ? ( +
e.stopPropagation()} + > + {belowCard} +
+ ) : null; + const content = (
{ 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()} > -
+
{children} + {belowCardLink ? ( +
{belowCardLink}
+ ) : null}
- {belowCard ? ( -
e.stopPropagation()} - > - {belowCard} -
+ {belowCardLink ? ( +
{belowCardLink}
) : null}
); diff --git a/app/components/modals/Login/LoginForm.tsx b/app/components/modals/Login/LoginForm.tsx index 827358b..24e3620 100644 --- a/app/components/modals/Login/LoginForm.tsx +++ b/app/components/modals/Login/LoginForm.tsx @@ -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,115 +206,143 @@ export default function LoginForm({ variant, ]); + useEffect(() => { + if (isExpiredLinkError(errorParam)) { + setLinkExpired(true); + } + }, [errorParam]); + const urlErrorMessage = - errorParam === "expired_link" - ? t("errors.expiredLink") - : errorParam === "stakeholder_wrong_account" - ? t("errors.stakeholderWrongAccount") - : errorParam === "invalid_link" || errorParam === "server" - ? errorParam === "server" - ? t("errors.serverError") - : t("errors.invalidLink") - : ""; + 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 ( -
-
-
- +
+
+
+
+ +
+
- + + {(urlErrorMessage || formError) && ( +
+
+ {urlErrorMessage ? ( + { + stripErrorQuery(); + }} + className="w-full" + /> + ) : null} + {formError ? ( + { + setFormError(""); + }} + className="w-full" + /> + ) : null} +
+
+ )} + + {!sent ? ( + { + e.preventDefault(); + void sendLink(); + }} + noValidate + > + { + setEmail(e.target.value); + setEmailError(""); + stripErrorQuery(); + }} + disabled={submitting} + error={Boolean(emailError)} + textHint={emailError || false} + showHelpIcon={false} + maxLength={EMAIL_MAX_LEN} + /> + + ) : null}
- {(urlErrorMessage || formError) && ( -
-
- {urlErrorMessage ? ( - { - stripErrorQuery(); - }} - className="w-full" - /> - ) : null} - {formError ? ( - { - setFormError(""); - }} - className="w-full" - /> - ) : null} -
-
- )} - - {!sent ? ( -
{ - e.preventDefault(); - void sendLink(); - }} - noValidate - > - { - setEmail(e.target.value); - stripErrorQuery(); - }} - disabled={submitting} - error={Boolean(emailError)} - showHelpIcon - maxLength={EMAIL_MAX_LEN} - /> - {emailError ? ( -
- - ) : null} + + )} +
); } diff --git a/app/contexts/AuthModalContext.tsx b/app/contexts/AuthModalContext.tsx index 55d4364..f7d4929 100644 --- a/app/contexts/AuthModalContext.tsx +++ b/app/contexts/AuthModalContext.tsx @@ -94,6 +94,7 @@ export function AuthModalProvider({ children }: { children: ReactNode }) { variant={opts.variant ?? "default"} magicLinkNextPath={opts.nextPath} onDismiss={keepRuleDismiss} + onClose={closeLogin} /> diff --git a/app/hooks/index.ts b/app/hooks/index.ts index 256749d..3a89a01 100644 --- a/app/hooks/index.ts +++ b/app/hooks/index.ts @@ -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, diff --git a/app/hooks/useVisualViewportHeight.ts b/app/hooks/useVisualViewportHeight.ts new file mode 100644 index 0000000..6698278 --- /dev/null +++ b/app/hooks/useVisualViewportHeight.ts @@ -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; +} diff --git a/lib/server/magicLinkMail.ts b/lib/server/magicLinkMail.ts new file mode 100644 index 0000000..ce840ac --- /dev/null +++ b/lib/server/magicLinkMail.ts @@ -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, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +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 = ` + + + + +${escapeHtml(subject)} + + +
${escapeHtml( + previewText, + )}
+ + + + +
+ + + + + + + +
+ + + + + +
CommunityRule + +
+
+

${escapeHtml(heading)}

+

${escapeHtml(intro)}

+

+ Log in +

+
+

${escapeHtml(ignore)}

+
+

${escapeHtml(madeBy)}

+

+ Privacy +    + About CommunityRule +

+
+
+
+ +`; + + return { subject, previewText, text, html }; +} diff --git a/lib/server/mail.ts b/lib/server/mail.ts index e0838d9..bdb1d10 100644 --- a/lib/server/mail.ts +++ b/lib/server/mail.ts @@ -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 { - 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}`, diff --git a/messages/en/modals/askOrganizerInquiry.json b/messages/en/modals/askOrganizerInquiry.json index 0e012ec..539cc89 100644 --- a/messages/en/modals/askOrganizerInquiry.json +++ b/messages/en/modals/askOrganizerInquiry.json @@ -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", diff --git a/messages/en/pages/login.json b/messages/en/pages/login.json index 85d176d..b68d268 100644 --- a/messages/en/pages/login.json +++ b/messages/en/pages/login.json @@ -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.", diff --git a/stories/modals/Login.stories.tsx b/stories/modals/Login.stories.tsx index 28e9832..d129644 100644 --- a/stories/modals/Login.stories.tsx +++ b/stories/modals/Login.stories.tsx @@ -109,7 +109,7 @@ export const HeaderOverlayBlurred = { ariaLabelledBy="login-modal-heading" > Loading…

}> - + {}} />
@@ -154,7 +154,53 @@ export const FullPageRouteSolid = { } > Loading…

}> - + {}} /> +
+ + ), +}; + +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) => ( +
+ +
+ ), + ], + render: () => ( + {}} + backdropVariant="solid" + usePortal={false} + ariaLabelledBy="login-modal-heading" + belowCard={ + + {backToHome} + + } + > + Loading…

}> + {}} />
), diff --git a/tests/components/AskOrganizerInquiry.test.tsx b/tests/components/AskOrganizerInquiry.test.tsx new file mode 100644 index 0000000..2cbbab0 --- /dev/null +++ b/tests/components/AskOrganizerInquiry.test.tsx @@ -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( + , + ); + + 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( + , + ); + + 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( + , + ); + + 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(); + }); +}); diff --git a/tests/components/Create.test.tsx b/tests/components/Create.test.tsx index 9f07018..b4de667 100644 --- a/tests/components/Create.test.tsx +++ b/tests/components/Create.test.tsx @@ -289,12 +289,10 @@ describe("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 diff --git a/tests/components/Login.test.tsx b/tests/components/Login.test.tsx index 757bf22..d9a8064 100644 --- a/tests/components/Login.test.tsx +++ b/tests/components/Login.test.tsx @@ -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( @@ -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 content

+
, + ); + 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" }); + }); }); diff --git a/tests/components/LoginForm.test.tsx b/tests/components/LoginForm.test.tsx index 2c368d7..ba69f06 100644 --- a/tests/components/LoginForm.test.tsx +++ b/tests/components/LoginForm.test.tsx @@ -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(); + }); }); diff --git a/tests/contexts/AuthModalContext.test.tsx b/tests/contexts/AuthModalContext.test.tsx index 84fbc22..bcb0f62 100644 --- a/tests/contexts/AuthModalContext.test.tsx +++ b/tests/contexts/AuthModalContext.test.tsx @@ -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( diff --git a/tests/unit/authMagicLinkRequestRoute.test.ts b/tests/unit/authMagicLinkRequestRoute.test.ts index 18ee53c..3d56cf7 100644 --- a/tests/unit/authMagicLinkRequestRoute.test.ts +++ b/tests/unit/authMagicLinkRequestRoute.test.ts @@ -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", ); }); diff --git a/tests/unit/hooks/useVisualViewportHeight.test.ts b/tests/unit/hooks/useVisualViewportHeight.test.ts new file mode 100644 index 0000000..b4e6901 --- /dev/null +++ b/tests/unit/hooks/useVisualViewportHeight.test.ts @@ -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 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 }); + }); +}); diff --git a/tests/unit/magicLinkMail.test.ts b/tests/unit/magicLinkMail.test.ts new file mode 100644 index 0000000..eeec16d --- /dev/null +++ b/tests/unit/magicLinkMail.test.ts @@ -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"); + 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 "); + }); +}); diff --git a/tests/unit/privacyRetention.test.ts b/tests/unit/privacyRetention.test.ts index 133a75d..f53c77f 100644 --- a/tests/unit/privacyRetention.test.ts +++ b/tests/unit/privacyRetention.test.ts @@ -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`); }); });