-
Notifications
You must be signed in to change notification settings - Fork 1
/
LoginForm.tsx
416 lines (403 loc) · 14.3 KB
/
LoginForm.tsx
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import React from "react";
import { FC, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { cn } from "@util/index";
import { parsePhoneNumber } from "libphonenumber-js";
import * as z from "zod";
import { Alert } from "@elements/alert";
import { Button } from "@elements/button";
import { Card, CardContent, CardFooter } from "@elements/card";
import { Input } from "@elements/input";
import { PhoneInput } from "@elements/phoneInput";
import {
DirectionType,
LoginFormTextsTypes,
ThirdPartyAuthTextsTypes,
} from "@_types/index";
import { EyeIcon, HiddenEyeIcon } from "../../icons";
import { AuthButtons } from "./AuthButtons";
type LoginFormTypes = {
/** Object containing text labels used throughout the form. */
texts?: LoginFormTextsTypes;
/** If true, only logos are displayed in third-party auth buttons. */
logosOnly?: boolean;
/** Direction of text and UI elements, either left-to-right or right-to-left. */
direction?: DirectionType;
/** If true, an error alert is displayed at the top of the form. */
showError?: boolean;
/** Title text of error alert. */
errorTitle?: string;
/** Description text of error alert. */
errorText?: string;
/** Login identifier type user will use to log in. */
loginType?: "email" | "username" | "phone" | "link";
/** If true, the reset password option is hidden. */
withResetPassword?: boolean;
/** If true, the register option is hidden. */
allowRegister?: boolean;
/** If true, a loading spinner is displayed within the main form submit button. */
isLoading?: boolean;
/** If true, a loading spinner is displayed within the Google login button. */
isGoogleLoading?: boolean;
/** If true, a loading spinner is displayed within the Twitter login button. */
isTwitterLoading?: boolean;
/** If true, a loading spinner is displayed within the Github login button. */
isGithubLoading?: boolean;
/** If true, Google login option is displayed. */
viaGoogle?: boolean;
/** If true, Github login option is displayed. */
viaGithub?: boolean;
/** If true, Twitter login option is displayed. */
viaTwitter?: boolean;
/** Function to handle form submission. */
onLogin: (e: any) => void;
/** Function to route user to the register page. */
onRouteToRegister?: () => void;
/** Function to handle forgotten password case. */
onForgotPassword?: () => void;
/** Function to handle Google login. */
onGoogleLogin?: () => void;
/** Function to handle Github login. */
onGithubLogin?: () => void;
/** Function to handle Twitter login. */
onTwitterLogin?: () => void;
/** Additional buttons to add under the login button */
additionalButtons?: any;
/** The allowed length of the password input field */
passwordLength?: number;
/** If true, the form is displayed without a card container styling.*/
cardless?: boolean;
};
export const LoginForm: FC<LoginFormTypes> = ({
loginType = "email",
passwordLength = 8,
texts,
...props
}) => {
const [passwordVisible, setPasswordVisible] = useState(false);
const thirdPartyAuthTexts: ThirdPartyAuthTextsTypes = {
continueWithGoogle: texts?.continueWithGoogle,
continueWithTwitter: texts?.continueWithTwitter,
continueWithApple: texts?.continueWithApple,
continueWithMicrosoft: texts?.continueWithMicrosoft,
continueWithGithub: texts?.continueWithGithub,
continueWithEmail: texts?.continueWithEmail,
continueWithPhone: texts?.continueWithPhone,
};
let formSchema;
if (loginType === "email") {
formSchema = z.object({
email: z
.string({ required_error: texts?.email?.required || "Email Required" })
.min(1, { message: texts?.email?.required || "Email Required" })
.email({ message: texts?.email?.invalid || "Email Invalid" }),
password: z
.string({
required_error: texts?.password?.required || "Password Required",
})
.min(1, { message: texts?.password?.required || "Password Required" })
.min(passwordLength, {
message: texts?.password?.tooShort || "Password too short",
}),
});
} else if (loginType === "username") {
formSchema = z.object({
username: z
.string({
required_error: texts?.username?.required || "Username Required",
})
.min(2, { message: texts?.username?.tooShort || "Username too short" })
.refine(
(value) => {
const isValid = /^[a-zA-Z][a-zA-Z0-9_-]{2,14}$/.test(value);
return isValid;
},
{ message: texts?.username?.invalid || "Username Invalid" },
),
password: z
.string({
required_error: texts?.password?.required || "Password Required",
})
.min(1, { message: texts?.password?.required || "Password Required" })
.min(passwordLength, {
message: texts?.password?.tooShort || "Password too short",
}),
});
} else if (loginType === "phone") {
formSchema = z.object({
phone: z
.string({
required_error: texts?.phone?.required || "Phone Number Required",
})
.refine(
(value) => {
let phoneNumber = parsePhoneNumber(value);
return phoneNumber.isValid();
},
{ message: texts?.phone?.invalid || "Phone Number Invalid" },
),
});
} else if (loginType === "link") {
formSchema = z.object({
email: z
.string({ required_error: texts?.email?.required || "Email Required" })
.min(1, { message: texts?.email?.required || "Email Required" })
.email({ message: texts?.email?.invalid || "Email Invalid" }),
});
} else {
formSchema = z.object({});
}
const { handleSubmit, control, formState } = useForm({
resolver: zodResolver(formSchema),
});
const renderFields = () => {
switch (loginType) {
case "email":
return (
<>
<Controller
control={control}
name="email"
render={({ field }) => (
<Input
inputProps={{
className:
props.direction === "rtl"
? "hawa-text-right"
: "hawa-text-left",
}}
dir={"ltr"}
width="full"
autoComplete="email"
label={texts?.email?.label || "Email"}
helperText={formState.errors.email?.message}
placeholder={texts?.email?.placeholder || "[email protected]"}
{...field}
/>
)}
/>
<div>
<Controller
control={control}
name="password"
render={({ field }) => (
<Input
width="full"
autoComplete="current-password"
type={passwordVisible ? "text" : "password"}
label={texts?.password?.label || "Password"}
endIcon={
<div
className="hawa-cursor-pointer"
onClick={() => setPasswordVisible(!passwordVisible)}
>
{passwordVisible ? (
<EyeIcon className="hawa-text-gray-500" />
) : (
<HiddenEyeIcon className="hawa-text-gray-500" />
)}
</div>
}
placeholder={
texts?.password?.placeholder || "Enter your password"
}
helperText={formState.errors.password?.message}
{...field}
/>
)}
/>
{props.withResetPassword && (
<div
onClick={props.onForgotPassword}
className="hawa-mb-3 hawa-mt-2 hawa-w-fit hawa-cursor-pointer hawa-select-none hawa-text-xs dark:hawa-text-gray-300"
>
{texts?.forgotPassword || "Forgot Password?"}
</div>
)}
</div>
</>
);
case "username":
return (
<>
<Controller
control={control}
name="username"
render={({ field }) => {
return (
<Input
width="full"
autoComplete="username"
label={texts?.username?.label || "Username"}
helperText={formState.errors.username?.message}
placeholder={texts?.username?.placeholder || "sikka_sa"}
{...field}
/>
);
}}
/>
<div>
<Controller
control={control}
name="password"
render={({ field }) => (
<Input
width="full"
autoComplete="current-password"
type={passwordVisible ? "text" : "password"}
label={texts?.password?.label || "Password"}
endIcon={
<div
className="hawa-cursor-pointer"
onClick={() => setPasswordVisible(!passwordVisible)}
>
{passwordVisible ? (
<EyeIcon className="hawa-text-gray-500" />
) : (
<HiddenEyeIcon className="hawa-text-gray-500" />
)}
</div>
}
placeholder={
texts?.password?.placeholder || "Enter your password"
}
helperText={formState.errors.password?.message}
{...field}
/>
)}
/>
{props.withResetPassword && (
<div
onClick={props.onForgotPassword}
className="hawa-mb-3 hawa-mt-2 hawa-w-fit hawa-cursor-pointer hawa-select-none hawa-text-xs dark:hawa-text-gray-300"
>
{texts?.forgotPassword || "Forgot Password?"}
</div>
)}
</div>
</>
);
case "phone":
return (
<>
<Controller
control={control}
name="phone"
render={({ field }) => (
<PhoneInput
label={texts?.phone?.label || "Phone Number"}
helperText={formState.errors.phone?.message}
preferredCountry={{ label: "+966" }}
handleChange={(e) =>
field.onChange(parsePhoneNumber(e).number)
}
/>
)}
/>
</>
);
case "link":
return (
<>
<Controller
control={control}
name="email"
render={({ field }) => (
<Input
width="full"
autoComplete="email"
label={texts?.email?.label || "Email"}
helperText={formState.errors.email?.message}
placeholder={texts?.email?.placeholder || "[email protected]"}
{...field}
/>
)}
/>
</>
);
default:
break;
}
};
return (
<div className="hawa-flex hawa-flex-col hawa-gap-4">
<Card
dir={props.direction}
className={cn(
props.cardless &&
"!hawa-border-none !hawa-bg-transparent !hawa-shadow-none !hawa-drop-shadow-none",
)}
>
<CardContent headless noPadding={props.cardless}>
{props.showError && (
<Alert
direction={props.direction}
title={props.errorTitle}
text={props.errorText}
severity="error"
/>
)}
<form
noValidate
className="hawa-flex hawa-flex-col hawa-gap-4"
onSubmit={handleSubmit((e) => {
if (props.onLogin) {
return props.onLogin(e);
} else {
console.log("Form is submitted but onLogin prop is missing");
}
})}
>
{renderFields()}
<Button
className="hawa-mt-0 hawa-w-full"
type="submit"
isLoading={props.isLoading}
disabled={props.isLoading}
>
{texts?.loginText || "Login"}
</Button>
{props.additionalButtons}
{props.allowRegister && (
<div className="hawa-select-none hawa-p-3 hawa-text-center hawa-text-sm hawa-font-normal dark:hawa-text-gray-300">
{texts?.newUserText || "New user?"}{" "}
<span
onClick={props.onRouteToRegister}
className="clickable-link"
>
{texts?.createAccount || "Create Account"}
</span>
</div>
)}
</form>
</CardContent>
{props.viaGithub || props.viaGoogle || props.viaTwitter ? (
<CardFooter
noPadding={props.cardless}
className={cn(
props.logosOnly
? "hawa-flex hawa-flex-row hawa-justify-center hawa-gap-2"
: "hawa-grid hawa-grid-cols-1 hawa-gap-2",
)}
>
<AuthButtons
texts={thirdPartyAuthTexts}
viaGoogle={props.viaGoogle}
viaGithub={props.viaGithub}
viaTwitter={props.viaTwitter}
isGoogleLoading={props.isGoogleLoading}
isGithubLoading={props.isGithubLoading}
isTwitterLoading={props.isTwitterLoading}
handleGoogle={props.onGoogleLogin}
handleGithub={props.onGithubLogin}
handleTwitter={props.onTwitterLogin}
/>
</CardFooter>
) : null}
</Card>
{/* {props.handleColorMode && props.handleLanguage && (
*/}
</div>
);
};