fix(mobile): improve scroll restoration, media gesture swipe, 5-digit otp, persistent cooldown and modal android back navigation
This commit is contained in:
1 parent
00cfd1a2a0
commit
1d2d141514
16 files changed
+12610
-11527
No files matched your search
@@ -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
|
||||
|
||||
@@ -7,6 +7,8 @@ import { useUserStore } from "../lib/store/userStore";
|
||||
import { toast } from "sonner";
|
||||
import { toPersian } from "../lib/utils";
|
||||
|
||||
import OtpInput5 from "./OtpInput5";
|
||||
|
||||
interface LoginModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
@@ -15,6 +17,8 @@ interface LoginModalProps {
|
||||
isAdvisorContext?: boolean;
|
||||
}
|
||||
|
||||
const loginOtpCooldownExpiries: Record<string, number> = {};
|
||||
|
||||
export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdvisorContext }: LoginModalProps) {
|
||||
const [step, setStep] = useState<"phone" | "otp">("phone");
|
||||
const [phoneNumber, setPhoneNumber] = useState("");
|
||||
@@ -22,17 +26,33 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [countdown, setCountdown] = useState(0);
|
||||
const { fetchProfile } = useUserStore();
|
||||
const otpInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const stepRef = useRef(step);
|
||||
useEffect(() => {
|
||||
if (step === "otp") {
|
||||
const timer = setTimeout(() => {
|
||||
otpInputRef.current?.focus();
|
||||
}, 100);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
stepRef.current = step;
|
||||
}, [step]);
|
||||
|
||||
// Handle hardware / Android back button
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const currentState = window.history.state || {};
|
||||
window.history.pushState({ ...currentState, __loginModalOpen: true, __loginStep: step }, "");
|
||||
|
||||
const handlePopState = () => {
|
||||
if (stepRef.current === "otp") {
|
||||
setStep("phone");
|
||||
} else {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("popstate", handlePopState);
|
||||
return () => {
|
||||
window.removeEventListener("popstate", handlePopState);
|
||||
};
|
||||
}, [isOpen, step, onClose]);
|
||||
|
||||
const handleVerifyOtpWithCode = React.useCallback(async (code: string) => {
|
||||
const cleanCode = code.trim();
|
||||
if (cleanCode.length !== 5) {
|
||||
@@ -69,8 +89,11 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
})
|
||||
.then((otp) => {
|
||||
if (otp && otp.code) {
|
||||
setOtpCode(otp.code);
|
||||
handleVerifyOtpWithCode(otp.code);
|
||||
const clean = otp.code.replace(/[^0-9]/g, "").slice(0, 5);
|
||||
setOtpCode(clean);
|
||||
if (clean.length === 5) {
|
||||
handleVerifyOtpWithCode(clean);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
@@ -80,23 +103,6 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
}
|
||||
}, [step, handleVerifyOtpWithCode]);
|
||||
|
||||
const handleOtpInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const val = e.target.value.replace(/[^0-9]/g, "").slice(0, 5);
|
||||
setOtpCode(val);
|
||||
if (val.length === 5) {
|
||||
handleVerifyOtpWithCode(val);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOtpPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
const pasted = e.clipboardData.getData("text").replace(/[^0-9]/g, "").slice(0, 5);
|
||||
if (pasted.length === 5) {
|
||||
e.preventDefault();
|
||||
setOtpCode(pasted);
|
||||
handleVerifyOtpWithCode(pasted);
|
||||
}
|
||||
};
|
||||
|
||||
// Reset modal state when closed or opened
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
@@ -126,6 +132,16 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const existingExpiry = loginOtpCooldownExpiries[cleanPhone] || 0;
|
||||
const remainingSeconds = Math.max(0, Math.ceil((existingExpiry - now) / 1000));
|
||||
|
||||
if (remainingSeconds > 0) {
|
||||
setCountdown(remainingSeconds);
|
||||
setStep("otp");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await authService.sendOtp(cleanPhone);
|
||||
@@ -136,7 +152,8 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
toast.success("کد تایید پیامک شد");
|
||||
}
|
||||
setStep("otp");
|
||||
setCountdown(120); // 2 minutes cooldown
|
||||
loginOtpCooldownExpiries[cleanPhone] = Date.now() + 120 * 1000;
|
||||
setCountdown(120);
|
||||
} catch (err: unknown) {
|
||||
const errObj = err as { message?: string };
|
||||
toast.error(errObj.message || "خطا در ارسال کد تایید");
|
||||
@@ -152,10 +169,12 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
|
||||
const handleResendOtp = async () => {
|
||||
if (countdown > 0) return;
|
||||
const cleanPhone = phoneNumber.trim();
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await authService.sendOtp(phoneNumber.trim());
|
||||
await authService.sendOtp(cleanPhone);
|
||||
toast.success("کد تایید جدید ارسال شد");
|
||||
loginOtpCooldownExpiries[cleanPhone] = Date.now() + 120 * 1000;
|
||||
setCountdown(120);
|
||||
} catch (err: unknown) {
|
||||
const errObj = err as { message?: string };
|
||||
@@ -278,19 +297,13 @@ export default function LoginModal({ isOpen, onClose, onLogin, petName, isAdviso
|
||||
ویرایش شماره
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Key className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-medical-gray-400" />
|
||||
<input
|
||||
ref={otpInputRef}
|
||||
type="text"
|
||||
maxLength={5}
|
||||
autoComplete="one-time-code"
|
||||
placeholder="کد ۵ رقمی"
|
||||
<div>
|
||||
<OtpInput5
|
||||
value={otpCode}
|
||||
onChange={handleOtpInputChange}
|
||||
onPaste={handleOtpPaste}
|
||||
onChange={(val) => setOtpCode(val)}
|
||||
disabled={isLoading}
|
||||
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-4 pr-12 pl-4 focus:ring-2 focus:ring-canina-blue/20 focus:border-canina-blue outline-none font-black text-2xl text-center tracking-[0.5em]"
|
||||
autoFocus={true}
|
||||
onComplete={(code) => handleVerifyOtpWithCode(code)}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[10px] text-medical-gray-400 font-bold text-center mt-2">
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"use client";
|
||||
|
||||
import React, { useRef, useEffect } from "react";
|
||||
import { toEnglishDigits } from "../lib/utils";
|
||||
|
||||
interface OtpInput5Props {
|
||||
value: string;
|
||||
onChange: (val: string) => void;
|
||||
disabled?: boolean;
|
||||
autoFocus?: boolean;
|
||||
onComplete?: (code: string) => void;
|
||||
}
|
||||
|
||||
export default function OtpInput5({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
autoFocus = true,
|
||||
onComplete,
|
||||
}: OtpInput5Props) {
|
||||
const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
|
||||
|
||||
// Array of 5 characters
|
||||
const digits = Array.from({ length: 5 }, (_, i) => value[i] || "");
|
||||
|
||||
useEffect(() => {
|
||||
if (autoFocus && inputRefs.current[0]) {
|
||||
const timer = setTimeout(() => {
|
||||
inputRefs.current[0]?.focus({ preventScroll: true });
|
||||
}, 80);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [autoFocus]);
|
||||
|
||||
const handleDigitChange = (index: number, char: string) => {
|
||||
const cleanChars = toEnglishDigits(char).replace(/[^0-9]/g, "");
|
||||
if (!cleanChars) {
|
||||
// Empty / Backspace in controlled input
|
||||
const newDigits = [...digits];
|
||||
newDigits[index] = "";
|
||||
const newVal = newDigits.join("");
|
||||
onChange(newVal);
|
||||
return;
|
||||
}
|
||||
|
||||
// If multiple chars pasted or typed
|
||||
if (cleanChars.length > 1) {
|
||||
const slice5 = cleanChars.slice(0, 5);
|
||||
onChange(slice5);
|
||||
const nextIndex = Math.min(slice5.length, 4);
|
||||
inputRefs.current[nextIndex]?.focus();
|
||||
if (slice5.length === 5 && onComplete) {
|
||||
onComplete(slice5);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const single = cleanChars[0];
|
||||
const newDigits = [...digits];
|
||||
newDigits[index] = single;
|
||||
const newVal = newDigits.join("");
|
||||
onChange(newVal);
|
||||
|
||||
if (index < 4) {
|
||||
inputRefs.current[index + 1]?.focus();
|
||||
}
|
||||
|
||||
if (newVal.length === 5 && onComplete) {
|
||||
onComplete(newVal);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Backspace") {
|
||||
if (!digits[index] && index > 0) {
|
||||
// Move to previous and clear
|
||||
inputRefs.current[index - 1]?.focus();
|
||||
const newDigits = [...digits];
|
||||
newDigits[index - 1] = "";
|
||||
onChange(newDigits.join(""));
|
||||
}
|
||||
} else if (e.key === "ArrowLeft") {
|
||||
// In LTR inputs, Left goes to previous
|
||||
if (index > 0) {
|
||||
inputRefs.current[index - 1]?.focus();
|
||||
}
|
||||
} else if (e.key === "ArrowRight") {
|
||||
// In LTR inputs, Right goes to next
|
||||
if (index < 4) {
|
||||
inputRefs.current[index + 1]?.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent) => {
|
||||
e.preventDefault();
|
||||
const pasted = e.clipboardData.getData("text");
|
||||
const clean = toEnglishDigits(pasted).replace(/[^0-9]/g, "").slice(0, 5);
|
||||
if (clean) {
|
||||
onChange(clean);
|
||||
const targetIndex = Math.min(clean.length, 4);
|
||||
inputRefs.current[targetIndex]?.focus();
|
||||
if (clean.length === 5 && onComplete) {
|
||||
onComplete(clean);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center gap-2.5 sm:gap-3.5 my-2" dir="ltr">
|
||||
{[0, 1, 2, 3, 4].map((idx) => {
|
||||
const val = digits[idx] || "";
|
||||
const isFilled = Boolean(val);
|
||||
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
ref={(el) => {
|
||||
inputRefs.current[idx] = el;
|
||||
}}
|
||||
type="tel"
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
maxLength={1}
|
||||
autoComplete={idx === 0 ? "one-time-code" : "off"}
|
||||
value={val}
|
||||
disabled={disabled}
|
||||
onChange={(e) => handleDigitChange(idx, e.target.value)}
|
||||
onKeyDown={(e) => handleKeyDown(idx, e)}
|
||||
onPaste={handlePaste}
|
||||
onFocus={(e) => e.target.select()}
|
||||
className={`w-12 h-14 sm:w-14 sm:h-16 text-center text-xl sm:text-2xl font-black font-mono rounded-2xl border-2 transition-all outline-none shadow-xs ${
|
||||
isFilled
|
||||
? "border-canina-blue bg-canina-blue/5 text-canina-blue ring-2 ring-canina-blue/20"
|
||||
: "border-medical-gray-200 bg-medical-gray-50/80 text-medical-gray-900 focus:border-canina-blue focus:bg-white focus:ring-4 focus:ring-canina-blue/15"
|
||||
} ${disabled ? "opacity-50 cursor-not-allowed" : "cursor-text"}`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
"use client";
|
||||
import { useState, useMemo, useEffect } from "react";
|
||||
import { useState, useMemo, useEffect, useRef } from "react";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ArrowRight,
|
||||
@@ -148,6 +148,18 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
||||
description?: string;
|
||||
} | null>(null);
|
||||
|
||||
const thumbnailContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Auto-scroll active thumbnail into view when changed via gesture/click
|
||||
useEffect(() => {
|
||||
if (thumbnailContainerRef.current) {
|
||||
const activeEl = thumbnailContainerRef.current.children[activeMediaIndex] as HTMLElement;
|
||||
if (activeEl) {
|
||||
activeEl.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
|
||||
}
|
||||
}
|
||||
}, [activeMediaIndex]);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.resolve().then(() => setIsMounted(true));
|
||||
}, []);
|
||||
@@ -442,7 +454,32 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
||||
initial={{ opacity: 0, scale: 0.96 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="bg-white rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200 shadow-xl relative group overflow-hidden h-[280px] sm:h-[390px] flex items-center justify-center p-2 sm:p-4 select-none"
|
||||
drag="x"
|
||||
dragConstraints={{ left: 0, right: 0 }}
|
||||
dragElastic={0.2}
|
||||
onDragEnd={(e, info) => {
|
||||
const swipeThreshold = 50;
|
||||
if (info.offset.x > swipeThreshold || info.velocity.x > 300) {
|
||||
// Swipe right -> in RTL, swipe right goes to previous item, or left/right intuitive navigation
|
||||
if (activeMediaIndex > 0) {
|
||||
const newIdx = activeMediaIndex - 1;
|
||||
setActiveMediaIndex(newIdx);
|
||||
if (galleryMedia[newIdx]?.type === 'image') {
|
||||
setActiveImage(galleryMedia[newIdx].url);
|
||||
}
|
||||
}
|
||||
} else if (info.offset.x < -swipeThreshold || info.velocity.x < -300) {
|
||||
// Swipe left -> go to next item
|
||||
if (activeMediaIndex < galleryMedia.length - 1) {
|
||||
const newIdx = activeMediaIndex + 1;
|
||||
setActiveMediaIndex(newIdx);
|
||||
if (galleryMedia[newIdx]?.type === 'image') {
|
||||
setActiveImage(galleryMedia[newIdx].url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="bg-white rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200 shadow-xl relative group overflow-hidden h-[280px] sm:h-[390px] flex items-center justify-center p-2 sm:p-4 select-none touch-pan-y cursor-grab active:cursor-grabbing"
|
||||
>
|
||||
{/* Top Floating Badges */}
|
||||
<div className="absolute top-4 left-4 sm:top-6 sm:left-6 flex flex-col gap-1.5 sm:gap-2 z-10 items-start pointer-events-none">
|
||||
@@ -577,7 +614,10 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
||||
|
||||
{/* Multiple Gallery Media Thumbnails Strip */}
|
||||
{galleryMedia.length > 1 && (
|
||||
<div className="flex items-center gap-2 overflow-x-auto py-2 px-1 sleek-hscroll">
|
||||
<div
|
||||
ref={thumbnailContainerRef}
|
||||
className="flex items-center gap-2 overflow-x-auto py-2 px-1 sleek-hscroll touch-pan-x cursor-grab active:cursor-grabbing select-none"
|
||||
>
|
||||
{galleryMedia.map((item, idx) => {
|
||||
const isSelected = activeMediaIndex === idx;
|
||||
|
||||
@@ -601,12 +641,12 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
||||
src={item.thumbnail || item.url || product.image}
|
||||
alt={`${product.name} - ${idx + 1}`}
|
||||
className="w-full h-full"
|
||||
imgClassName="w-full h-full object-contain"
|
||||
imgClassName="w-full h-full object-contain pointer-events-none"
|
||||
/>
|
||||
|
||||
{/* Video Overlay Badge on thumbnail */}
|
||||
{item.type === 'video' && (
|
||||
<div className="absolute inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/40 flex items-center justify-center pointer-events-none">
|
||||
<div className="w-6 h-6 rounded-full bg-canina-blue text-white flex items-center justify-center shadow-md">
|
||||
<Play className="w-3 h-3 fill-white ml-0.5" />
|
||||
</div>
|
||||
@@ -618,7 +658,7 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
|
||||
|
||||
{/* Podcast Overlay Badge on thumbnail */}
|
||||
{item.type === 'podcast' && (
|
||||
<div className="absolute inset-0 bg-purple-950/60 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-purple-950/60 flex items-center justify-center pointer-events-none">
|
||||
<div className="w-6 h-6 rounded-full bg-purple-600 text-white flex items-center justify-center shadow-md">
|
||||
<Headphones className="w-3.5 h-3.5 text-white" />
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user