From 86e8101d8c552f6815a92a5d990f3924575f261e Mon Sep 17 00:00:00 2001
From: parsa aghaei
Date: Sat, 5 Sep 2026 18:19:11 +0330
Subject: [PATCH] fix: mobile UX improvements - scroll restoration, OTP
autofill, swipe direction, back button
- ClientLayout: implement proper manual scroll restoration using module-level
_wasPopNavigation flag and sessionStorage. Fixes scroll jumping to top/bottom
on Back navigation. Scroll position saved on scroll (debounced) and cleanup,
restored via double-rAF on popstate navigation.
- AuthModal/LoginModal: fix Android back button to push only ONE history sentinel
on modal open (not on every subView/step change). Prevents stacking of extra
history entries. Back in sub-views re-pushes sentinel for next back press.
- AuthModal/LoginModal: remove navigator.credentials.get (WebOTP API) which was
showing an intrusive permission modal. The native autoComplete=one-time-code
on the first OTP input provides the suggestion bar above the keyboard instead.
- AuthModal/LoginModal: add isVerifyingRef guard to prevent double toast on
successful login. Both onComplete callback and form submit were calling
triggerVerifyOtp/handleVerifyOtpWithCode simultaneously.
- AuthModal: remove triggerVerifyOtp from handleOtpChange to eliminate the second
duplicate call (only onComplete now triggers verification).
- OtpInput5: remove maxLength=1 restriction from first input so browser can
inject the full 5-digit OTP code. Multi-char input is already handled by
handleDigitChange which distributes digits across all boxes.
- ProductPage: fix swipe gesture direction in media gallery. Swipe right -> next
item, swipe left -> previous item (matches RTL intuition for Persian users).
---
frontend/application/app/ClientLayout.tsx | 74 +-
frontend/application/components/AuthModal.tsx | 68 +-
.../application/components/LoginModal.tsx | 43 +-
frontend/application/components/OtpInput5.tsx | 4 +-
.../application/components/ProductPage.tsx | 12 +-
graphify-out/.graphify_labels.json | 53 +-
graphify-out/.graphify_labels.json.sig | 2 +-
graphify-out/2026-09-05/.graphify_labels.json | 48 +-
graphify-out/2026-09-05/GRAPH_REPORT.md | 258 +-
graphify-out/2026-09-05/graph.json | 9062 +++++++++--------
graphify-out/2026-09-05/manifest.json | 1294 +--
graphify-out/GRAPH_REPORT.md | 261 +-
graphify-out/cache/stat-index.json | 2 +-
graphify-out/graph.html | 8 +-
graphify-out/graph.json | 7596 +++++++-------
graphify-out/manifest.json | 1276 +--
16 files changed, 10175 insertions(+), 9886 deletions(-)
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}
/>
+