fix(mobile): improve scroll restoration, media gesture swipe, 5-digit otp, persistent cooldown and modal android back navigation
Deploy Canina / deploy (push) Successful in 2m6s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 0s

This commit is contained in:
parsa aghaei committed 2026-09-05 17:53:29 +03:30
1 parent 00cfd1a2a0
commit 1d2d141514
16 files changed
+12610 -11527

No files matched your search

+73 -79
View File
@@ -30,6 +30,8 @@ import { authService } from "../lib/services/authService";
import { toast } from "sonner";
import { toPersian, toEnglishDigits, cn } from "../lib/utils";
import OtpInput5 from "./OtpInput5";
interface AuthModalProps {
isOpen: boolean;
onClose: () => void;
@@ -43,12 +45,15 @@ function extractOtpFromText(text: string): string {
return clean.replace(/[^0-9]/g, "").slice(0, 5);
}
// Global OTP expiry timestamp cache by phone number so switching back and forth preserves timer
const otpCooldownExpiries: Record<string, number> = {};
export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
const { fetchProfile } = useUserStore();
// Auth navigation state
const [authMode, setAuthMode] = useState<"login" | "register">("login");
const [loginMethod, setLoginMethod] = useState<"otp" | "password">("password");
const [loginMethod, setLoginMethod] = useState<"otp" | "password">("otp");
const [subView, setSubView] = useState<"main" | "otp-verify" | "forgot-phone" | "forgot-otp" | "reset-password" | "b2b">("main");
// Form fields
@@ -69,28 +74,54 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
const [showPassword, setShowPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const otpInputRef = useRef<HTMLInputElement>(null);
const phoneNumberRef = useRef(phoneNumber);
const subViewRef = useRef(subView);
const isOpenRef = useRef(isOpen);
const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true));
useEffect(() => {
phoneNumberRef.current = phoneNumber;
}, [phoneNumber]);
// Focus retry when OTP input is shown
useEffect(() => {
if (subView === "otp-verify" || subView === "forgot-otp") {
const timers = [50, 150, 300, 500].map((delay) =>
setTimeout(() => {
if (otpInputRef.current) {
otpInputRef.current.focus({ preventScroll: true });
}
}, delay),
);
return () => timers.forEach((t) => clearTimeout(t));
}
subViewRef.current = subView;
}, [subView]);
useEffect(() => {
isOpenRef.current = isOpen;
}, [isOpen]);
// Handle hardware / browser back button for Android & mobile navigation
useEffect(() => {
if (!isOpen) return;
// Push a state for this modal level
const currentState = window.history.state || {};
window.history.pushState({ ...currentState, __authModalOpen: true, __subView: subView }, "");
const handlePopState = (e: PopStateEvent) => {
// If user hit Android back button
if (subViewRef.current !== "main") {
// Go back inside modal
if (subViewRef.current === "forgot-otp") {
setSubView("forgot-phone");
} else if (subViewRef.current === "reset-password") {
setSubView("forgot-phone");
} else {
setSubView("main");
}
} else {
// In main view: close modal without navigating the page behind
onClose();
}
};
window.addEventListener("popstate", handlePopState);
return () => {
window.removeEventListener("popstate", handlePopState);
};
}, [isOpen, subView, onClose]);
// Reset modal state on open/close
useEffect(() => {
if (!isOpen) {
@@ -167,9 +198,6 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
const clean = extractOtpFromText(otp.code);
if (clean) {
setOtpCode(clean);
if (otpInputRef.current) {
otpInputRef.current.value = clean;
}
if (clean.length === 5 && subView === "otp-verify") {
triggerVerifyOtp(clean);
}
@@ -179,39 +207,15 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
.catch(() => {});
}
const inputEl = otpInputRef.current;
const handleDomAutofill = (e: Event) => {
const target = e.target as HTMLInputElement;
if (target && target.value) {
const clean = extractOtpFromText(target.value);
setOtpCode(clean);
if (clean.length === 5 && subView === "otp-verify") {
triggerVerifyOtp(clean);
}
}
};
if (inputEl) {
inputEl.addEventListener("input", handleDomAutofill);
inputEl.addEventListener("change", handleDomAutofill);
}
return () => {
isMounted = false;
ac.abort();
if (inputEl) {
inputEl.removeEventListener("input", handleDomAutofill);
inputEl.removeEventListener("change", handleDomAutofill);
}
};
}, [subView, triggerVerifyOtp]);
const handleOtpChange = (val: string) => {
const clean = extractOtpFromText(val);
setOtpCode(clean);
if (otpInputRef.current && otpInputRef.current.value !== clean) {
otpInputRef.current.value = clean;
}
if (clean.length === 5 && subView === "otp-verify") {
triggerVerifyOtp(clean);
}
@@ -225,6 +229,17 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
return;
}
// Check if cooldown is still active for this phone number
const now = Date.now();
const existingExpiry = otpCooldownExpiries[cleanPhone] || 0;
const remainingSeconds = Math.max(0, Math.ceil((existingExpiry - now) / 1000));
if (remainingSeconds > 0) {
setCountdown(remainingSeconds);
setSubView("otp-verify");
return;
}
setIsLoading(true);
try {
const res = await authService.sendOtp(cleanPhone);
@@ -235,6 +250,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
toast.success("کد تایید با موفقیت پیامک شد");
}
setSubView("otp-verify");
otpCooldownExpiries[cleanPhone] = Date.now() + 120 * 1000;
setCountdown(120);
} catch (err: unknown) {
const errObj = err as { message?: string };
@@ -302,10 +318,12 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
const handleResendOtp = async () => {
if (countdown > 0) return;
const cleanPhone = toEnglishDigits(phoneNumber).trim();
setIsLoading(true);
try {
await authService.sendOtp(toEnglishDigits(phoneNumber).trim());
await authService.sendOtp(cleanPhone);
toast.success("کد تایید جدید پیامک شد");
otpCooldownExpiries[cleanPhone] = Date.now() + 120 * 1000;
setCountdown(120);
} catch (err: unknown) {
const errObj = err as { message?: string };
@@ -483,7 +501,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
)}
>
<KeyRound className="w-3 h-3" />
<span>رمز عبور (پیش‌فرض)</span>
<span>رمز عبور</span>
</button>
<button
type="button"
@@ -765,29 +783,13 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
<label className="text-[11px] font-black text-medical-gray-500 block text-center">
کد ۵ رقمی ارسال‌شده به موبایل خود را وارد نمایید
</label>
<div className="relative">
<input
ref={otpInputRef}
id="otp-code-input"
name="one-time-code"
type="tel"
inputMode="numeric"
pattern="[0-9]*"
autoComplete="one-time-code"
placeholder="• • • • •"
value={otpCode}
onChange={(e) => handleOtpChange(e.target.value)}
onInput={(e) => handleOtpChange((e.target as HTMLInputElement).value)}
onPaste={(e) => {
e.preventDefault();
const pasted = e.clipboardData.getData('text');
handleOtpChange(pasted);
}}
disabled={isLoading}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 px-4 focus:ring-2 focus:ring-canina-blue/20 outline-none font-bold text-center text-2xl font-mono tracking-[0.4em]"
dir="ltr"
/>
</div>
<OtpInput5
value={otpCode}
onChange={handleOtpChange}
disabled={isLoading}
autoFocus={true}
onComplete={(code) => triggerVerifyOtp(code)}
/>
<p className="text-[10px] text-medical-gray-400 text-center font-medium">
در صورت دریافت پیامک، کد به صورت خودکار شناسایی و وارد می‌شود.
</p>
@@ -907,20 +909,12 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
<label className="text-[11px] font-black text-medical-gray-500 block text-center font-vazir">
کد ۵ رقمی بازیابی پیامک‌شده را وارد کنید
</label>
<div className="relative">
<input
ref={otpInputRef}
autoFocus
type="text"
inputMode="numeric"
autoComplete="one-time-code"
placeholder="• • • • •"
value={otpCode}
onChange={(e) => setOtpCode(toEnglishDigits(e.target.value).replace(/[^0-9]/g, "").slice(0, 5))}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 px-4 focus:ring-2 focus:ring-canina-blue/20 outline-none text-center font-mono font-bold text-2xl tracking-[0.4em]"
dir="ltr"
/>
</div>
<OtpInput5
value={otpCode}
onChange={(val) => setOtpCode(val)}
disabled={isLoading}
autoFocus={true}
/>
</div>
<button