Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor NewsletterForm to use Formik #239

Merged
merged 2 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@repo/utils": "^0.0.0",
"@storybook/icons": "^1.2.9",
"copy-to-clipboard": "^3.3.3",
"formik": "^2.4.6",
"he": "^1.2.0",
"next": "^14.2.3",
"next-mdx-remote": "^5.0.0",
Expand Down
44 changes: 0 additions & 44 deletions packages/ui/src/newsletter-form/actions.ts

This file was deleted.

128 changes: 64 additions & 64 deletions packages/ui/src/newsletter-form/index.tsx
Original file line number Diff line number Diff line change
@@ -1,82 +1,82 @@
'use client';

import { cn } from '@repo/utils';
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { useFormState, useFormStatus } from 'react-dom';
import { CloseIcon } from '@storybook/icons';
import { saveNewsletter } from './actions';
import * as React from 'react';
import { Formik, type FormikValues } from 'formik';
import { useMailingListForm } from './use-mailing-list-form';

const initialState = {
message: '',
};
const validateForm = (values: FormikValues): FormikValues => {
if (!values.email) {
return { email: 'Required' };
}

function SubmitButton(): JSX.Element {
const { pending } = useFormStatus();
return {};
};

return (
<button
aria-disabled={pending}
className="ui-absolute ui-flex ui-items-center ui-justify-center ui-h-8 ui-gap-2 ui-px-2 ui-text-sm ui-font-bold ui-text-white ui-transition-all ui-duration-300 -ui-translate-y-1/2 ui-bg-blue-500 ui-rounded-md ui-whitespace-nowrap ui-ring-offset-white focus-visible:ui-outline-none focus-visible:ui-ring-2 focus-visible:ui-ring-blue-700 focus-visible:ui-ring-offset-2 disabled:ui-pointer-events-none disabled:ui-opacity-50 dark:ui-ring-offset-slate-950 dark:focus-visible:ui-ring-slate-300 hover:ui-bg-blue-600 ui-right-2 ui-top-1/2 group"
type="submit"
>
Subscribe
</button>
);
interface NewsletterFormProps {
onSubscribe?: () => void;
}

export const NewsletterForm: FC = () => {
const [state, formAction] = useFormState(saveNewsletter, initialState);
const [status, setStatus] = useState<'idle' | 'done' | 'error'>('idle');
const [email, setEmail] = useState('');
export const NewsletterForm = ({
onSubscribe,
}: NewsletterFormProps): React.ReactElement => {
const formRef = React.useRef<HTMLFormElement | null>(null);
const [hasSubmitted, onSubmitForm] = useMailingListForm(onSubscribe);

useEffect(() => {
if (state.message === 'ok') setStatus('done');
if (state.message && state.message !== 'ok') setStatus('error');
}, [state.message]);
React.useEffect(() => {
if (hasSubmitted && formRef.current) {
const submitButtonEl = formRef.current.querySelector('[type="submit"]');
if (submitButtonEl) {
(submitButtonEl as HTMLButtonElement).blur();
}
}
}, [formRef, hasSubmitted]);

return (
<form
action={formAction}
className="ui-relative ui-w-full ui-min-w-[360px] ui-h-12"
<Formik
initialValues={{ email: '' }}
validate={validateForm}
onSubmit={onSubmitForm}
>
{(status === 'done' || status === 'error') && (
<div
className={cn(
'ui-absolute ui-top-0 ui-left-0 ui-w-full ui-h-full ui-z-10 ui-rounded-md ui-flex ui-items-center ui-justify-between ui-px-4',
status === 'done' && 'ui-bg-green-300',
status === 'error' && 'ui-bg-red-300',
)}
{({ values, handleChange, handleBlur, handleSubmit, isSubmitting }) => (
<form
className="ui-relative ui-w-full ui-min-w-[360px] ui-h-12"
ref={formRef}
onSubmit={handleSubmit}
>
{status === 'done' && <div>Thanks, you are all signed up!</div>}
{status === 'error' && <div>Your email is invalid</div>}
<input
className="ui-rounded-md ui-pl-4 ui-pr-[100px] ui-w-full ui-h-full ui-transition-color ui-bg-white ui-text-zinc-800 dark:ui-bg-slate-900 ui-border ui-border-zinc-200 dark:ui-border-slate-700 dark:ui-text-white"
id="email"
type="email"
name="email"
value={values.email}
placeholder="[email protected]"
onChange={handleChange}
onBlur={handleBlur}
autoCapitalize="off"
autoCorrect="off"
/>
<button
onClick={() => {
setStatus('idle');
setEmail('');
state.message = '';
}}
type="button"
className="ui-absolute ui-flex ui-items-center ui-justify-center ui-h-8 ui-gap-2 ui-px-2 ui-text-sm ui-font-bold ui-text-white ui-transition-all ui-duration-300 -ui-translate-y-1/2 ui-bg-blue-500 ui-rounded-md ui-whitespace-nowrap ui-ring-offset-white focus-visible:ui-outline-none focus-visible:ui-ring-2 focus-visible:ui-ring-blue-700 focus-visible:ui-ring-offset-2 disabled:ui-pointer-events-none disabled:ui-opacity-50 dark:ui-ring-offset-slate-950 dark:focus-visible:ui-ring-slate-300 hover:ui-bg-blue-600 ui-right-2 ui-top-1/2 group"
type="submit"
aria-disabled={isSubmitting}
>
<CloseIcon />
Subscribe
</button>
</div>
{!hasSubmitted ? (
<div
className="ui-absolute ui-top-0 ui-left-0 ui-w-full ui-h-full ui-z-10 ui-rounded-md ui-flex ui-items-center ui-justify-between ui-px-4 ui-bg-green-600"
role="alert"
>
<b>
<span role="img" aria-label="thumbs up">
👍
</span>{' '}
Thanks, you&rsquo;re all signed up!
</b>
</div>
) : null}
</form>
)}
<input
className="ui-rounded-md ui-pl-4 ui-pr-[100px] ui-w-full ui-h-full ui-transition-color ui-bg-white ui-text-zinc-800 dark:ui-bg-slate-900 ui-border ui-border-zinc-200 dark:ui-border-slate-700 dark:ui-text-white"
id="email"
name="email"
onChange={(e) => {
setEmail(e.target.value);
}}
placeholder="[email protected]"
type="text"
value={email}
/>
<SubmitButton />
<p aria-live="polite" className="sr-only" role="status">
{state.message}
</p>
</form>
</Formik>
);
};
44 changes: 44 additions & 0 deletions packages/ui/src/newsletter-form/use-mailing-list-form.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as React from 'react';
import type { FormikValues } from 'formik';

const config = {
id: '18b5cea6e6',
url: 'https://storybook.us18.list-manage.com/subscribe/post',
server: 'us18',
fields: {
u: '06a6fce3ab1327784d4342396',
id: '18b5cea6e6',
},
};

type SubmitHandler = (values: FormikValues) => Promise<void>;

export function useMailingListForm(onSubscribe?: () => void): [boolean, SubmitHandler] {
const [hasSubmitted, setSubmitStatus] = React.useState(false);

const onSubmitForm: SubmitHandler = async (values) => {
const data = new FormData();
const fullFields = {
...config.fields,
MERGE0: values.email as string,
} as const;

Object.keys(fullFields).forEach((key) =>
{ data.append(key, fullFields[key as keyof typeof fullFields]); }
);

await fetch(config.url, {
method: 'POST',
body: data,
mode: 'no-cors',
});

if (onSubscribe) {
onSubscribe();
}

setSubmitStatus(true);
};

return [hasSubmitted, onSubmitForm];
}