confirm-email-form.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import { postJSON } from '@/infrastructure/fetch-json'
  2. import useWaitForI18n from '@/shared/hooks/use-wait-for-i18n'
  3. import Notification from '@/shared/components/notification'
  4. import getMeta from '@/utils/meta'
  5. import {
  6. ChangeEventHandler,
  7. ComponentProps,
  8. FormEvent,
  9. MouseEventHandler,
  10. useState,
  11. } from 'react'
  12. import { Trans, useTranslation } from 'react-i18next'
  13. import LoadingSpinner from '@/shared/components/loading-spinner'
  14. import { sendMB } from '@/infrastructure/event-tracking'
  15. import OLFormLabel from '@/shared/components/ol/ol-form-label'
  16. import OLButton from '@/shared/components/ol/ol-button'
  17. import { useLocation } from '@/shared/hooks/use-location'
  18. import DSFormLabel from '@/shared/components/ds/ds-form-label'
  19. import DSButton from '@/shared/components/ds/ds-button'
  20. import CIAMSixDigitsInput from '@/features/settings/components/emails/ciam-six-digits-input'
  21. import OLFormText from '@/shared/components/ol/ol-form-text'
  22. import DSFormText from '@/shared/components/ds/ds-form-text'
  23. import { CaretRight } from '@phosphor-icons/react'
  24. import DSNotification from '@/shared/components/ds/ds-notification'
  25. type Feedback = {
  26. type: 'input' | 'alert'
  27. style: 'error' | 'info'
  28. message: string
  29. }
  30. type ConfirmEmailFormProps = {
  31. confirmationEndpoint: string
  32. flow: 'registration' | 'resend' | 'secondary'
  33. resendEndpoint: string
  34. successMessage?: React.ReactNode
  35. successButtonText?: string
  36. email?: string
  37. onSuccessfulConfirmation?: () => void
  38. interstitial: boolean
  39. isModal?: boolean
  40. onCancel?: MouseEventHandler<HTMLButtonElement>
  41. outerError?: string
  42. isCiam?: boolean
  43. }
  44. const OLSixDigitsInput = (props: ComponentProps<'input'>) => (
  45. <input
  46. inputMode="numeric"
  47. maxLength={6}
  48. className="form-control"
  49. {...props}
  50. />
  51. )
  52. export function ConfirmEmailForm({
  53. confirmationEndpoint,
  54. flow,
  55. resendEndpoint,
  56. successMessage,
  57. successButtonText,
  58. email = getMeta('ol-email'),
  59. onSuccessfulConfirmation,
  60. interstitial,
  61. isModal,
  62. onCancel,
  63. outerError,
  64. isCiam,
  65. }: ConfirmEmailFormProps) {
  66. const { t } = useTranslation()
  67. const [confirmationCode, setConfirmationCode] = useState('')
  68. const [feedback, setFeedback] = useState<Feedback | null>(null)
  69. const [isConfirming, setIsConfirming] = useState(false)
  70. const [isResending, setIsResending] = useState(false)
  71. const [hasResent, setHasResent] = useState(false)
  72. const [successRedirectPath, setSuccessRedirectPath] = useState('')
  73. const { isReady } = useWaitForI18n()
  74. const outerErrorDisplay = (!hasResent && outerError) || null
  75. const errorHandler = (err: any, actionType?: string) => {
  76. let errorName = err?.data?.message?.key || 'generic_something_went_wrong'
  77. if (err?.response?.status === 429) {
  78. if (actionType === 'confirm') {
  79. errorName = 'too_many_confirm_code_verification_attempts'
  80. } else if (actionType === 'resend') {
  81. errorName = 'too_many_confirm_code_resend_attempts'
  82. }
  83. setFeedback({
  84. type: 'alert',
  85. style: 'error',
  86. message: errorName,
  87. })
  88. } else {
  89. setFeedback({
  90. type: 'input',
  91. style: 'error',
  92. message: errorName,
  93. })
  94. }
  95. sendMB('email-verification-error', {
  96. errorName,
  97. flow,
  98. })
  99. }
  100. const invalidFormHandler = () => {
  101. if (!confirmationCode) {
  102. return setFeedback({
  103. type: 'input',
  104. style: 'error',
  105. message: 'please_enter_confirmation_code',
  106. })
  107. }
  108. }
  109. const submitHandler = async (e: FormEvent<HTMLFormElement>) => {
  110. e.preventDefault()
  111. setIsConfirming(true)
  112. setFeedback(null)
  113. sendMB('email-verification-click', {
  114. button: 'verify',
  115. flow,
  116. })
  117. try {
  118. const data = await postJSON(confirmationEndpoint, {
  119. body: { code: confirmationCode },
  120. })
  121. if (onSuccessfulConfirmation) {
  122. onSuccessfulConfirmation()
  123. } else {
  124. setSuccessRedirectPath(data?.redir || '/')
  125. }
  126. } catch (err) {
  127. errorHandler(err, 'confirm')
  128. } finally {
  129. setIsConfirming(false)
  130. }
  131. }
  132. const resendHandler: MouseEventHandler<HTMLButtonElement> = () => {
  133. setIsResending(true)
  134. setFeedback(null)
  135. postJSON(resendEndpoint)
  136. .then(data => {
  137. setIsResending(false)
  138. if (data?.message?.key) {
  139. setFeedback({
  140. type: 'alert',
  141. style: 'info',
  142. message: data.message.key,
  143. })
  144. }
  145. })
  146. .catch(err => {
  147. errorHandler(err, 'resend')
  148. })
  149. .finally(() => {
  150. setIsResending(false)
  151. setHasResent(true)
  152. })
  153. sendMB('email-verification-click', {
  154. button: 'resend',
  155. flow,
  156. })
  157. }
  158. const changeHandler: ChangeEventHandler<HTMLInputElement> = e => {
  159. setConfirmationCode(e.currentTarget.value)
  160. setFeedback(null)
  161. }
  162. if (!isReady) {
  163. return <LoadingSpinner />
  164. }
  165. if (successRedirectPath && successButtonText && successMessage) {
  166. return (
  167. <ConfirmEmailSuccessfulForm
  168. successMessage={successMessage}
  169. successButtonText={successButtonText}
  170. redirectTo={successRedirectPath}
  171. isCiam={Boolean(isCiam)}
  172. />
  173. )
  174. }
  175. const longLabel = isModal ? (
  176. t('enter_the_code', { email })
  177. ) : (
  178. <Trans
  179. i18nKey="enter_the_confirmation_code"
  180. components={[isCiam ? <strong /> : <span />]}
  181. values={{ email }}
  182. shouldUnescape
  183. tOptions={{ interpolation: { escapeValue: true } }}
  184. />
  185. )
  186. const Button = isCiam ? DSButton : OLButton
  187. const buttonSize = isCiam ? 'lg' : undefined
  188. const SixDigits = isCiam ? CIAMSixDigitsInput : OLSixDigitsInput
  189. const FormText = isCiam ? DSFormText : OLFormText
  190. const NotificationComponent = isCiam ? DSNotification : Notification
  191. const outerErrorEl = (feedback?.type === 'alert' || outerErrorDisplay) && (
  192. <NotificationComponent
  193. ariaLive="polite"
  194. className="confirm-email-alert"
  195. type={outerErrorDisplay ? 'error' : feedback!.style}
  196. content={outerErrorDisplay || <ErrorMessage error={feedback!.message!} />}
  197. />
  198. )
  199. return (
  200. <form
  201. onSubmit={submitHandler}
  202. onInvalid={invalidFormHandler}
  203. className="confirm-email-form"
  204. data-testid="confirm-email-form"
  205. >
  206. <div className="confirm-email-form-inner">
  207. {!isCiam && outerErrorEl}
  208. <Title
  209. isModal={isModal}
  210. interstitial={interstitial}
  211. isCiam={isCiam}
  212. outerErrorDisplay={outerErrorDisplay}
  213. />
  214. {isCiam && outerErrorEl}
  215. {isCiam && <p>{longLabel}</p>}
  216. {isCiam ? (
  217. <DSFormLabel htmlFor="one-time-code">
  218. {t('verification_code')}
  219. </DSFormLabel>
  220. ) : (
  221. <OLFormLabel htmlFor="one-time-code">{longLabel}</OLFormLabel>
  222. )}
  223. <SixDigits
  224. id="one-time-code"
  225. required
  226. value={confirmationCode}
  227. onChange={changeHandler}
  228. data-ol-dirty={feedback ? 'true' : undefined}
  229. autoComplete="one-time-code"
  230. autoFocus // eslint-disable-line jsx-a11y/no-autofocus
  231. disabled={!!outerErrorDisplay}
  232. />
  233. <div aria-live="polite">
  234. {feedback?.type === 'input' && (
  235. <FormText type="error" marginless>
  236. <ErrorMessage error={feedback.message} />
  237. </FormText>
  238. )}
  239. </div>
  240. <div className="form-actions">
  241. <Button
  242. size={buttonSize}
  243. disabled={isResending || !!outerErrorDisplay}
  244. type="submit"
  245. isLoading={isConfirming}
  246. loadingLabel={t('confirming')}
  247. >
  248. {t('confirm')}
  249. </Button>
  250. <Button
  251. variant="secondary"
  252. size={buttonSize}
  253. disabled={isConfirming}
  254. onClick={resendHandler}
  255. isLoading={isResending}
  256. loadingLabel={t('resending_confirmation_code')}
  257. >
  258. {t('resend_confirmation_code')}
  259. </Button>
  260. {onCancel && (
  261. <OLButton
  262. variant="danger-ghost"
  263. disabled={isConfirming || isResending}
  264. onClick={onCancel}
  265. >
  266. {t('cancel')}
  267. </OLButton>
  268. )}
  269. </div>
  270. {isCiam && flow === 'registration' && (
  271. <div className="mt-4 mb-2 text-center ">
  272. <Trans
  273. i18nKey="use_a_different_email"
  274. components={[
  275. // eslint-disable-next-line react/jsx-key, jsx-a11y/anchor-has-content
  276. <a
  277. href="/register"
  278. onClick={() =>
  279. sendMB('email-verification-click', {
  280. button: 'change-email',
  281. flow,
  282. })
  283. }
  284. />,
  285. ]}
  286. />
  287. </div>
  288. )}
  289. </div>
  290. </form>
  291. )
  292. }
  293. function Title({
  294. isModal,
  295. interstitial,
  296. outerErrorDisplay,
  297. isCiam,
  298. }: {
  299. isModal?: boolean
  300. interstitial: boolean
  301. isCiam?: boolean
  302. outerErrorDisplay: string | null
  303. }) {
  304. const { t } = useTranslation()
  305. if (isCiam) return <h1>{t('verify_your_email_address')}</h1>
  306. if (isModal)
  307. return outerErrorDisplay ? (
  308. <div className="mt-4" />
  309. ) : (
  310. <h3 className="h5">{outerErrorDisplay ? null : t('we_sent_code')}</h3>
  311. )
  312. if (interstitial)
  313. return <h1 className="h3 interstitial-header">{t('confirm_your_email')}</h1>
  314. return <h5 className="h5">{t('confirm_your_email')}</h5>
  315. }
  316. function ConfirmEmailSuccessfulForm({
  317. successMessage,
  318. successButtonText,
  319. redirectTo,
  320. isCiam,
  321. }: {
  322. successMessage: React.ReactNode
  323. successButtonText: string
  324. redirectTo: string
  325. isCiam: boolean
  326. }) {
  327. const location = useLocation()
  328. const submitHandler = (e: FormEvent<HTMLFormElement>) => {
  329. e.preventDefault()
  330. location.assign(redirectTo)
  331. }
  332. const button = isCiam ? (
  333. <DSButton
  334. type="submit"
  335. variant="primary"
  336. size="lg"
  337. className="w-100"
  338. trailingIcon={<CaretRight size={24} />}
  339. >
  340. {successButtonText}
  341. </DSButton>
  342. ) : (
  343. <OLButton type="submit" variant="primary">
  344. {successButtonText}
  345. </OLButton>
  346. )
  347. return (
  348. <form onSubmit={submitHandler} className="confirm-email-success-form">
  349. <div aria-live="polite">{successMessage}</div>
  350. <div className="form-actions">{button}</div>
  351. </form>
  352. )
  353. }
  354. function ErrorMessage({ error }: { error: string }) {
  355. const { t } = useTranslation()
  356. switch (error) {
  357. case 'invalid_confirmation_code':
  358. return <span>{t('invalid_confirmation_code')}</span>
  359. case 'expired_confirmation_code':
  360. return (
  361. <Trans
  362. i18nKey="expired_confirmation_code"
  363. /* eslint-disable-next-line react/jsx-key */
  364. components={[<strong />]}
  365. />
  366. )
  367. case 'email_already_registered':
  368. return <span>{t('email_already_registered')}</span>
  369. case 'email_does_not_belong_to_university':
  370. return <span>{t('email_does_not_belong_to_university')}</span>
  371. case 'too_many_confirm_code_resend_attempts':
  372. return <span>{t('too_many_confirm_code_resend_attempts')}</span>
  373. case 'too_many_confirm_code_verification_attempts':
  374. return <span>{t('too_many_confirm_code_verification_attempts')}</span>
  375. case 'we_sent_new_code':
  376. return <span>{t('we_sent_new_code')}</span>
  377. case 'please_enter_confirmation_code':
  378. return <span>{t('please_enter_confirmation_code')}</span>
  379. default:
  380. return <span>{t('generic_something_went_wrong')}</span>
  381. }
  382. }