1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210import { useCallback, useEffect, useRef, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { ErrorAlert, toast } from '~/components/alerts';
import { Button } from '~/components/buttons';
import { InputOTP, InputOTPGroup, InputOTPSlot } from '~/components/inputs';
import { useAuth } from '~/hooks/useAuth';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '..';
const OTPSchema = z.object({
pin: z.string().min(6, {
message: 'Your verification code must be 6 characters.',
}),
});
type OTPFormInputs = z.infer<typeof OTPSchema>;
interface OTPValidationFormProps {
email: string;
type: 'signup' | 'login';
}
const RESEND_TIMEOUT = 60;
const OTPValidationForm: React.FC<OTPValidationFormProps> = ({
email,
type,
}) => {
const errorAlertRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const announcerRef = useRef<HTMLDivElement>(null);
const [countdown, setCountdown] = useState<number>(RESEND_TIMEOUT);
const [isCountingDown, setIsCountingDown] = useState(false);
const {
confirmSignUp,
resendSignUpCode,
loading,
error: confirmSignUpError,
clearErrors,
} = useAuth();
const form = useForm<OTPFormInputs>({
resolver: zodResolver(OTPSchema),
defaultValues: {
pin: '',
},
});
useEffect(() => {
if (isCountingDown) {
const interval = setInterval(() => {
setCountdown((currentCountdown) => {
const newTimeLeft = currentCountdown - 1;
if (newTimeLeft < 0) {
clearInterval(interval as unknown as number);
return currentCountdown;
} else {
return newTimeLeft;
}
});
}, 1000) as unknown as number;
return () => clearInterval(interval as unknown as number);
}
}, [isCountingDown]);
useEffect(() => {
if (announcerRef.current) {
announcerRef.current.innerText =
'Please enter the verification code sent to your email.';
}
const timeoutId = setTimeout(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, 5000);
return () => clearTimeout(timeoutId);
}, []);
const handleResendCode = useCallback(async () => {
await resendSignUpCode(email);
setIsCountingDown(true);
setCountdown(RESEND_TIMEOUT);
toast.success({
title: 'Success',
description: 'Verification code resent successfully.',
});
}, [email, resendSignUpCode]);
const onSubmit = async (values: OTPFormInputs) => {
const { isSignUpComplete } = await confirmSignUp({
username: email,
confirmationCode: values.pin,
});
if (isSignUpComplete) {
toast.success({
title: 'Success',
description: 'Account verified successfully.',
});
}
};
const handleFocus = () => {
clearErrors();
};
return (
<Form {...form}>
<div ref={announcerRef} className="sr-only" aria-live="assertive"></div>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="w-full max-w-md space-y-4"
>
{confirmSignUpError && (
<ErrorAlert
error={confirmSignUpError.message}
className="mb-4"
ref={errorAlertRef}
/>
)}
<FormField
control={form.control}
name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>Verification Code</FormLabel>
<FormControl>
<InputOTP
maxLength={6}
{...field}
ref={inputRef}
onFocus={handleFocus}
>
<InputOTPGroup>
{Array.from({ length: 6 }).map((_, index) => (
<InputOTPSlot
key={index}
index={index}
className="size-12 bg-white"
/>
))}
</InputOTPGroup>
</InputOTP>
</FormControl>
<FormDescription>
Please enter the verification code sent to {email}.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-6">
<Button
onClick={handleResendCode}
disabled={isCountingDown || loading}
className="place-self-start bg-transparent p-0 text-gray-600 shadow-none"
aria-live="polite"
aria-disabled={isCountingDown || loading}
aria-label={
isCountingDown ? `Resend in ${countdown}s` : 'Resend code'
}
>
{isCountingDown ? `Resend in ${countdown}s` : 'Resend code'}
</Button>
<Button
type="submit"
className="h-12 w-full bg-[#1D781D] text-white"
disabled={loading}
aria-live="polite"
aria-label={
loading
? 'Processing,please wait'
: type === 'signup'
? 'Verify and Sign Up'
: 'Verify and Log In'
}
>
{loading ? (
<>
<span className="sr-only">Processing, please wait...</span>
<div
role="status"
className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-t-transparent"
></div>
</>
) : type === 'signup' ? (
'Verify and Sign Up'
) : (
'Verify and Log In'
)}
</Button>
</div>
</form>
</Form>
);
};
export default OTPValidationForm;