improve: overall ux in auth page

This commit is contained in:
Mahyar Khanbolooki
2025-07-14 20:59:01 +03:30
parent b344e7d291
commit 69540a67f2
10 changed files with 165 additions and 119 deletions
+82 -77
View File
@@ -1,6 +1,6 @@
'use client';
import React, { useState, type FormEvent, type ChangeEvent, useEffect } from 'react'
import React, { useState, type FormEvent, type ChangeEvent, useEffect, useTransition } from 'react'
import { useAuthStore } from '@/zustand/authStore';
import { redirect } from 'next/navigation';
import StepEnterPassword from '@/features/auth/components/StepEnterPassword';
@@ -20,7 +20,6 @@ import { useResetPassword } from '@/hooks/auth/useResetPassword';
type Props = object
function AuthIndex({ }: Props) {
const [isPending, setIsPending] = useState(false);
const [number, setNumber] = useState("");
const [password, setPassword] = useState("");
const [passwordRepeat, setPasswordRepeat] = useState("");
@@ -30,12 +29,14 @@ function AuthIndex({ }: Props) {
const [rememberMe, setRememberMe] = useState(false);
const [step, setStep] = useState(AUTH_STEP.ENTER_NUMBER);
const { timerRunning, secondsLeft, restart, stop } = useCountdown(step === AUTH_STEP.ENTER_OTP);
const [isPending, startTransition] = useTransition();
const isAuthenticated = useAuthStore((state) => state.isAuthenticated)
const loginMutation = useLogin()
const signupMutation = useSignup()
const { run: runUserExistCheck } = useCheckUserExistsLazy()
const { run: runOtpRequest } = useOtpRequest();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { run: runOtpValidation } = useOtpValidation();
const { run: runResetPassword } = useResetPassword();
@@ -58,10 +59,13 @@ function AuthIndex({ }: Props) {
useEffect(() => {
if (step === AUTH_STEP.ENTER_OTP) {
setOtp('');
console.log("REQUEST OTP")
runOtpRequest(number);
startTransition(() => {
setOtp('');
console.log("REQUEST OTP")
runOtpRequest(number);
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step]);
const onChange = (e: ChangeEvent<HTMLInputElement>) => {
@@ -106,90 +110,91 @@ function AuthIndex({ }: Props) {
}
else if (target.id === AUTH_PAGE_ELEMENT.RESEND_OTP) {
if (!timerRunning) {
try {
await runOtpRequest(number);
restart();
} catch {
console.error("Could not ask for otp")
}
startTransition(async () => {
try {
await runOtpRequest(number);
restart();
} catch {
console.error("Could not ask for otp")
}
});
}
}
};
const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
setIsPending(true);
if (step == AUTH_STEP.ENTER_NUMBER) {
startTransition(async () => {
try {
if (step == AUTH_STEP.ENTER_NUMBER) {
if (await runUserExistCheck(number)) {
setStep(AUTH_STEP.ENTER_PASSWORD)
} else {
setStep(AUTH_STEP.ENTER_OTP);
if (await runUserExistCheck(number)) {
setStep(AUTH_STEP.ENTER_PASSWORD)
} else {
setStep(AUTH_STEP.ENTER_OTP);
}
}
else if (step == AUTH_STEP.ENTER_PASSWORD) {
try {
await loginMutation.mutateAsync({ phone: number, password })
console.log("Logged in")
redirect("/")
}
catch (e) {
console.error("Wrong credentials: ", e)
}
}
else if (step == AUTH_STEP.ENTER_OTP) {
// if (!await runOtpValidation({ phone: number, otp })) {
// setOtp('');
// console.error('Wrong otp');
// }
stop();
console.log(await runUserExistCheck(number));
if (await runUserExistCheck(number)) {
console.log("1")
setStep(AUTH_STEP.ENTER_RESET_PASSWORD)
} else {
console.log("2")
setStep(AUTH_STEP.ENTER_NEW_PASSWORD)
}
}
else if (step == AUTH_STEP.ENTER_RESET_PASSWORD) {
console.log("Password changed")
try {
await runResetPassword({
phone: number,
newPassword: password,
otp
})
resetStates();
setStep(AUTH_STEP.ENTER_NUMBER)
} catch (ex) {
console.error('Password reset failed: ', ex)
}
}
else if (step == AUTH_STEP.ENTER_NEW_PASSWORD) {
try {
await signupMutation.mutateAsync({ phone: number, password })
console.log("Signed up")
redirect("/")
}
catch (e) {
console.error("Could not signup: ", e)
}
}
} catch (ex) {
console.error(ex)
}
else if (step == AUTH_STEP.ENTER_PASSWORD) {
try {
await loginMutation.mutateAsync({ phone: number, password })
console.log("Logged in")
redirect("/")
}
catch (e) {
console.error("Wrong credentials: ", e)
}
}
else if (step == AUTH_STEP.ENTER_OTP) {
if (!await runOtpValidation({ phone: number, otp })) {
setOtp('');
console.error('Wrong otp');
}
stop();
console.log(await runUserExistCheck(number));
if (await runUserExistCheck(number)) {
console.log("1")
setStep(AUTH_STEP.ENTER_RESET_PASSWORD)
} else {
console.log("2")
setStep(AUTH_STEP.ENTER_NEW_PASSWORD)
}
}
else if (step == AUTH_STEP.ENTER_RESET_PASSWORD) {
console.log("Password changed")
try {
await runResetPassword({
phone: number,
newPassword: password,
otp
})
resetStates();
setStep(AUTH_STEP.ENTER_NUMBER)
} catch (ex) {
console.error('Password reset failed: ', ex)
}
}
else if (step == AUTH_STEP.ENTER_NEW_PASSWORD) {
try {
await signupMutation.mutateAsync({ phone: number, password })
console.log("Signed up")
redirect("/")
}
catch (e) {
console.error("Could not signup: ", e)
}
}
} catch (ex) {
console.error(ex)
} finally {
setIsPending(false);
}
});
}
const stepMap = {
[AUTH_STEP.ENTER_NUMBER]: <StepEnterNumber disabled={isPending} onChange={onChange} value={number} />,
[AUTH_STEP.ENTER_PASSWORD]: <StepEnterPassword disabled={isPending} onChange={onChange} onClick={onClick} value={password} passwordVisible={showPassword} rememberMe={rememberMe} />,
[AUTH_STEP.ENTER_OTP]: <StepEnterOtp disabled={isPending} onChange={onChange} onClick={onClick} phoneNumber={number} value={otp} timerRunning={timerRunning} secondsLeft={secondsLeft} />,
[AUTH_STEP.ENTER_NEW_PASSWORD]: <StepNewPassword disabled={isPending} onChange={onChange} onClick={onClick} value={password} repeatValue={passwordRepeat} passwordVisible={showPassword} repeatPasswordVisible={showPasswordRepeat} />,
[AUTH_STEP.ENTER_RESET_PASSWORD]: <StepNewPassword isReset disabled={isPending} onChange={onChange} onClick={onClick} value={password} repeatValue={passwordRepeat} passwordVisible={showPassword} repeatPasswordVisible={showPasswordRepeat} />,
[AUTH_STEP.ENTER_NUMBER]: <StepEnterNumber pending={isPending} onChange={onChange} value={number} />,
[AUTH_STEP.ENTER_PASSWORD]: <StepEnterPassword pending={isPending} onChange={onChange} onClick={onClick} value={password} passwordVisible={showPassword} rememberMe={rememberMe} />,
[AUTH_STEP.ENTER_OTP]: <StepEnterOtp pending={isPending} onChange={onChange} onClick={onClick} phoneNumber={number} value={otp} timerRunning={timerRunning} secondsLeft={secondsLeft} />,
[AUTH_STEP.ENTER_NEW_PASSWORD]: <StepNewPassword pending={isPending} onChange={onChange} onClick={onClick} value={password} repeatValue={passwordRepeat} passwordVisible={showPassword} repeatPasswordVisible={showPasswordRepeat} />,
[AUTH_STEP.ENTER_RESET_PASSWORD]: <StepNewPassword isReset pending={isPending} onChange={onChange} onClick={onClick} value={password} repeatValue={passwordRepeat} passwordVisible={showPassword} repeatPasswordVisible={showPasswordRepeat} />,
}
return (
+31 -3
View File
@@ -1,11 +1,39 @@
import clsx from 'clsx';
import React from 'react'
import { motion } from 'framer-motion';
import { Refresh } from 'iconsax-react';
type Props = {} & React.ButtonHTMLAttributes<HTMLButtonElement>;
type Props = {
pending?: boolean | undefined
} & React.ButtonHTMLAttributes<HTMLButtonElement>;
function Button({ children, className, disabled, ...rest }: Props) {
function Button({ children, className, disabled, pending, ...rest }: Props) {
return (
<div>
<button disabled={disabled} className={`${className} ${disabled ? 'bg-disabled text-disabled-text' : 'bg-primary text-white'} transition-all duration-200 cursor-pointer w-full rounded-normal p-3 font-normal text-sm`} {...rest}>
<button
disabled={disabled}
className={clsx(
className,
disabled ? 'bg-disabled text-disabled-text' : 'bg-primary text-white hover:bg-[#222222] active:brightness-110',
pending && 'bg-transparent! text-transparent! cursor-auto!',
'relative transition-all duration-200 cursor-pointer w-full rounded-normal p-3 font-normal text-sm overflow-clip'
)}
{...rest}
>
<motion.div
className='absolute left-0 top-0 h-full w-full bg-neutral-200'
initial={{ y: '100%' }}
animate={!pending ? { y: '100%' } : { y: 0 }}
>
<motion.div
animate={pending && { rotateZ: [0, 360] }}
transition={{ duration: 1.2, repeat: Infinity, ease: 'linear' }}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
className='-translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2 absolute'>
<Refresh stroke='#333333' size={24} />
</motion.div>
</motion.div>
{children}
</button>
</div>
+5 -1
View File
@@ -1,5 +1,6 @@
import React from 'react'
import Tooltip from '../utils/Tooltip';
import clsx from 'clsx';
type Props = {
htmlFor: string;
@@ -22,7 +23,10 @@ function InputField({ onChange, htmlFor, labelText, children, valid = true, clas
<Tooltip content={inputProps['aria-errormessage']} hidden={!inputProps['aria-errormessage']}>
<input
onChange={onChange}
className='py-2.5 pt-3.5 text-base w-full outline-0 !leading-6'
className={clsx(
inputProps['aria-errormessage'] && '!text-red-300',
'py-2.5 pt-3.5 text-base w-full outline-0 !leading-6'
)}
name={htmlFor}
{...inputProps} />
{children}
+1 -1
View File
@@ -55,7 +55,7 @@ function OTPInputField({ onChange, maxLength = 6, htmlFor, labelText, className,
htmlFor={htmlFor}>
{labelText}
</label>
<div id={htmlFor} className='inline-flex justify-between items-center gap-2'>
<div id={htmlFor} className='inline-flex justify-between items-center gap-2' dir='ltr'>
{inputRefs?.current?.map((ref, i) => {
return (
<input
+2 -2
View File
@@ -23,7 +23,7 @@ const arrowClasses = {
const Tooltip = ({
children,
title: content,
content,
hidden = false,
position = 'top',
...rest
@@ -34,7 +34,7 @@ const Tooltip = ({
{children}
{!hidden && (
<div
className={`pointer-events-none bg-disabled text-disabled-text absolute z-10 px-3 py-2 text-xs text-muted-foreground bg-muted rounded whitespace-nowrap transition-opacity duration-150 opacity-0 group-hover:opacity-100 ${positionClasses[position]}`}
className={`pointer-events-none absolute z-10 px-3 py-2 text-xs text-muted-foreground bg-muted rounded whitespace-nowrap transition-opacity duration-150 opacity-0 group-hover:opacity-100 ${positionClasses[position]}`}
>
{content}
<div
@@ -1,16 +1,16 @@
import LoadingOverlay from '@/components/overlays/LoadingOverlay';
// import LoadingOverlay from '@/components/overlays/LoadingOverlay';
import React from 'react'
type Props = {
isPending: boolean
} & Omit<React.FormHTMLAttributes<HTMLFormElement>, "id">;
function AuthFormWrapper({ children, isPending, ...restProps }: Props) {
function AuthFormWrapper({ children, ...restProps }: Props) {
return (
<form {...restProps} className='p-6 lg:py-[75px] w-full flex items-center justify-center py-4 lg:items-center lg:px-10 px-4 drop-shadow-black h-full'>
<div className='relative h-full w-full px-4 sm:px-6 lg:p-0 flex flex-col max-h-[812px] max-w-[1200px] bg-container rounded-container overflow-clip lg:flex-row justify-between'>
{children}
<LoadingOverlay visible={isPending} bgOpacity={0} />
{/* <LoadingOverlay visible={isPending} bgOpacity={0} /> */}
</div>
</form>
)
@@ -7,9 +7,10 @@ import React, { useEffect, useState } from 'react'
type Props = {
onChange: React.ChangeEventHandler<HTMLInputElement>;
value: string;
pending?: boolean | undefined
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'id'>
function StepEnterNumber({ onChange, disabled = false, value }: Props) {
function StepEnterNumber({ onChange, pending, disabled, value }: Props) {
const [error, setError] = useState('');
const hasError = (e = error) => {
@@ -35,7 +36,8 @@ function StepEnterNumber({ onChange, disabled = false, value }: Props) {
alt='login banner'
width={100}
height={100}
unoptimized={true}
unoptimized
priority
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
@@ -56,7 +58,7 @@ function StepEnterNumber({ onChange, disabled = false, value }: Props) {
onChange={onChange}
type='number' />
</div>
<Button disabled={disabled || hasError() || value.length <= 0} type='submit'>بعدی</Button>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>بعدی</Button>
</div>
</>
)
+17 -9
View File
@@ -1,6 +1,7 @@
import Button from '@/components/button/PrimaryButton';
import OTPInputField from '@/components/input/MultiInputField';
import { AUTH_PAGE_ELEMENT, AUTH_PAGE_ELEMENT as AUTH_PAGE_ELEMENTS } from '@/enums';
import clsx from 'clsx';
import Image from 'next/image';
import React, { useEffect, useState } from 'react'
@@ -11,9 +12,10 @@ type Props = {
phoneNumber: string;
timerRunning: boolean;
secondsLeft: number;
pending?: boolean | undefined
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'id'>
function StepEnterOtp({ onChange, onClick, disabled = false, value, phoneNumber, timerRunning, secondsLeft }: Props) {
function StepEnterOtp({ onChange, onClick, pending, disabled = false, value, phoneNumber, timerRunning, secondsLeft }: Props) {
const [error, setError] = useState('');
const hasError = (e = error) => {
@@ -37,7 +39,8 @@ function StepEnterOtp({ onChange, onClick, disabled = false, value, phoneNumber,
alt='login banner'
width={100}
height={100}
unoptimized={true}
unoptimized
priority
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='pt-4' dir='rtl'>
@@ -60,22 +63,27 @@ function StepEnterOtp({ onChange, onClick, disabled = false, value, phoneNumber,
onChange={onChange} />
</div>
<div className='inline-flex justify-center items-center w-full pt-6 text-xs'>
<div className='text-center w-full pt-6 text-xs'>
<div dir='rtl'>
{timerRunning ?
<div>{secondsLeft} ثانیه دیگر تا دریافت کد</div> :
<div>
کد را دریافت نکردید؟
<span className='text-primary px-1'>
<button type='button' id={AUTH_PAGE_ELEMENTS.RESEND_OTP} className='cursor-pointer' onClick={onClick}>
دوباره امتحان کنید
</button>
</span>
<button
type='button'
disabled={pending}
id={AUTH_PAGE_ELEMENTS.RESEND_OTP}
className={clsx(
'px-1 transition-colors duration-200',
!pending ? 'text-primary cursor-pointer' : 'text-neutral-200 cursor-auto'
)} onClick={onClick}>
دوباره امتحان کنید
</button>
</div>
}
</div>
</div>
<Button disabled={disabled || hasError() || value.length <= 0} type='submit'>بعدی</Button>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>بعدی</Button>
</div>
</>
)
@@ -11,9 +11,10 @@ type Props = {
value: string;
passwordVisible: boolean;
rememberMe: boolean;
pending?: boolean | undefined
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'id'>
function StepEnterPassword({ onChange, onClick, disabled = false, value, passwordVisible, rememberMe }: Props) {
function StepEnterPassword({ onChange, onClick, pending, disabled = false, value, passwordVisible, rememberMe }: Props) {
const [error, setError] = useState('');
const hasError = (e = error) => {
@@ -39,7 +40,8 @@ function StepEnterPassword({ onChange, onClick, disabled = false, value, passwor
alt='login banner'
width={100}
height={100}
unoptimized={true}
unoptimized
priority
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
@@ -72,7 +74,7 @@ function StepEnterPassword({ onChange, onClick, disabled = false, value, passwor
<input name={AUTH_PAGE_ELEMENT.INPUT_REMEMBER_ME} className='h-4.5 w-4.5 checked:accent-primary' onChange={onChange} type='checkbox' checked={rememberMe} /></div>
</div>
</div>
<Button disabled={disabled || hasError() || value.length <= 0} type='submit'>ورود به منو</Button>
<Button disabled={disabled || hasError() || value.length <= 0} pending={pending} type='submit'>ورود به منو</Button>
</div>
</>
)
@@ -13,9 +13,10 @@ type Props = {
isReset?: boolean;
passwordVisible: boolean;
repeatPasswordVisible: boolean;
pending?: boolean | undefined
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'id'>
function StepNewPassword({ isReset: reset = false, disabled = false, onChange, onClick, value, repeatValue, passwordVisible, repeatPasswordVisible }: Props) {
function StepNewPassword({ isReset: reset = false, pending, disabled = false, onChange, onClick, value, repeatValue, passwordVisible, repeatPasswordVisible }: Props) {
const [error, setError] = useState('');
const [error2, setError2] = useState('');
@@ -25,28 +26,23 @@ function StepNewPassword({ isReset: reset = false, disabled = false, onChange, o
useEffect(() => {
let error = '';
let error2 = '';
if (value.length > 0) {
if (!/^.{6,}$/.test(value)) {
error = 'کلمه عبور باید شامل حداقل 6 کاراکتر باشد';
}
}
setError(error);
}, [value])
useEffect(() => {
let error = '';
if (value.length > 0) {
if (!/^.{6,}$/.test(value)) {
error = 'کلمه عبور باید شامل حداقل 6 کاراکتر باشد';
if (repeatValue.length > 0) {
if (!/^.{6,}$/.test(repeatValue)) {
error2 = 'کلمه عبور باید شامل حداقل 6 کاراکتر باشد';
} else if (repeatValue !== value) {
error = 'تکرار کلمه عبور مطابقت ندارد';
error2 = 'تکرار کلمه عبور مطابقت ندارد';
}
}
setError2(error);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [repeatValue])
setError(error);
setError2(error2);
}, [value, repeatValue])
return (
<>
@@ -56,7 +52,8 @@ function StepNewPassword({ isReset: reset = false, disabled = false, onChange, o
alt='login banner'
width={100}
height={100}
unoptimized={true}
unoptimized
priority
/>
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
@@ -97,7 +94,7 @@ function StepNewPassword({ isReset: reset = false, disabled = false, onChange, o
</button>
</InputField>
</div>
<Button disabled={disabled || hasError() || hasError(error2) || value.length <= 0} type='submit'>ورود</Button>
<Button disabled={disabled || hasError() || hasError(error2) || value.length <= 0} pending={pending} type='submit'>ورود</Button>
</div>
</>
)