Skip to content

Commit 0333ab9

Browse files
feat(mosaic): add internal Waitlist and Swingset previews (#10501)
Co-authored-by: Alex Carpenter <alex.carpenter@clerk.dev>
1 parent 0905976 commit 0333ab9

21 files changed

Lines changed: 770 additions & 6 deletions

‎.changeset/mosaic-waitlist-ci.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

‎.changeset/mosaic-waitlist.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

‎packages/mosaic/src/__tests__/feature/fake-fapi.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type {
1616
SessionWithActivitiesJSON,
1717
UserJSON,
1818
UserOrganizationInvitationJSON,
19+
WaitlistJSON,
1920
Web3WalletJSON,
2021
} from '@clerk/shared/types';
2122
import { http, HttpResponse } from 'msw';
@@ -77,6 +78,7 @@ export interface FakeFapiState {
7778
apiKeys: ApiKeyJSON[];
7879
verification: FakeVerificationState;
7980
passwordUpdates: URLSearchParams[];
81+
waitlistEntries: string[];
8082
enterpriseConnections: EnterpriseConnectionJSON[];
8183
enterpriseLinking: FakeEnterpriseLinking;
8284
mfa: FakeMfaState;
@@ -316,6 +318,7 @@ export function serveFapi(seed: FakeFapiSeed = {}): FakeFapiState {
316318
suggestions: [],
317319
apiKeys: [],
318320
passwordUpdates: [],
321+
waitlistEntries: [],
319322
enterpriseConnections: [],
320323
deviceTrackingEnabled: true,
321324
mfa: createMfaState(),
@@ -574,6 +577,33 @@ export function serveFapi(seed: FakeFapiSeed = {}): FakeFapiState {
574577
target.status = 'revoked';
575578
return envelope({ ...deviceSessionPayload(target), user: requester.user, status: 'revoked' }, state.client);
576579
}),
580+
http.post(fapiUrl('/v1/waitlist'), async ({ request }) => {
581+
const emailAddress = new URLSearchParams(await request.text()).get('email_address') ?? '';
582+
if (!/^[^\s@]+@[^\s@]+$/.test(emailAddress)) {
583+
return HttpResponse.json(
584+
{
585+
errors: [
586+
{
587+
code: 'form_param_format_invalid',
588+
message: 'is invalid',
589+
long_message: 'email_address must be a valid email address.',
590+
meta: { param_name: 'email_address' },
591+
},
592+
],
593+
},
594+
{ status: 422 },
595+
);
596+
}
597+
state.waitlistEntries.push(emailAddress);
598+
const now = Date.now();
599+
const entry: WaitlistJSON = {
600+
object: 'waitlist',
601+
id: `wle_${state.waitlistEntries.length}`,
602+
created_at: now,
603+
updated_at: now,
604+
};
605+
return envelope(entry, null);
606+
}),
577607
http.post(fapiUrl('/v1/me/change_password'), async ({ request }) => {
578608
const session = findSession(state, state.client.last_active_session_id);
579609
if (!session) {
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import { act, screen, waitFor } from '@testing-library/react';
2+
import userEvent from '@testing-library/user-event';
3+
import { describe, expect, it, onTestFinished, vi } from 'vitest';
4+
5+
import { holdRequests, serveFapi } from '../../../__tests__/feature/fake-fapi';
6+
import { fapiEnvironment } from '../../../__tests__/feature/fapi';
7+
import { renderWithClerk } from '../../../__tests__/feature/render';
8+
import type { WaitlistProps } from '../waitlist';
9+
import { Waitlist } from '../waitlist';
10+
11+
function renderWaitlist(props: WaitlistProps = {}) {
12+
return renderWithClerk(<Waitlist {...props} />);
13+
}
14+
15+
const emailField = () => screen.getByRole('textbox', { name: 'Email address' });
16+
const joinButton = () => screen.getByRole('button', { name: 'Join the waitlist' });
17+
18+
async function join(emailAddress: string) {
19+
const user = userEvent.setup();
20+
await user.type(await screen.findByRole('textbox', { name: 'Email address' }), emailAddress);
21+
await user.click(joinButton());
22+
return user;
23+
}
24+
25+
describe('Waitlist', () => {
26+
describe('joining', () => {
27+
it('adds the email address to the waitlist and thanks the user', async () => {
28+
const fapi = serveFapi();
29+
await renderWaitlist();
30+
31+
await join('alice@example.com');
32+
33+
expect(await screen.findByRole('heading', { name: 'Thanks for joining the waitlist!' })).toHaveFocus();
34+
expect(screen.getByText('We’ll be in touch when your spot is ready')).toBeInTheDocument();
35+
expect(fapi.waitlistEntries).toEqual(['alice@example.com']);
36+
expect(screen.queryByRole('status')).toBeNull();
37+
});
38+
39+
it('holds the form while the request is in flight', async () => {
40+
serveFapi();
41+
await renderWaitlist();
42+
const request = holdRequests('post', '/v1/waitlist');
43+
44+
await join('alice@example.com');
45+
46+
await waitFor(() => expect(request.requests).toHaveLength(1));
47+
expect(emailField()).toHaveAttribute('aria-disabled', 'true');
48+
await userEvent.setup().click(screen.getByRole('button', { name: /Join the waitlist/ }));
49+
expect(request.requests).toHaveLength(1);
50+
51+
request.release();
52+
expect(await screen.findByRole('heading', { name: 'Thanks for joining the waitlist!' })).toBeInTheDocument();
53+
});
54+
55+
it('cannot be submitted without an email address', async () => {
56+
serveFapi();
57+
await renderWaitlist();
58+
59+
await screen.findByRole('textbox', { name: 'Email address' });
60+
expect(joinButton()).toHaveAttribute('aria-disabled', 'true');
61+
});
62+
63+
it('fills in the email address from the query string', async () => {
64+
const originalUrl = window.location.href;
65+
window.history.replaceState(null, '', '?email_address=bob%40example.com');
66+
onTestFinished(() => window.history.replaceState(null, '', originalUrl));
67+
const fapi = serveFapi();
68+
await renderWaitlist();
69+
70+
expect(await screen.findByRole('textbox', { name: 'Email address' })).toHaveValue('bob@example.com');
71+
await userEvent.setup().click(joinButton());
72+
73+
await screen.findByRole('heading', { name: 'Thanks for joining the waitlist!' });
74+
expect(fapi.waitlistEntries).toEqual(['bob@example.com']);
75+
});
76+
});
77+
78+
describe('errors', () => {
79+
it('shows an invalid email address on the field', async () => {
80+
const fapi = serveFapi();
81+
await renderWaitlist();
82+
83+
await join('not-an-email');
84+
85+
await waitFor(() =>
86+
expect(emailField()).toHaveAccessibleDescription('Email address must be a valid email address.'),
87+
);
88+
expect(emailField()).toHaveAttribute('aria-invalid', 'true');
89+
expect(fapi.waitlistEntries).toEqual([]);
90+
expect(screen.queryByRole('heading', { name: 'Thanks for joining the waitlist!' })).toBeNull();
91+
});
92+
93+
it('shows a failure that names no field above the form, and lets the user try again', async () => {
94+
serveFapi();
95+
await renderWaitlist();
96+
const request = holdRequests('post', '/v1/waitlist');
97+
98+
await join('alice@example.com');
99+
await waitFor(() => expect(request.requests).toHaveLength(1));
100+
request.fail('waitlist_unavailable', 'The waitlist is not accepting new entries.');
101+
102+
await waitFor(() =>
103+
expect(screen.getByRole('alert')).toHaveTextContent('The waitlist is not accepting new entries.'),
104+
);
105+
expect(emailField()).toHaveValue('alice@example.com');
106+
expect(emailField()).not.toHaveAttribute('aria-disabled');
107+
expect(joinButton()).not.toHaveAttribute('aria-disabled');
108+
});
109+
});
110+
111+
describe('after joining', () => {
112+
it('sends the user to afterJoinWaitlistUrl once the thank-you has shown', async () => {
113+
serveFapi();
114+
const { navigate } = await renderWaitlist({ afterJoinWaitlistUrl: '/thanks' });
115+
vi.useFakeTimers({ shouldAdvanceTime: true });
116+
onTestFinished(() => {
117+
vi.useRealTimers();
118+
});
119+
120+
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
121+
await user.type(await screen.findByRole('textbox', { name: 'Email address' }), 'alice@example.com');
122+
await user.click(joinButton());
123+
124+
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('You will be redirected soon…'));
125+
expect(navigate).not.toHaveBeenCalled();
126+
127+
await act(() => vi.advanceTimersByTimeAsync(2000));
128+
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/thanks'));
129+
});
130+
});
131+
132+
describe('signing in', () => {
133+
it('goes to the application sign-in URL', async () => {
134+
serveFapi({ environment: fapiEnvironment({ display_config: { sign_in_url: '/login' } }) });
135+
const { navigate } = await renderWaitlist();
136+
137+
await userEvent.setup().click(await screen.findByRole('button', { name: 'Sign in' }));
138+
139+
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/login'));
140+
});
141+
142+
it('goes to signInUrl when one is passed', async () => {
143+
serveFapi();
144+
const { navigate } = await renderWaitlist({ signInUrl: '/custom-sign-in' });
145+
146+
await userEvent.setup().click(await screen.findByRole('button', { name: 'Sign in' }));
147+
148+
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/custom-sign-in'));
149+
});
150+
});
151+
152+
describe('branding', () => {
153+
it('signs the card when the instance is branded', async () => {
154+
serveFapi({ environment: fapiEnvironment({ display_config: { branded: true } }) });
155+
await renderWaitlist();
156+
157+
await screen.findByRole('textbox', { name: 'Email address' });
158+
expect(screen.getByText(/Secured by/)).toBeInTheDocument();
159+
});
160+
161+
it('carries no signature when the branding is paid off', async () => {
162+
serveFapi();
163+
await renderWaitlist();
164+
165+
await screen.findByRole('textbox', { name: 'Email address' });
166+
expect(screen.queryByText(/Secured by/)).toBeNull();
167+
});
168+
});
169+
});
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { useForm } from '../../components/form';
2+
import { setup } from '../../machine/setup';
3+
import { useMachine } from '../../machine/use-machine';
4+
import type { WaitlistModel } from './waitlist.types';
5+
import type { WaitlistViewProps } from './waitlist.view';
6+
7+
export const WAITLIST_REDIRECT_DELAY_MS = 2000;
8+
9+
interface WaitlistMachineContext {
10+
onRedirect: (() => void) | undefined;
11+
}
12+
13+
type WaitlistMachineEvent = { type: 'JOINED' };
14+
15+
const { createMachine } = setup<WaitlistMachineContext, WaitlistMachineEvent>();
16+
17+
const waitlistMachine = createMachine({
18+
id: 'waitlist',
19+
initial: 'form',
20+
context: { onRedirect: undefined },
21+
states: {
22+
form: {
23+
on: { JOINED: 'joined' },
24+
},
25+
joined: {
26+
after: {
27+
[WAITLIST_REDIRECT_DELAY_MS]: {
28+
guard: context => context.onRedirect !== undefined,
29+
actions: context => context.onRedirect?.(),
30+
},
31+
},
32+
},
33+
},
34+
});
35+
36+
export type WaitlistReadyModel = Extract<WaitlistModel, { status: 'ready' }>;
37+
38+
export function useWaitlistController(model: WaitlistReadyModel): WaitlistViewProps {
39+
const { initialEmailAddress, renderBranding, onJoinWaitlist, onSignIn, onRedirect } = model;
40+
const [snapshot, send] = useMachine(waitlistMachine, { context: { onRedirect } });
41+
const form = useForm({
42+
initialValues: { emailAddress: initialEmailAddress },
43+
canSubmit: values => values.emailAddress.trim() !== '',
44+
onSubmit: async values => {
45+
await onJoinWaitlist(values.emailAddress);
46+
send({ type: 'JOINED' });
47+
},
48+
});
49+
50+
return {
51+
step: snapshot.value === 'form' ? 'form' : 'joined',
52+
form,
53+
renderBranding,
54+
isRedirecting: onRedirect !== undefined,
55+
onSignIn,
56+
};
57+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export const waitlistMessages = {
2+
start: {
3+
title: 'Join the waitlist',
4+
description: 'Enter your email address and we’ll let you know when your spot is ready',
5+
emailLabel: 'Email address',
6+
emailPlaceholder: 'Enter your email address',
7+
submit: 'Join the waitlist',
8+
pending: 'Joining the waitlist',
9+
},
10+
success: {
11+
title: 'Thanks for joining the waitlist!',
12+
description: 'We’ll be in touch when your spot is ready',
13+
redirecting: 'You will be redirected soon…',
14+
},
15+
signIn: {
16+
text: 'Already have access?',
17+
action: 'Sign in',
18+
},
19+
} as const;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { useClerk } from '@clerk/shared/react';
2+
import type { WaitlistProps } from '@clerk/shared/types';
3+
4+
import { useMosaicEnvironment } from '../../hooks/use-mosaic-environment';
5+
import { useMosaicRouter } from '../../hooks/use-mosaic-router';
6+
import { save } from '../../utils/errors';
7+
import type { WaitlistField, WaitlistModel } from './waitlist.types';
8+
9+
export type WaitlistModelOptions = Pick<WaitlistProps, 'afterJoinWaitlistUrl' | 'signInUrl'>;
10+
11+
const WAITLIST_FIELDS: readonly WaitlistField[] = ['emailAddress'];
12+
13+
export function useWaitlistModel(options: WaitlistModelOptions = {}): WaitlistModel {
14+
const clerk = useClerk();
15+
const environment = useMosaicEnvironment();
16+
const router = useMosaicRouter();
17+
18+
if (!clerk.loaded || !environment) {
19+
return { status: 'loading' };
20+
}
21+
22+
const { displayConfig } = environment;
23+
const signInUrl = options.signInUrl || clerk.__internal_getOption('signInUrl') || displayConfig.signInUrl;
24+
const { afterJoinWaitlistUrl } = options;
25+
26+
return {
27+
status: 'ready',
28+
initialEmailAddress: router.getSearchParams().get('email_address') ?? '',
29+
renderBranding: displayConfig.branded,
30+
onJoinWaitlist: emailAddress => save(() => clerk.joinWaitlist({ emailAddress }), WAITLIST_FIELDS),
31+
onSignIn: () => void router.navigate(clerk.buildUrlWithAuth(signInUrl)),
32+
onRedirect: afterJoinWaitlistUrl ? () => void router.navigate(afterJoinWaitlistUrl) : undefined,
33+
};
34+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import * as stylex from '@stylexjs/stylex';
2+
3+
import { space } from '../../tokens.stylex';
4+
5+
export const styles = stylex.create({
6+
redirecting: {
7+
gap: space['2'],
8+
alignItems: 'center',
9+
display: 'flex',
10+
justifyContent: 'center',
11+
},
12+
footer: {
13+
justifyContent: 'center',
14+
},
15+
footerText: {
16+
textAlign: 'center',
17+
},
18+
});

0 commit comments

Comments
 (0)