92 lines
2.3 KiB
TypeScript
92 lines
2.3 KiB
TypeScript
import type { FC } from "react";
|
|
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { Alert, Button, PasswordInput, Stack, TextInput } from "@mantine/core";
|
|
import { useState } from "react";
|
|
import { FormProvider, type Resolver, useForm } from "react-hook-form";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Link } from "react-router";
|
|
|
|
import {
|
|
type AuthFormValues,
|
|
loginSchema,
|
|
registerSchema,
|
|
} from "../../model/auth.schema";
|
|
import classes from "./AuthForm.module.css";
|
|
|
|
type AuthFormProps = {
|
|
onSubmit: (email: string, password: string) => Promise<void>;
|
|
register?: true;
|
|
};
|
|
|
|
const AuthForm: FC<AuthFormProps> = (props) => {
|
|
const { onSubmit, register } = props;
|
|
const { t } = useTranslation();
|
|
const schema = register ? registerSchema : loginSchema;
|
|
|
|
const methods = useForm<AuthFormValues>({
|
|
resolver: zodResolver(schema) as Resolver<AuthFormValues>,
|
|
});
|
|
|
|
const {
|
|
formState: { errors, isSubmitting },
|
|
} = methods;
|
|
|
|
const [submitError, setSubmitError] = useState<null | string>(null);
|
|
|
|
const onSubmit2 = methods.handleSubmit(async (values) => {
|
|
setSubmitError(null);
|
|
|
|
try {
|
|
await onSubmit(values.email, values.password);
|
|
}
|
|
catch {
|
|
setSubmitError(t("auth.requestError"));
|
|
}
|
|
});
|
|
|
|
const to = register ? "/login" : "/register";
|
|
|
|
return (
|
|
<FormProvider {...methods}>
|
|
<form onSubmit={onSubmit2}>
|
|
<fieldset className={classes.fieldset} disabled={isSubmitting}>
|
|
<Stack>
|
|
<TextInput
|
|
label={t("auth.email")}
|
|
{...methods.register("email")}
|
|
error={errors.email?.message as string}
|
|
/>
|
|
|
|
<PasswordInput
|
|
label={t("auth.password")}
|
|
{...methods.register("password")}
|
|
error={errors.password?.message as string}
|
|
/>
|
|
|
|
{register && (
|
|
<PasswordInput
|
|
label={t("auth.passwordConfirmation")}
|
|
{...methods.register("passwordConfirmation")}
|
|
error={errors.passwordConfirmation?.message as string}
|
|
/>
|
|
)}
|
|
|
|
{submitError && <Alert color="red">{submitError}</Alert>}
|
|
|
|
<Button loading={isSubmitting} type="submit">
|
|
{t(register ? "auth.register" : "auth.login")}
|
|
</Button>
|
|
|
|
<Button component={Link} to={to} variant="subtle">
|
|
{t(register ? "auth.haveAccount" : "auth.noAccount")}
|
|
</Button>
|
|
</Stack>
|
|
</fieldset>
|
|
</form>
|
|
</FormProvider>
|
|
);
|
|
};
|
|
|
|
export { AuthForm };
|