📦 EqualifyEverything / equalify-dashboard

📄 login-form.tsx · 220 lines
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
210
211
212
213
214
215
216
217
218
219
220import { useEffect, useRef, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  ArrowTopRightIcon,
  EyeClosedIcon,
  EyeOpenIcon,
} from '@radix-ui/react-icons';
import { useForm } from 'react-hook-form';
import { Link } from 'react-router-dom';
import { z } from 'zod';

import { ErrorAlert, toast } from '~/components/alerts';
import { Button } from '~/components/buttons';
import { Input } from '~/components/inputs';
import { useAuth } from '~/hooks/useAuth';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  OTPValidationForm,
} from '..';

const LoginSchema = z.object({
  email: z.string().email({
    message: 'Please enter a valid email address.',
  }),
  password: z.string().min(1, {
    message: "Password can't be empty.",
  }),
});

type LoginFormInputs = z.infer<typeof LoginSchema>;

const LoginForm = () => {
  const errorAlertRef = useRef<HTMLDivElement>(null);
  const {
    signIn,
    loading,
    error: signInError,
    clearErrors,
    needsConfirmation,
    cancelConfirmation,
    pendingUsername,
  } = useAuth();

  const form = useForm<LoginFormInputs>({
    resolver: zodResolver(LoginSchema),
    defaultValues: {
      email: '',
      password: '',
    },
  });

  const onSubmit = async (values: LoginFormInputs) => {
    try {
      const { success, confirmationRequired } = await signIn({
        username: values.email,
        password: values.password,
      });

      if (success) {
        toast.success({
          title: 'Success',
          description: 'Login successful. Redirecting to reports page.',
        });
      } else if (confirmationRequired) {
        toast.success({
          title: 'Success',
          description:
            'Email not confirmed. A code has been sent to your email.',
        });
      }
    } catch (error) {
      toast.error({
        title: 'Success',
        description: 'Login failed. Please try again.',
      });
    }
  };

  const [showPassword, setShowPassword] = useState(false);
  const togglePasswordVisibility = () => setShowPassword(!showPassword);

  useEffect(() => {
    if (signInError) errorAlertRef.current?.focus();
  }, [signInError]);

  useEffect(() => {
    return () => {
      clearErrors();
      cancelConfirmation();
    };
  }, [clearErrors, cancelConfirmation]);

  if (needsConfirmation && pendingUsername) {
    return <OTPValidationForm email={pendingUsername} type="login" />;
  }

  return (
    <>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="w-full max-w-md space-y-4"
        >
          {signInError && (
            <ErrorAlert
              error={signInError.message}
              className="mb-4"
              ref={errorAlertRef}
            />
          )}
          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel htmlFor="email">Email</FormLabel>
                <FormControl>
                  <Input
                    type="email"
                    className="h-12 bg-white"
                    id="email"
                    aria-required={true}
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <FormLabel htmlFor="password">Password</FormLabel>
                <FormControl>
                  <div className="relative">
                    <Input
                      type={showPassword ? 'text' : 'password'}
                      className="h-12 bg-white"
                      id="password"
                      aria-required={true}
                      {...field}
                    />
                    <Button
                      type="button"
                      size="icon"
                      aria-label={
                        showPassword ? 'Hide password' : 'Show password'
                      }
                      aria-pressed={showPassword}
                      onClick={togglePasswordVisibility}
                      className="absolute right-3 top-1/2 -translate-y-1/2 bg-transparent text-gray-500 shadow-none"
                    >
                      {showPassword ? (
                        <EyeOpenIcon aria-hidden />
                      ) : (
                        <EyeClosedIcon aria-hidden />
                      )}
                    </Button>
                  </div>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <div className="space-y-4">
            <Button
              type="submit"
              className="h-12 w-full bg-[#1D781D] text-white"
              disabled={loading}
              aria-live="polite"
              aria-label={loading ? 'Processing, please wait' : 'Continue'}
            >
              {loading ? (
                <>
                  <div
                    aria-hidden="true"
                    className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-t-transparent"
                  ></div>
                </>
              ) : (
                'Continue'
              )}
            </Button>

            <p className="text-center text-sm text-[#4D4D4D]">
              Don't have an account?{' '}
              <Link
                to="/signup"
                className="group inline-flex items-end gap-1 font-semibold text-[#1D781D] hover:underline"
              >
                Sign up
                <ArrowTopRightIcon className="group-hover:scale-110" />
              </Link>
            </p>
            <p className="text-center text-sm text-[#4D4D4D]">
              Forgot your password?{' '}
              <Link
                to="/forgot"
                className="group inline-flex items-end gap-1 font-semibold text-[#1D781D] hover:underline"
              >
                Reset Now
                <ArrowTopRightIcon className="group-hover:scale-110" />
              </Link>
            </p>
          </div>
        </form>
      </Form>
    </>
  );
};

export default LoginForm;