Pin phone sheets to the visible viewport, and let people correct login and organizer errors.

This commit is contained in:
adilallo committed 2026-11-11 17:01:44 -07:00
1 parent 27d74e510c
commit 39807ef452
17 files changed
+236 -16

No files matched your search

@@ -23,8 +23,10 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
description: t("description"), description: t("description"),
emailLabel: t("emailLabel"), emailLabel: t("emailLabel"),
emailPlaceholder: t("emailPlaceholder"), emailPlaceholder: t("emailPlaceholder"),
emailInvalid: t("emailInvalid"),
questionLabel: t("questionLabel"), questionLabel: t("questionLabel"),
questionPlaceholder: t("questionPlaceholder"), questionPlaceholder: t("questionPlaceholder"),
questionTooShort: t("questionTooShort"),
submitButton: t("submitButton"), submitButton: t("submitButton"),
closeAfterSuccess: t("closeAfterSuccess"), closeAfterSuccess: t("closeAfterSuccess"),
successTitle: t("successTitle"), successTitle: t("successTitle"),
@@ -59,6 +61,16 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
} }
}, [isOpen]); }, [isOpen]);
const onEmailChange = useCallback((value: string) => {
setEmail(value);
setEmailError(false);
}, []);
const onMessageChange = useCallback((value: string) => {
setMessage(value);
setQuestionError(false);
}, []);
const onSubmit = useCallback( const onSubmit = useCallback(
async (e: FormEvent<HTMLFormElement>) => { async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
@@ -149,8 +161,8 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
sendFailed={sendFailed} sendFailed={sendFailed}
emailError={emailError} emailError={emailError}
questionError={questionError} questionError={questionError}
onEmailChange={setEmail} onEmailChange={onEmailChange}
onMessageChange={setMessage} onMessageChange={onMessageChange}
onHoneypotChange={setHoneypot} onHoneypotChange={setHoneypot}
onSubmit={onSubmit} onSubmit={onSubmit}
onDismissFailed={() => setSendFailed(false)} onDismissFailed={() => setSendFailed(false)}
@@ -8,8 +8,10 @@ export interface AskOrganizerInquiryModalCopy {
description: string; description: string;
emailLabel: string; emailLabel: string;
emailPlaceholder: string; emailPlaceholder: string;
emailInvalid: string;
questionLabel: string; questionLabel: string;
questionPlaceholder: string; questionPlaceholder: string;
questionTooShort: string;
submitButton: string; submitButton: string;
closeAfterSuccess: string; closeAfterSuccess: string;
successTitle: string; successTitle: string;
@@ -125,6 +125,7 @@ export function AskOrganizerInquiryModalView({
value={email} value={email}
onChange={(e) => onEmailChange(e.target.value)} onChange={(e) => onEmailChange(e.target.value)}
error={emailError} error={emailError}
textHint={emailError ? copy.emailInvalid : false}
inputSize="medium" inputSize="medium"
showHelpIcon={false} showHelpIcon={false}
/> />
@@ -136,6 +137,7 @@ export function AskOrganizerInquiryModalView({
value={message} value={message}
onChange={(e) => onMessageChange(e.target.value)} onChange={(e) => onMessageChange(e.target.value)}
error={questionError} error={questionError}
textHint={questionError ? copy.questionTooShort : false}
size="medium" size="medium"
appearance="embedded" appearance="embedded"
rows={4} rows={4}
@@ -48,7 +48,7 @@ const CreateContainer = memo<CreateProps>(
}) => { }) => {
const createRef = useRef<HTMLDivElement>(null); const createRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(null); const overlayRef = useRef<HTMLDivElement>(null);
const viewportHeight = useVisualViewportHeight( const viewport = useVisualViewportHeight(
isOpen && presentation === "sheet", isOpen && presentation === "sheet",
); );
@@ -92,7 +92,8 @@ const CreateContainer = memo<CreateProps>(
kebabMenuItems={kebabMenuItems} kebabMenuItems={kebabMenuItems}
belowCard={belowCard} belowCard={belowCard}
presentation={presentation} presentation={presentation}
viewportHeight={viewportHeight} viewportHeight={viewport?.height}
viewportOffsetTop={viewport?.offsetTop}
/> />
); );
}, },
@@ -95,4 +95,6 @@ export interface CreateViewProps {
belowCard?: React.ReactNode; belowCard?: React.ReactNode;
presentation: CreateModalPresentationValue; presentation: CreateModalPresentationValue;
viewportHeight?: number; viewportHeight?: number;
/** `visualViewport.offsetTop`, so a phone sheet tracks the visible region on iOS. */
viewportOffsetTop?: number;
} }
@@ -43,6 +43,7 @@ export function CreateView({
belowCard, belowCard,
presentation, presentation,
viewportHeight, viewportHeight,
viewportOffsetTop,
}: CreateViewProps) { }: CreateViewProps) {
return ( return (
<CreateModalFrameView <CreateModalFrameView
@@ -57,6 +58,7 @@ export function CreateView({
belowCard={belowCard} belowCard={belowCard}
presentation={presentation} presentation={presentation}
viewportHeight={viewportHeight} viewportHeight={viewportHeight}
viewportOffsetTop={viewportOffsetTop}
> >
<ModalHeader <ModalHeader
onClose={onClose} onClose={onClose}
@@ -33,6 +33,8 @@ export type CreateModalFrameViewProps = {
presentation?: CreateModalPresentationValue; presentation?: CreateModalPresentationValue;
/** Visible viewport height so a phone sheet footer rides above the keyboard. */ /** Visible viewport height so a phone sheet footer rides above the keyboard. */
viewportHeight?: number; viewportHeight?: number;
/** `visualViewport.offsetTop`, so the sheet tracks the visible region on iOS. */
viewportOffsetTop?: number;
}; };
/** /**
@@ -51,6 +53,7 @@ export function CreateModalFrameView({
belowCard, belowCard,
presentation = "dialog", presentation = "dialog",
viewportHeight, viewportHeight,
viewportOffsetTop,
}: CreateModalFrameViewProps) { }: CreateModalFrameViewProps) {
if (!isOpen) return null; if (!isOpen) return null;
@@ -65,7 +68,12 @@ export function CreateModalFrameView({
: "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]"; : "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 = const overlayStyle =
isSheet && viewportHeight != null isSheet && viewportHeight != null
? { height: viewportHeight, maxHeight: viewportHeight } ? {
top: viewportOffsetTop ?? 0,
bottom: "auto" as const,
height: viewportHeight,
maxHeight: viewportHeight,
}
: undefined; : undefined;
const content = ( const content = (
@@ -26,7 +26,7 @@ const LoginContainer = memo<LoginProps>(
const backdropRef = useRef<HTMLDivElement>(null); const backdropRef = useRef<HTMLDivElement>(null);
const previousActiveElementRef = useRef<HTMLElement | null>(null); const previousActiveElementRef = useRef<HTMLElement | null>(null);
const [portalReady, setPortalReady] = useState(() => !usePortal); const [portalReady, setPortalReady] = useState(() => !usePortal);
const viewportHeight = useVisualViewportHeight(isOpen); const viewport = useVisualViewportHeight(isOpen);
// Defer enabling the portal until after the layout commit so we don’t sync-setState // 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 // inside the effect (eslint react-hooks/set-state-in-effect) while still mounting
@@ -135,7 +135,8 @@ const LoginContainer = memo<LoginProps>(
portalReady={portalReady} portalReady={portalReady}
usePortal={usePortal} usePortal={usePortal}
backdropVariant={backdropVariant} backdropVariant={backdropVariant}
viewportHeight={viewportHeight} viewportHeight={viewport?.height}
viewportOffsetTop={viewport?.offsetTop}
> >
{children} {children}
</LoginView> </LoginView>
@@ -35,4 +35,6 @@ export interface LoginViewProps {
backdropVariant: LoginBackdropVariant; backdropVariant: LoginBackdropVariant;
/** Visible viewport height on phones so the footer rides above the keyboard. */ /** Visible viewport height on phones so the footer rides above the keyboard. */
viewportHeight?: number; viewportHeight?: number;
/** `visualViewport.offsetTop`, so the sheet tracks the visible region on iOS. */
viewportOffsetTop?: number;
} }
+7 -1
View File
@@ -24,13 +24,19 @@ export function LoginView({
usePortal, usePortal,
backdropVariant, backdropVariant,
viewportHeight, viewportHeight,
viewportOffsetTop,
}: LoginViewProps) { }: LoginViewProps) {
if (!isOpen) return null; if (!isOpen) return null;
if (usePortal && !portalReady) return null; if (usePortal && !portalReady) return null;
const phoneSheetStyle = const phoneSheetStyle =
viewportHeight != null viewportHeight != null
? { height: viewportHeight, maxHeight: viewportHeight } ? {
top: viewportOffsetTop ?? 0,
bottom: "auto" as const,
height: viewportHeight,
maxHeight: viewportHeight,
}
: undefined; : undefined;
const belowCardLink = belowCard ? ( const belowCardLink = belowCard ? (
@@ -158,6 +158,7 @@ export default function LoginForm({
setFormError(""); setFormError("");
const trimmed = email.trim().toLowerCase(); const trimmed = email.trim().toLowerCase();
if (!EMAIL_PATTERN.test(trimmed)) { if (!EMAIL_PATTERN.test(trimmed)) {
setSent(false);
setEmailError(t("errors.emailInvalid")); setEmailError(t("errors.emailInvalid"));
return; return;
} }
@@ -173,6 +174,7 @@ export default function LoginForm({
: undefined; : undefined;
const result = await requestMagicLink(trimmed, nextPath, draft); const result = await requestMagicLink(trimmed, nextPath, draft);
if (result.ok === false) { if (result.ok === false) {
setSent(false);
if (result.retryAfterMs != null && result.retryAfterMs > 0) { if (result.retryAfterMs != null && result.retryAfterMs > 0) {
const seconds = Math.ceil(result.retryAfterMs / 1000); const seconds = Math.ceil(result.retryAfterMs / 1000);
setFormError( setFormError(
@@ -190,6 +192,7 @@ export default function LoginForm({
setLinkExpired(false); setLinkExpired(false);
setSent(true); setSent(true);
} catch { } catch {
setSent(false);
setFormError(t("errors.network")); setFormError(t("errors.network"));
} finally { } finally {
setSubmitting(false); setSubmitting(false);
+25 -7
View File
@@ -1,22 +1,40 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
/** /**
* Visible viewport height, including the shrink when a phone keyboard opens. * 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`. * @param enabled When false, skip listeners and return `undefined`.
* @returns Pixel height of `visualViewport`, or `undefined` when disabled. * @returns Height and top offset of `visualViewport`, or `undefined` when disabled.
* *
* @example * @example
* const viewportHeight = useVisualViewportHeight(isOpen); * const viewport = useVisualViewportHeight(isOpen);
*/ */
export function useVisualViewportHeight(enabled: boolean): number | undefined { export function useVisualViewportHeight(
const [height, setHeight] = useState<number | undefined>(undefined); enabled: boolean,
): { height: number; offsetTop: number } | undefined {
const [frame, setFrame] = useState<
{ height: number; offsetTop: number } | undefined
>(undefined);
useEffect(() => { useEffect(() => {
if (!enabled) return; if (!enabled) return;
const vp = window.visualViewport; const vp = window.visualViewport;
const sync = () => { const sync = () => {
setHeight(vp?.height ?? window.innerHeight); 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(); sync();
vp?.addEventListener("resize", sync); vp?.addEventListener("resize", sync);
@@ -29,5 +47,5 @@ export function useVisualViewportHeight(enabled: boolean): number | undefined {
}; };
}, [enabled]); }, [enabled]);
return enabled ? height : undefined; return enabled ? frame : undefined;
} }
@@ -4,7 +4,9 @@
"description": "Have a question about organizing? Send it over and an experienced organizer will get back to you.", "description": "Have a question about organizing? Send it over and an experienced organizer will get back to you.",
"emailLabel": "Email address", "emailLabel": "Email address",
"emailPlaceholder": "you@example.com", "emailPlaceholder": "you@example.com",
"emailInvalid": "Enter an email address like name@example.org.",
"questionLabel": "Your question", "questionLabel": "Your question",
"questionTooShort": "Please enter at least 10 characters.",
"questionPlaceholder": "What would you like to know?", "questionPlaceholder": "What would you like to know?",
"submitButton": "Send question", "submitButton": "Send question",
"closeAfterSuccess": "Close", "closeAfterSuccess": "Close",
@@ -95,4 +95,53 @@ describe("AskOrganizerInquiryModal", () => {
screen.getByRole("button", { name: /send question/i }), screen.getByRole("button", { name: /send question/i }),
).toBeInTheDocument(); ).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();
});
}); });
+36 -1
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 { screen, fireEvent, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import { renderWithProviders } from "../utils/test-utils"; import { renderWithProviders } from "../utils/test-utils";
import Login from "../../app/components/modals/Login"; import Login from "../../app/components/modals/Login";
describe("Login", () => { describe("Login", () => {
const originalViewport = window.visualViewport;
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
afterEach(() => {
Object.defineProperty(window, "visualViewport", {
configurable: true,
value: originalViewport,
});
});
it("uses blurredYellow backdrop by default (header overlay)", async () => { it("uses blurredYellow backdrop by default (header overlay)", async () => {
renderWithProviders( renderWithProviders(
<Login isOpen onClose={vi.fn()} ariaLabelledBy="login-modal-heading"> <Login isOpen onClose={vi.fn()} ariaLabelledBy="login-modal-heading">
@@ -172,4 +181,30 @@ describe("Login", () => {
expect(screen.getByLabelText("Close")).toBeInTheDocument(); expect(screen.getByLabelText("Close")).toBeInTheDocument();
expect(screen.queryByLabelText("More options")).not.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" });
});
}); });
+25
View File
@@ -424,4 +424,29 @@ describe("LoginForm", () => {
expect(requestMagicLink).toHaveBeenCalledTimes(2); 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();
});
}); });
@@ -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 });
});
});