diff --git a/frontend/application/app/ClientLayout.tsx b/frontend/application/app/ClientLayout.tsx index eeb5fa06..5d0a9920 100644 --- a/frontend/application/app/ClientLayout.tsx +++ b/frontend/application/app/ClientLayout.tsx @@ -21,6 +21,12 @@ import { useUIStore } from "../lib/store/uiStore"; import MaintenancePage from "../components/MaintenancePage"; import { NavigationTarget } from "../lib/types"; +// Module-level flag: survives across effect re-runs because it lives outside the component. +// When the user presses Back/Forward, popstate fires BEFORE pathname changes. +// The flag is read (and reset) in the pathname effect which runs AFTER. +let _wasPopNavigation = false; + + export default function ClientLayout({ children }: { children: React.ReactNode }) { const isCartOpen = useUIStore((state) => state.isCartOpen); const isLoginModalOpen = useUIStore((state) => state.isLoginModalOpen); @@ -52,36 +58,68 @@ export default function ClientLayout({ children }: { children: React.ReactNode } useUserStore.getState().logout(); } - // Preserve scroll restoration on back/forward + // Let the browser handle scroll restoration on Back/Forward navigation. + // We separately implement push-navigation scroll-to-top below. if (typeof window !== 'undefined' && 'scrollRestoration' in window.history) { - window.history.scrollRestoration = 'auto'; + window.history.scrollRestoration = 'manual'; } + + // Permanent listener: set the flag whenever any popstate fires. + // This includes modal sentinel pops - those don't change pathname so they + // are harmless (the pathname effect won't run, flag stays set until the + // next real back navigation that DOES change pathname). + const handlePopState = () => { _wasPopNavigation = true; }; + window.addEventListener('popstate', handlePopState); + return () => window.removeEventListener('popstate', handlePopState); }, [fetchProfile, fetchSettings]); - // Track navigation type (push vs pop) to allow smooth scroll restoration on Back/Forward + + // Scroll-to-top only on PUSH navigation, not on Back/Forward. + // _wasPopNavigation is set by the permanent popstate listener above + // BEFORE this effect runs for the new pathname. useEffect(() => { if (typeof window === 'undefined') return; - - let popstateTriggered = false; - const handlePopState = () => { - popstateTriggered = true; - }; - - window.addEventListener('popstate', handlePopState); - - // Give microtask/frame for popstate event to register before checking - const timeoutId = setTimeout(() => { - if (!popstateTriggered) { - window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); + if (_wasPopNavigation) { + // Back/Forward: restore the previously saved scroll position. + _wasPopNavigation = false; + const savedY = sessionStorage.getItem(`__scroll_${pathname}`); + if (savedY) { + const y = parseInt(savedY, 10); + // Double rAF: first waits for React commit, second waits for paint + requestAnimationFrame(() => + requestAnimationFrame(() => + window.scrollTo({ top: y, behavior: 'instant' }) + ) + ); } - }, 0); + return; + } + // Push navigation (link click, router.push): scroll to top immediately. + window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); + }, [pathname]); + // Save current scroll position to sessionStorage (debounced + on cleanup) + // so it can be restored on Back navigation. + useEffect(() => { + if (typeof window === 'undefined') return; + const key = `__scroll_${pathname}`; + let debounceTimer: ReturnType; + const handleScroll = () => { + clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => { + sessionStorage.setItem(key, String(window.scrollY)); + }, 100); + }; + window.addEventListener('scroll', handleScroll, { passive: true }); return () => { - window.removeEventListener('popstate', handlePopState); - clearTimeout(timeoutId); + clearTimeout(debounceTimer); + // Save immediately on exit (before pathname changes) + sessionStorage.setItem(key, String(window.scrollY)); + window.removeEventListener('scroll', handleScroll); }; }, [pathname]); + // Check Maintenance Mode (Admin / Partner bypass) const isMaintenanceMode = getText('MAINTENANCE_MODE', 'false') === 'true' || getText('maintenance_mode', 'false') === 'true'; const isAdmin = role === 'User_Partner' || (typeof window !== 'undefined' && Boolean(localStorage.getItem('adminToken'))); diff --git a/frontend/application/components/AuthModal.tsx b/frontend/application/components/AuthModal.tsx index 45465c00..60150dd8 100644 --- a/frontend/application/components/AuthModal.tsx +++ b/frontend/application/components/AuthModal.tsx @@ -77,6 +77,8 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { const phoneNumberRef = useRef(phoneNumber); const subViewRef = useRef(subView); const isOpenRef = useRef(isOpen); + // Guard against double-verify (onComplete fires, then form submit also fires) + const isVerifyingRef = useRef(false); const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true)); useEffect(() => { @@ -92,17 +94,17 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { }, [isOpen]); // Handle hardware / browser back button for Android & mobile navigation + // IMPORTANT: only depend on isOpen here — NOT subView. If we depend on subView, + // every subView change pushes a new history entry and back button never closes the modal. useEffect(() => { if (!isOpen) return; - // Push a state for this modal level - const currentState = window.history.state || {}; - window.history.pushState({ ...currentState, __authModalOpen: true, __subView: subView }, ""); + // Push ONE history entry when the modal opens so back button hits this entry first + window.history.pushState({ __authModalOpen: true }, ""); - const handlePopState = (e: PopStateEvent) => { - // If user hit Android back button + const handlePopState = () => { if (subViewRef.current !== "main") { - // Go back inside modal + // Navigate back within the modal if (subViewRef.current === "forgot-otp") { setSubView("forgot-phone"); } else if (subViewRef.current === "reset-password") { @@ -110,8 +112,10 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { } else { setSubView("main"); } + // Push another sentinel so the next back also hits this handler + window.history.pushState({ __authModalOpen: true }, ""); } else { - // In main view: close modal without navigating the page behind + // Already at main view — close the modal onClose(); } }; @@ -120,7 +124,8 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { return () => { window.removeEventListener("popstate", handlePopState); }; - }, [isOpen, subView, onClose]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpen]); // Reset modal state on open/close useEffect(() => { @@ -160,6 +165,9 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { const cleanCode = extractOtpFromText(codeToVerify); const cleanPhone = toEnglishDigits(phoneNumberRef.current).replace(/[^0-9]/g, ""); if (cleanCode.length !== 5 || !cleanPhone) return; + // Prevent double-call from onComplete + form submit firing simultaneously + if (isVerifyingRef.current) return; + isVerifyingRef.current = true; setIsLoading(true); try { @@ -172,6 +180,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { } catch (err: unknown) { const errObj = err as { message?: string }; toast.error(errObj.message || "کد تایید نامعتبر است"); + isVerifyingRef.current = false; } finally { setIsLoading(false); } @@ -179,48 +188,20 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { [fetchProfile, onClose], ); - // WebOTP API SMS Auto-read - useEffect(() => { - if (subView !== "otp-verify" && subView !== "forgot-otp") return; - let isMounted = true; - const ac = new AbortController(); - - if (typeof window !== "undefined" && "OTPCredential" in window) { - (navigator as unknown as { credentials: { get: (opts: unknown) => Promise<{ code?: string }> } }).credentials - ?.get({ - otp: { transport: ["sms"] }, - signal: ac.signal, - }) - .then((otp) => { - if (!isMounted) return; - if (otp && typeof otp.code === "string") { - const clean = extractOtpFromText(otp.code); - if (clean) { - setOtpCode(clean); - if (clean.length === 5 && subView === "otp-verify") { - triggerVerifyOtp(clean); - } - } - } - }) - .catch(() => {}); - } - - return () => { - isMounted = false; - ac.abort(); - }; - }, [subView, triggerVerifyOtp]); + // NOTE: We intentionally do NOT use navigator.credentials.get (WebOTP API) here + // because it shows an intrusive browser permission modal that is poor UX. + // autoComplete="one-time-code" on the first OTP input provides the native + // suggestion bar above the keyboard on Android without any permission dialog. const handleOtpChange = (val: string) => { const clean = extractOtpFromText(val); setOtpCode(clean); - if (clean.length === 5 && subView === "otp-verify") { - triggerVerifyOtp(clean); - } + // Auto-verify is handled by OtpInput5's onComplete callback only + // to prevent double-submission }; + const handleSendOtp = async (e?: React.FormEvent) => { if (e) e.preventDefault(); const cleanPhone = toEnglishDigits(phoneNumber).trim(); @@ -915,6 +896,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { disabled={isLoading} autoFocus={true} /> +