webapp/src/components/Nav/AuthModal/RegisterForm.tsx

275 lines
8.6 KiB
TypeScript
Raw Normal View History

2022-10-25 16:25:42 +00:00
import type { JSX } from 'solid-js'
2024-02-08 17:30:27 +00:00
import { Show, createMemo, createSignal } from 'solid-js'
2024-02-04 11:25:21 +00:00
import type { AuthModalSearchParams } from './types'
2022-10-25 16:25:42 +00:00
import { clsx } from 'clsx'
import { useLocalize } from '../../../context/localize'
2023-12-15 13:45:34 +00:00
import { useSession } from '../../../context/session'
2022-10-25 16:25:42 +00:00
import { useRouter } from '../../../stores/router'
import { hideModal } from '../../../stores/ui'
import { validateEmail } from '../../../utils/validateEmail'
2022-10-25 16:25:42 +00:00
import { AuthModalHeader } from './AuthModalHeader'
import { PasswordField } from './PasswordField'
import { SocialProviders } from './SocialProviders'
2024-02-04 11:25:21 +00:00
import { email, setEmail } from './sharedLogic'
2024-02-08 18:36:05 +00:00
import { GenericResponse } from '@authorizerdev/authorizer-js'
import styles from './AuthModal.module.scss'
2024-02-08 15:37:17 +00:00
type EmailStatus = 'not verified' | 'verified' | 'registered' | ''
2022-10-25 16:25:42 +00:00
type FormFields = {
fullName: string
2022-10-25 16:25:42 +00:00
email: string
password: string
}
type ValidationErrors = Partial<Record<keyof FormFields, string | JSX.Element>>
const handleEmailInput = (newEmail: string) => {
2024-01-13 14:22:04 +00:00
setEmail(newEmail.toLowerCase())
}
2022-10-25 16:25:42 +00:00
export const RegisterForm = () => {
const { changeSearchParams } = useRouter<AuthModalSearchParams>()
2023-02-17 09:21:02 +00:00
const { t } = useLocalize()
2024-02-06 14:34:27 +00:00
const { signUp, isRegistered, resendVerifyEmail } = useSession()
2022-10-25 16:25:42 +00:00
const [submitError, setSubmitError] = createSignal('')
const [fullName, setFullName] = createSignal('')
2022-10-25 16:25:42 +00:00
const [password, setPassword] = createSignal('')
const [isSubmitting, setIsSubmitting] = createSignal(false)
const [isSuccess, setIsSuccess] = createSignal(false)
const [validationErrors, setValidationErrors] = createSignal<ValidationErrors>({})
const [passwordError, setPasswordError] = createSignal<string>()
2024-02-06 14:34:27 +00:00
const [emailStatus, setEmailStatus] = createSignal<string>('')
2022-10-25 16:25:42 +00:00
const authFormRef: { current: HTMLFormElement } = { current: null }
const handleNameInput = (newName: string) => {
setFullName(newName)
2022-10-25 16:25:42 +00:00
}
const handleSubmit = async (event: Event) => {
event.preventDefault()
if (passwordError()) {
setValidationErrors((errors) => ({ ...errors, password: passwordError() }))
2023-08-21 11:11:18 +00:00
} else {
setValidationErrors(({ password: _notNeeded, ...rest }) => rest)
}
setValidationErrors(({ email: _notNeeded, ...rest }) => rest)
setValidationErrors(({ fullName: _notNeeded, ...rest }) => rest)
2022-10-25 16:25:42 +00:00
setSubmitError('')
const newValidationErrors: ValidationErrors = {}
const cleanName = fullName().trim()
const cleanEmail = email().trim()
if (!cleanName) {
newValidationErrors.fullName = t('Please enter a name to sign your comments and publication')
2022-10-25 16:25:42 +00:00
}
if (!cleanEmail) {
2022-10-25 16:25:42 +00:00
newValidationErrors.email = t('Please enter email')
} else if (!validateEmail(email())) {
2022-10-25 16:25:42 +00:00
newValidationErrors.email = t('Invalid email')
}
if (!password()) {
newValidationErrors.password = t('Please enter password')
}
setValidationErrors(newValidationErrors)
2024-02-06 14:34:27 +00:00
const isValid = createMemo(() => Object.keys(newValidationErrors).length === 0)
if (!isValid()) {
authFormRef.current
.querySelector<HTMLInputElement>(`input[name="${Object.keys(newValidationErrors)[0]}"]`)
.focus()
2022-10-25 16:25:42 +00:00
return
}
setIsSubmitting(true)
try {
2023-12-24 08:16:41 +00:00
const opts = {
2023-11-28 18:04:51 +00:00
given_name: cleanName,
email: cleanEmail,
password: password(),
2023-11-28 18:04:51 +00:00
confirm_password: password(),
2023-12-03 10:22:42 +00:00
redirect_uri: window.location.origin,
2023-12-24 08:16:41 +00:00
}
2024-02-01 20:34:53 +00:00
const { errors } = await signUp(opts)
2024-02-08 15:37:17 +00:00
if (errors) return
setIsSuccess(true)
} catch (error) {
console.error(error)
} finally {
setIsSubmitting(false)
}
}
2024-02-08 18:36:05 +00:00
const handleResendLink = async (_ev) => {
const response: GenericResponse = await resendVerifyEmail({
email: email(),
identifier: 'basic_signup',
})
setIsSuccess(response?.message === 'Verification email has been sent. Please check your inbox')
}
2024-02-08 15:37:17 +00:00
const handleCheckEmailStatus = (status: EmailStatus | string) => {
switch (status) {
case 'not verified':
2024-02-01 20:34:53 +00:00
setValidationErrors((prev) => ({
...prev,
email: (
<>
2024-02-08 15:37:17 +00:00
{t('This email is not verified')},{' '}
2024-02-08 18:36:05 +00:00
<span class="link" onClick={handleResendLink}>
2024-02-08 15:37:17 +00:00
{t('resend confirmation link')}
2024-02-01 20:34:53 +00:00
</span>
</>
),
}))
2024-02-08 15:37:17 +00:00
break
case 'verified':
setValidationErrors((prev) => ({
2024-02-15 17:49:12 +00:00
email: (
<>
{t('This email is verified')}. {t('You can')}
2024-02-15 18:09:26 +00:00
<span class="link" onClick={() => changeSearchParams({ mode: 'login' })}>
{t('enter')}
</span>
2024-02-15 17:49:12 +00:00
</>
),
2024-02-08 15:37:17 +00:00
}))
break
case 'registered':
2024-02-15 17:49:12 +00:00
setValidationErrors((prev) => ({
...prev,
2024-02-08 15:37:17 +00:00
email: (
<>
2024-02-08 18:36:05 +00:00
{t('This email is registered')}. {t('You can')}{' '}
2024-02-08 15:37:17 +00:00
<span class="link" onClick={() => changeSearchParams({ mode: 'send-reset-link' })}>
{t('Set the new password').toLocaleLowerCase()}
</span>
</>
),
}))
break
default:
2024-02-08 17:30:27 +00:00
console.info('[RegisterForm] email is not registered')
2024-02-08 15:37:17 +00:00
break
}
}
const handleEmailBlur = async () => {
if (validateEmail(email())) {
const checkResult = await isRegistered(email())
2024-02-08 17:30:27 +00:00
setEmailStatus(checkResult)
2024-02-08 15:37:17 +00:00
handleCheckEmailStatus(checkResult)
2022-10-25 16:25:42 +00:00
}
}
return (
<>
<Show when={!isSuccess()}>
<form onSubmit={handleSubmit} class={styles.authForm} ref={(el) => (authFormRef.current = el)}>
2023-05-18 20:02:19 +00:00
<div>
<AuthModalHeader modalType="register" />
2023-05-18 20:02:19 +00:00
<Show when={submitError()}>
<div class={styles.authInfo}>
2024-01-27 06:21:48 +00:00
<div class={styles.warn}>{submitError()}</div>
2023-05-18 20:02:19 +00:00
</div>
</Show>
<div
class={clsx('pretty-form__item', {
'pretty-form__item--error': validationErrors().fullName,
})}
>
2023-05-18 20:02:19 +00:00
<input
name="fullName"
type="text"
2024-02-08 17:42:07 +00:00
disabled={Boolean(emailStatus())}
2023-05-18 20:02:19 +00:00
placeholder={t('Full name')}
2024-02-08 15:37:17 +00:00
autocomplete="one-time-code"
2023-05-18 20:02:19 +00:00
onInput={(event) => handleNameInput(event.currentTarget.value)}
/>
<label for="name">{t('Full name')}</label>
2024-02-08 17:42:07 +00:00
<Show when={validationErrors().fullName && !emailStatus()}>
2023-08-30 21:30:15 +00:00
<div class={styles.validationError}>{validationErrors().fullName}</div>
</Show>
2022-10-25 16:25:42 +00:00
</div>
2023-08-30 21:30:15 +00:00
<div
class={clsx('pretty-form__item', {
2024-02-08 17:30:27 +00:00
'pretty-form__item--error': validationErrors().email && !emailStatus(),
})}
>
2023-05-18 20:02:19 +00:00
<input
id="email"
name="email"
2024-02-08 15:37:17 +00:00
autocomplete="one-time-code"
2023-05-18 20:02:19 +00:00
type="email"
placeholder={t('Email')}
onInput={(event) => handleEmailInput(event.currentTarget.value)}
onBlur={handleEmailBlur}
/>
<label for="email">{t('Email')}</label>
2024-02-08 17:42:07 +00:00
<div class={clsx(styles.validationError, { info: Boolean(emailStatus()) })}>
2024-02-08 16:42:52 +00:00
{validationErrors().email}
</div>
2022-10-25 16:25:42 +00:00
</div>
2023-08-30 21:30:15 +00:00
2024-02-15 18:09:26 +00:00
<PasswordField
disableAutocomplete={true}
disabled={Boolean(emailStatus())}
errorMessage={(err) => setPasswordError(err)}
onInput={(value) => setPassword(value)}
/>
2023-05-18 20:02:19 +00:00
<div>
2024-02-15 18:09:26 +00:00
<button
class={clsx('button', styles.submitButton)}
disabled={isSubmitting() || Boolean(emailStatus())}
type="submit"
2024-02-15 17:49:12 +00:00
>
2024-02-15 18:09:26 +00:00
{isSubmitting() ? '...' : t('Join')}
</button>
</div>
2022-10-25 16:25:42 +00:00
</div>
2023-05-18 20:02:19 +00:00
<div>
<SocialProviders />
2022-10-25 16:25:42 +00:00
2023-05-18 20:02:19 +00:00
<div class={styles.authControl}>
<span
class={styles.authLink}
onClick={() =>
changeSearchParams({
mode: 'login',
})
}
>
2023-05-18 20:02:19 +00:00
{t('I have an account')}
</span>
</div>
2022-10-25 16:25:42 +00:00
</div>
</form>
</Show>
<Show when={isSuccess()}>
<div class={styles.title}>{t('Almost done! Check your email.')}</div>
<div class={styles.text}>{t("We've sent you a message with a link to enter our website.")}</div>
<div>
<button class={clsx('button', styles.submitButton)} onClick={() => hideModal()}>
{t('Back to main page')}
</button>
</div>
</Show>
</>
)
}