add sign in with password and form forgot password

This commit is contained in:
vergiLgood1 2025-04-04 22:00:19 +07:00
parent 08ee186737
commit 5d3665807e
23 changed files with 704 additions and 153 deletions

View File

@ -30,7 +30,7 @@ import { ImageIcon, Loader2 } from "lucide-react";
import { createClient } from "@/app/_utils/supabase/client";
import { getFullName, getInitials } from "@/app/_utils/common";
import { useProfileFormHandlers } from "../dashboard/user-management/_handlers/use-profile-form";
import { CTexts } from "@/app/_lib/const/string";
import { CTexts } from "@/app/_lib/const/texts";
// Profile update form schema
const profileFormSchema = z.object({

View File

@ -32,7 +32,7 @@ import {
updateUser,
} from "@/app/(pages)/(admin)/dashboard/user-management/action";
import { useProfileFormHandlers } from "../../dashboard/user-management/_handlers/use-profile-form";
import { CTexts } from "@/app/_lib/const/string";
import { CTexts } from "@/app/_lib/const/texts";
const profileFormSchema = z.object({
username: z.string().nullable().optional(),

View File

@ -11,8 +11,8 @@ import { z } from "zod"
import { useUnbanUserMutation, useUpdateUserMutation, useUploadAvatarMutation } from "../_queries/mutations"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { CNumbers } from "@/app/_lib/const/number"
import { CTexts } from "@/app/_lib/const/string"
import { CNumbers } from "@/app/_lib/const/numbers"
import { CTexts } from "@/app/_lib/const/texts"
import { useUserActionsHandler } from "./actions/use-user-actions"
// Profile update form schema

View File

@ -3,29 +3,59 @@
import type { IUserSchema } from "@/src/entities/models/users/users.model"
import { useSendMagicLinkMutation, useSendPasswordRecoveryMutation } from "@/app/(pages)/(auth)/_queries/mutations"
import { toast } from "sonner"
import { useForm } from "react-hook-form"
import { ISendPasswordRecoverySchema, SendPasswordRecoverySchema } from "@/src/entities/models/auth/send-password-recovery.model"
import { zodResolver } from "@hookform/resolvers/zod"
export const useSendPasswordRecoveryHandler = (user: IUserSchema, onOpenChange: (open: boolean) => void) => {
const { mutateAsync: sendPasswordRecovery, isPending } =
export const useSendPasswordRecoveryHandler = () => {
const { mutateAsync: sendPasswordRecovery, isPending, error } =
useSendPasswordRecoveryMutation()
const handleSendPasswordRecovery = async () => {
if (user.email) {
await sendPasswordRecovery(user.email, {
onSuccess: () => {
toast.success(`Password recovery email sent to ${user.email}`)
onOpenChange(false)
const {
register,
handleSubmit: handleFormSubmit,
reset,
formState: { errors: formErrors },
setError: setFormError,
} = useForm<ISendPasswordRecoverySchema>({
defaultValues: {
email: "",
},
resolver: zodResolver(SendPasswordRecoverySchema),
})
const onSubmit = handleFormSubmit(async (data) => {
if (isPending) return
const email = data.email;
try {
toast.promise(sendPasswordRecovery(email), {
loading: "Sending password recovery...",
success: () => {
reset()
return "An email has been sent to you. Please check your inbox."
},
onError: (error) => {
toast.error(error.message)
onOpenChange(false)
error: (err) => {
const errorMessage = err?.message || "Failed to send email."
setFormError("email", { message: errorMessage })
return errorMessage
},
})
} catch (err: any) {
setFormError("email", { message: err?.message || "An error occurred while sending the email." })
}
}
})
return {
handleSendPasswordRecovery,
register,
handleSubmit: onSubmit,
reset,
formErrors,
isPending,
error: !!error,
errors: !!error || formErrors.email,
sendPasswordRecovery,
}
}

View File

@ -0,0 +1,84 @@
import { useNavigations } from "@/app/_hooks/use-navigations";
import { useSignInPasswordlessMutation } from "../_queries/mutations";
import { toast } from "sonner";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { ISignInPasswordlessSchema, SignInPasswordlessSchema } from "@/src/entities/models/auth/sign-in.model";
import { zodResolver } from "@hookform/resolvers/zod";
import { createRoute } from "@/app/_utils/common";
import { ROUTES } from "@/app/_lib/const/routes";
export function useSignInPasswordlessHandler() {
const { mutateAsync: signIn, isPending, error: queryError } = useSignInPasswordlessMutation();
const { router } = useNavigations();
// For server/API errors
const [error, setError] = useState<string>();
const {
register,
handleSubmit: handleFormSubmit,
reset,
formState: { errors: formErrors },
setError: setFormError,
} = useForm<ISignInPasswordlessSchema>({
defaultValues: {
email: "",
},
resolver: zodResolver(SignInPasswordlessSchema),
mode: "onSubmit" // Validate on form submission
});
const onSubmit = handleFormSubmit(async (data) => {
if (isPending) return;
setError(undefined);
const formData = new FormData();
formData.append('email', data.email);
try {
await toast.promise(
signIn(formData),
{
loading: 'Sending magic link...',
success: () => {
// If we reach here, the operation was successful
router.push(createRoute(ROUTES.AUTH.VERIFY_OTP, { email: data.email }));
return 'An email has been sent to you. Please check your inbox.';
},
error: (err) => {
const errorMessage = err?.message || 'Failed to send email.';
setError(errorMessage);
return errorMessage;
}
}
);
} catch (err: any) {
// Error is already handled in the toast.promise error callback
setError(err?.message || 'An error occurred while sending the email.');
}
});
// Extract the validation error message for the email field
const getFieldErrorMessage = (fieldName: keyof ISignInPasswordlessSchema) => {
return formErrors[fieldName]?.message || '';
};
// Wrapper to handle the form submission properly
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit(e);
};
return {
reset,
register,
handleSignIn: handleSubmit,
error: getFieldErrorMessage('email') || error, // Prioritize form validation errors
isPending,
errors: !!error || !!queryError || Object.keys(formErrors).length > 0,
formErrors,
getFieldErrorMessage
};
}

View File

@ -0,0 +1,86 @@
import { useNavigations } from "@/app/_hooks/use-navigations";
import { useSignInWithPasswordMutation } from "../_queries/mutations";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { ISignInWithPasswordSchema, SignInWithPasswordSchema } from "@/src/entities/models/auth/sign-in.model";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "sonner";
import { createRoute } from "@/app/_utils/common";
import { ROUTES } from "@/app/_lib/const/routes";
export const useSignInWithPasswordHandler = () => {
const { mutateAsync: signInWithPassword, isPending, error: queryError } = useSignInWithPasswordMutation();
const { router } = useNavigations();
const [error, setError] = useState<string>();
const {
register,
handleSubmit: handleFormSubmit,
reset,
formState: { errors: formErrors },
setError: setFormError,
} = useForm<ISignInWithPasswordSchema>({
defaultValues: {
email: "",
password: ""
},
resolver: zodResolver(SignInWithPasswordSchema),
mode: "onSubmit" // Validate on form submission
});
const onSubmit = handleFormSubmit(async (data) => {
if (isPending) return;
setError(undefined);
const formData = new FormData();
formData.append('email', data.email);
try {
toast.promise(
signInWithPassword(formData),
{
loading: 'Sending magic link...',
success: () => {
// If we reach here, the operation was successful
router.push(createRoute(ROUTES.APP.DASHBOARD));
return 'An email has been sent to you. Please check your inbox.';
},
error: (err) => {
const errorMessage = err?.message || 'Failed to send email.';
setError(errorMessage);
return errorMessage;
}
}
);
} catch (err: any) {
// Error is already handled in the toast.promise error callback
setError(err?.message || 'An error occurred while sending the email.');
}
});
// Extract the validation error message for the email field
const getFieldErrorMessage = (fieldName: keyof ISignInWithPasswordSchema) => {
return formErrors[fieldName]?.message || '';
};
// Wrapper to handle the form submission properly
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit(e);
};
return {
reset,
register,
handleSignIn: handleSubmit,
isPending,
error: getFieldErrorMessage('email') || error, // Prioritize form validation errors
queryError,
errors: !!error || !!queryError || Object.keys(formErrors).length > 0,
formErrors,
getFieldErrorMessage
};
}

View File

@ -1,80 +0,0 @@
import { useNavigations } from "@/app/_hooks/use-navigations";
import { useSignInPasswordlessMutation } from "../_queries/mutations";
import { toast } from "sonner";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { ISignInPasswordlessSchema, SignInPasswordlessSchema } from "@/src/entities/models/auth/sign-in.model";
import { zodResolver } from "@hookform/resolvers/zod";
export function useSignInHandler() {
const { mutateAsync: signIn, isPending, error: errors } = useSignInPasswordlessMutation();
const { router } = useNavigations();
const [error, setError] = useState<string>();
const {
register,
reset,
formState: { errors: formErrors },
setError: setFormError,
} = useForm<ISignInPasswordlessSchema>({
defaultValues: {
email: "",
},
resolver: zodResolver(SignInPasswordlessSchema),
})
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (isPending) return;
setError(undefined);
const formData = new FormData(event.currentTarget);
const email = formData.get('email')?.toString();
const res = await signIn(formData);
if (!res?.error) {
toast('An email has been sent to you. Please check your inbox.');
if (email) router.push(`/verify-otp?email=${encodeURIComponent(email)}`);
} else {
setError(res.error);
}
};
// const onSubmit = handleSubmit(async (data) => {
// if (isPending) return;
// console.log(data);
// setError(undefined);
// const { email } = data;
// const formData = new FormData();
// formData.append('email', email);
// const res = await signIn(formData);
// if (!res?.error) {
// toast('An email has been sent to you. Please check your inbox.');
// router.push(`/verify-otp?email=${encodeURIComponent(email)}`);
// } else {
// setError(res.error);
// }
// })
return {
// formData,
// handleChange,
reset,
register,
handleSignIn: handleSubmit,
error,
isPending,
errors: !!error || errors,
};
}

View File

@ -0,0 +1,90 @@
"use client";
import { useSearchParams } from "next/navigation";
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@/app/_components/ui/input-otp";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/app/_components/ui/card";
import { cn } from "@/app/_lib/utils";
import { Loader2 } from "lucide-react";
import { Controller } from "react-hook-form";
import { Button } from "@/app/_components/ui/button";
import { useVerifyOtpHandler } from "../../_handlers/use-verify-otp";
import { useSendPasswordRecoveryHandler } from "../../_handlers/use-send-password-recovery";
import { FormField } from "@/app/_components/form-field";
import { Input } from "@/app/_components/ui/input";
import { Separator } from "@/app/_components/ui/separator";
interface ForgotPasswordFormProps extends React.HTMLAttributes<HTMLDivElement> { }
export function ForgotPasswordForm({ className, ...props }: ForgotPasswordFormProps) {
const {
register,
handleSubmit,
error,
errors,
formErrors,
isPending
} = useSendPasswordRecoveryHandler()
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card className="bg-[#171717] border-gray-800 text-white border-none max-w-md space-y-4">
<CardHeader className="text-start">
<CardTitle className="text-2xl font-bold">Reset Your Password</CardTitle>
<CardDescription className="text-gray-400">
Type in your email and we'll send you a link to reset your password
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<FormField
label="Email"
input={
<Input
{...register("email")}
placeholder="you@example.com"
className={`bg-[#1C1C1C] border-gray-800`}
error={!!errors}
disabled={isPending}
/>
}
error={formErrors.email?.message}
/>
<Separator className="" />
<div className="flex justify-center">
<Button
type="submit"
className="w-full bg-emerald-600 hover:bg-emerald-700 text-white"
disabled={isPending}
>
{isPending ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Sending email...
</>
) : (
"Send Reset Email"
)}
</Button>
</div>
</form>
</CardContent>
</Card>
<div className="text-balance text-center text-xs text-gray-400 [&_a]:text-emerald-500 [&_a]:underline [&_a]:underline-offset-4 [&_a]:hover:text-emerald-400">
By clicking continue, you agree to Sigap's{" "}
<a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>.
</div>
</div>
)
}

View File

@ -0,0 +1,25 @@
import { VerifyOtpForm } from "@/app/(pages)/(auth)/verify-otp/_components/verify-otp-form";
import { GalleryVerticalEnd } from "lucide-react";
import { ForgotPasswordForm } from "./_components/forgot-password-form";
export default async function ForgotPasswordPage() {
return (
<div className="grid min-h-svh">
<div className="flex flex-col gap-4 p-6 md:p-10 relative">
<div className="flex justify-between items-center">
<a href="#" className="flex items-center gap-2 font-medium">
<div className="flex h-6 w-6 items-center justify-center rounded-md bg-primary text-primary-foreground">
<GalleryVerticalEnd className="size-4" />
</div>
Sigap Tech.
</a>
</div>
<div className="flex flex-1 items-center justify-center">
<div className="w-full max-w-lg">
<ForgotPasswordForm />
</div>
</div>
</div>
</div>
);
}

View File

@ -15,10 +15,10 @@
// *
// * @returns {Object} Object berisi handler dan state untuk form sign in
// * @example
// * const { handleSubmit, isPending, error } = useSignInHandler();
// * const { handleSubmit, isPending, error } = useSignInPasswordlessHandler();
// * <form onSubmit={handleSubmit}>...</form>
// */
// export function useSignInHandler() {
// export function useSignInPasswordlessHandler() {
// const { signIn } = useAuthActions();
// const { router } = useNavigations();

View File

@ -0,0 +1,194 @@
"use client";
import React, { useState } from "react";
import { Loader2, Lock, Eye, EyeOff } from "lucide-react";
import { Button } from "@/app/_components/ui/button";
import { Input } from "@/app/_components/ui/input";
import Link from "next/link";
import { FormField } from "@/app/_components/form-field";
import { useSignInPasswordlessHandler } from "../../_handlers/use-sign-in-passwordless";
import { useSignInWithPasswordHandler } from "../../_handlers/use-sign-in-with-password";
import { useNavigations } from "@/app/_hooks/use-navigations";
import { createRoute } from "@/app/_utils/common";
import { ROUTES } from "@/app/_lib/const/routes";
export function SignInWithPasswordForm({
className,
...props
}: React.ComponentPropsWithoutRef<"form">) {
const { router } = useNavigations();
// State for password visibility toggle
const [showPassword, setShowPassword] = useState(false);
const [isSignInWithPassword, setIsSignInWithPassword] = useState(false);
// State to track if the password field has a value
const [hasPasswordValue, setHasPasswordValue] = useState(false);
// Get handlers for both authentication methods
const passwordHandler = useSignInWithPasswordHandler();
const passwordlessHandler = useSignInPasswordlessHandler();
// Choose the appropriate handler based on whether password is provided
const {
register,
isPending,
handleSignIn,
error,
errors,
formErrors,
getFieldErrorMessage
} = isSignInWithPassword ? passwordHandler : passwordlessHandler;
// Handle password input changes to determine which auth method to use
const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setHasPasswordValue(!!e.target.value);
};
// Toggle password visibility
const togglePasswordVisibility = () => {
setShowPassword(!showPassword);
};
// Toggle password form field
const togglePasswordField = () => {
setIsSignInWithPassword(!isSignInWithPassword);
};
const handleForgotPassword = () => {
router.push(createRoute(ROUTES.AUTH.FORGOT_PASSWORD))
}
return (
<div>
<div className="flex-1 flex items-center justify-center px-6">
<div className="w-full max-w-xl space-y-8">
<div className="flex flex-col gap-1">
<h1 className="text-3xl font-bold tracking-tight text-white">
Welcome back
</h1>
<p className="text-sm text-gray-400">
{isSignInWithPassword
? "Sign in with your password"
: "Sign in with a one-time password sent to your email"}
</p>
</div>
<div className="space-y-4">
<Button
variant="outline"
className="w-full bg-[#1C1C1C] text-white border-gray-800 hover:bg-[#2C2C2C] hover:border-gray-700"
size="lg"
disabled={isPending}
>
<Lock className="mr-2 h-5 w-5" />
Continue with SSO
</Button>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t border-gray-800" />
</div>
<div className="relative flex justify-center text-xs">
<span className="bg-background px-2 text-gray-400">or</span>
</div>
</div>
</div>
<form onSubmit={handleSignIn} className="space-y-4" {...props} noValidate>
<div className="relative">
<FormField
label="Email"
link={true}
linkText={isSignInWithPassword ? "Use passwordless sign-in" : "Use password sign-in"}
onClick={togglePasswordField}
input={
<Input
{...(isSignInWithPassword
? passwordHandler.register("email")
: passwordlessHandler.register("email"))}
placeholder="you@example.com"
className={`bg-[#1C1C1C] border-gray-800`}
error={!!formErrors.email}
disabled={isPending}
/>
}
error={getFieldErrorMessage('email') || error}
/>
</div>
{isSignInWithPassword && (
<FormField
label="Password"
linkText="Forgot password?"
link={true}
onClick={handleForgotPassword}
input={
<div className="relative">
<Input
{...passwordHandler.register("password")}
type={showPassword ? "text" : "password"}
placeholder="Password"
className={`bg-[#1C1C1C] border-gray-800 pr-10`}
error={isSignInWithPassword && !!passwordHandler.formErrors.password}
disabled={isPending}
onChange={handlePasswordChange}
/>
<button
type="button"
onClick={togglePasswordVisibility}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
}
error={passwordHandler.getFieldErrorMessage('password') || error}
/>
)}
<Button
className="w-full bg-emerald-600 hover:bg-emerald-700 text-white"
size="lg"
disabled={isPending}
>
{isPending ? (
<>
<Loader2 className="h-5 w-5 animate-spin mr-2" />
{isSignInWithPassword ? "Signing in..." : "Sending login link..."}
</>
) : (
"Sign in"
)}
</Button>
</form>
<div className="text-center text-lg">
<span className="text-gray-400">Don't have an account? </span>
<Link
href="/contact-us"
className="text-white hover:text-emerald-500"
>
Contact Us
</Link>
</div>
<p className="text-center text-xs text-gray-400">
By continuing, you agree to Sigap's{" "}
<a href="#" className="text-gray-400 hover:text-white">
Terms of Service
</a>{" "}
and{" "}
<a href="#" className="text-gray-400 hover:text-white">
Privacy Policy
</a>
, and to receive periodic emails with updates.
</p>
</div>
</div>
</div>
);
}

View File

@ -4,36 +4,24 @@ import type React from "react";
import { Loader2, Lock } from "lucide-react";
import { Button } from "@/app/_components/ui/button";
import { Input } from "@/app/_components/ui/input";
import { SubmitButton } from "@/app/_components/submit-button";
import Link from "next/link";
import { FormField } from "@/app/_components/form-field";
// import { useSignInController } from "@/src/interface-adapters/controllers/auth/sign-in.controller";
import { useState } from "react";
import { useSignInPasswordlessHandler } from "../../_handlers/use-sign-in-passwordless";
import { useSignInHandler } from "../_handlers/use-sign-in";
export function SignInForm({
className,
...props
}: React.ComponentPropsWithoutRef<"form">) {
// const [error, setError] = useState<string>();
// const [loading, setLoading] = useState(false);
// const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
// event.preventDefault();
// if (loading) return;
// const formData = new FormData(event.currentTarget);
// setLoading(true);
// const res = await signIn(formData);
// if (res && res.error) {
// setError(res.error);
// }
// setLoading(false);
// };
const { register, isPending, handleSignIn, error, errors } = useSignInHandler();
const {
register,
isPending,
handleSignIn,
error,
errors,
formErrors,
getFieldErrorMessage
} = useSignInPasswordlessHandler();
return (
<div>
@ -46,15 +34,6 @@ export function SignInForm({
<p className="text-sm text-gray-400">Sign in to your account</p>
</div>
{/* {message && (
<div
className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative"
role="alert"
>
<span className="block sm:inline">{message}</span>
</div>
)} */}
<div className="space-y-4">
<Button
variant="outline"
@ -84,11 +63,11 @@ export function SignInForm({
{...register("email")}
placeholder="you@example.com"
className={`bg-[#1C1C1C] border-gray-800`}
error={!!errors}
error={!!formErrors.email}
disabled={isPending}
/>
}
error={error}
error={getFieldErrorMessage('email') || error}
/>
<Button
className="w-full bg-emerald-600 hover:bg-emerald-700 text-white"

View File

@ -1,10 +1,11 @@
import { SignInForm } from "@/app/(pages)/(auth)/_components/signin-form";
import { SignInForm } from "@/app/(pages)/(auth)/sign-in/_components/signin-form";
import { Message } from "@/app/_components/form-message";
import { Button } from "@/app/_components/ui/button";
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/app/_components/ui/carousal";
import { IconQuoteFilled } from "@tabler/icons-react";
import { GalleryVerticalEnd, Globe, QuoteIcon } from "lucide-react";
import { CarousalQuotes } from "./_components/carousal-quote";
import { SignInWithPasswordForm } from "./_components/sign-in-with-password-form";
export default async function Login(props: { searchParams: Promise<Message> }) {
return (
@ -20,7 +21,7 @@ export default async function Login(props: { searchParams: Promise<Message> }) {
</div>
<div className="flex flex-1 items-center justify-center">
<div className="w-full max-w-md">
<SignInForm />
<SignInWithPasswordForm />
</div>
</div>
</div>

View File

@ -17,7 +17,7 @@ import { cn } from "@/app/_lib/utils";
import { Loader2 } from "lucide-react";
import { Controller } from "react-hook-form";
import { Button } from "@/app/_components/ui/button";
import { useVerifyOtpHandler } from "../_handlers/use-verify-otp";
import { useVerifyOtpHandler } from "../../_handlers/use-verify-otp";
interface VerifyOtpFormProps extends React.HTMLAttributes<HTMLDivElement> {}

View File

@ -1,4 +1,4 @@
import { VerifyOtpForm } from "@/app/(pages)/(auth)/_components/verify-otp-form";
import { VerifyOtpForm } from "@/app/(pages)/(auth)/verify-otp/_components/verify-otp-form";
import { GalleryVerticalEnd } from "lucide-react";
export default async function VerifyOtpPage() {

View File

@ -1,17 +1,107 @@
import { Label } from "./ui/label";
"use client"
interface FormFieldProps {
label: string;
input: React.ReactNode;
error?: string;
import React, { type ComponentPropsWithoutRef, ReactElement, type ReactNode, isValidElement } from "react"
import { Info } from "lucide-react"
import { Label } from "./ui/label"
import { Button } from "./ui/button"
import { cn } from "../_lib/utils"
interface FormFieldProps extends ComponentPropsWithoutRef<"div"> {
label: string
link?: boolean
linkText?: string
onClick?: () => void
input: ReactElement<any>
error?: string
description?: string
required?: boolean
size?: "sm" | "md" | "lg"
labelClassName?: string
inputWrapperClassName?: string
hideLabel?: boolean
id?: string
}
export function FormField({ label, input, error }: FormFieldProps) {
export function FormField({
label,
link,
linkText,
onClick,
input,
error,
description,
required = false,
size = "md",
labelClassName,
inputWrapperClassName,
hideLabel = false,
id,
className,
...props
}: FormFieldProps) {
// Generate an ID for connecting label with input if not provided
const fieldId = id || label.toLowerCase().replace(/\s+/g, "-")
// Size-based spacing
const sizeClasses = {
sm: "space-y-1",
md: "space-y-2",
lg: "space-y-3",
}
// Safely clone the input element if it's a valid React element
const inputElement = isValidElement(input)
? React.cloneElement(input as ReactElement<any>, {
id: fieldId,
"aria-invalid": error ? "true" : "false",
"aria-describedby": error ? `${fieldId}-error` : description ? `${fieldId}-description` : undefined,
})
: input
return (
<div className="space-y-2">
<Label className="text-sm text-gray-300">{label}</Label>
{input}
{error && <p className="text-destructive text-xs mt-1">{error}</p>}
<div className={cn("w-full", sizeClasses[size], className)} {...props}>
<div className="flex items-center justify-between">
{!hideLabel && (
<Label
htmlFor={fieldId}
className={cn(
"text-sm font-medium text-gray-300",
required && "after:content-['*'] after:ml-0.5 after:text-destructive",
labelClassName,
)}
>
{label}
</Label>
)}
{link && (
<Button
size="sm"
variant="link"
className="text-xs text-gray-400 hover:text-gray-200 p-0 h-auto"
onClick={onClick}
type="button"
>
{linkText}
</Button>
)}
</div>
<div className={cn("relative", inputWrapperClassName)}>{inputElement}</div>
{description && !error && (
<p id={`${fieldId}-description`} className="text-xs text-gray-400 mt-1">
{description}
</p>
)}
{error && (
<div id={`${fieldId}-error`} className="flex items-start gap-1.5 text-destructive text-xs mt-1" role="alert">
<Info className="h-3 w-3 mt-0.5 flex-shrink-0" />
<span>{error}</span>
</div>
)}
</div>
);
)
}

View File

@ -0,0 +1,34 @@
// src/constants/routes.ts
/**
* Application route constants for better maintainability
* Use these constants instead of hard-coded strings throughout the app
*/
export const ROUTES = {
// Auth routes
AUTH: {
SIGN_IN_PASSWORDLESS: '/sign-in',
SIGN_IN_WITH_PASSWORD: '/sign-in-password',
SIGN_UP: '/sign-up',
VERIFY_OTP: '/verify-otp',
RESET_PASSWORD: '/reset-password',
FORGOT_PASSWORD: '/forgot-password',
},
// Main application routes
APP: {
DASHBOARD: '/dashboard',
PROFILE: '/profile',
SETTINGS: '/settings',
USER_MANAGEMENT: '/dashboard/user-management',
},
// Public routes
PUBLIC: {
HOME: '/',
CONTACT: '/contact-us',
ABOUT: '/about',
TERMS: '/terms',
PRIVACY: '/privacy',
}
};

View File

@ -330,3 +330,21 @@ export function calculateUserStats(users: IUserSchema[] | undefined) {
totalUsers > 0 ? ((inactiveUsers / totalUsers) * 100).toFixed(1) : '0.0',
};
}
/**
* Generate route with query parameters
* @param baseRoute - The base route path
* @param params - Object containing query parameters
* @returns Formatted route with query parameters
*/
export const createRoute = (baseRoute: string, params?: Record<string, string>): string => {
if (!params || Object.keys(params).length === 0) {
return baseRoute;
}
const queryString = Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
return `${baseRoute}?${queryString}`;
};

View File

@ -1,4 +1,4 @@
import { CTexts } from "../_lib/const/string";
import { CTexts } from "../_lib/const/texts";
import { CRegex } from "../_lib/const/regex";
/**

View File

@ -1,5 +1,5 @@
import { CNumbers } from "@/app/_lib/const/number";
import { CTexts } from "@/app/_lib/const/string";
import { CNumbers } from "@/app/_lib/const/numbers";
import { CTexts } from "@/app/_lib/const/texts";
import { phonePrefixValidation, phoneRegexValidation } from "@/app/_utils/validation";
import { z } from "zod";

View File

@ -1,5 +1,5 @@
import { CNumbers } from "@/app/_lib/const/number";
import { CTexts } from "@/app/_lib/const/string";
import { CNumbers } from "@/app/_lib/const/numbers";
import { CTexts } from "@/app/_lib/const/texts";
import { IInstrumentationService } from "@/src/application/services/instrumentation.service.interface";
import { IUploadAvatarUseCase } from "@/src/application/use-cases/users/upload-avatar.use-case";
import { z } from "zod";