acupedia-store-ui/src/components/common/PhoneInput.tsx

174 lines
6.3 KiB
TypeScript

import React from 'react';
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation';
export interface PhoneInputProps {
dialCode: string;
phone: string; // local digits only
country?: string;
onDialCodeChange?: (newCode: string, newCountry: string) => void;
onPhoneChange: (newPhone: string) => void;
error?: string | null;
disabled?: boolean;
theme?: 'dark' | 'light';
id?: string;
clearOnDialCodeChange?: boolean;
}
export const PhoneInput: React.FC<PhoneInputProps> = ({
dialCode,
phone,
country,
onDialCodeChange,
onPhoneChange,
error,
disabled = false,
theme = 'dark',
id = 'phone-input',
clearOnDialCodeChange = false,
}) => {
let activeRule = getCountryRuleByDialCode(dialCode);
if (!activeRule && country) {
activeRule = getCountryRuleByName(country);
}
if (!activeRule) {
activeRule = getCountryRuleByDialCode('+91')!;
}
const handleDialCodeSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newCode = e.target.value;
const rule = getCountryRuleByDialCode(newCode);
const newCountry = rule ? rule.country : (country || 'India');
if (onDialCodeChange) {
onDialCodeChange(newCode, newCountry);
}
if (clearOnDialCodeChange) {
onPhoneChange('');
} else if (rule) {
onPhoneChange(cleanPhoneInput(phone, rule.maxLength, false));
}
};
const handlePhoneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const inputVal = e.target.value;
const trimmed = inputVal.trim();
// Check if input contains an explicit international prefix '+'
if (trimmed.startsWith('+')) {
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) {
if (onDialCodeChange && matched.code !== dialCode) {
onDialCodeChange(matched.code, matched.country);
}
const rest = trimmed.slice(matched.code.length).replace(/\D/g, '');
onPhoneChange(rest.slice(0, matched.maxLength));
return;
}
}
// Check if input was pasted with dial code digits without '+' (e.g. 919876543210)
const dialDigits = activeRule.code.replace(/\D/g, '');
const rawDigits = trimmed.replace(/\D/g, '');
if (
dialDigits &&
rawDigits.startsWith(dialDigits) &&
rawDigits.length > activeRule.maxLength
) {
const rest = rawDigits.slice(dialDigits.length);
onPhoneChange(rest.slice(0, activeRule.maxLength));
return;
}
// Strictly numeric local digits, capped at active country's maxLength
const cleaned = cleanPhoneInput(inputVal, activeRule.maxLength, false);
onPhoneChange(cleaned);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// Allow navigation keys, backspace, delete, tab, copy/paste shortcuts
if (
['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab', 'Enter', 'Escape'].includes(e.key) ||
(e.ctrlKey || e.metaKey)
) {
return;
}
// Allow '+' as leading character to support international number paste/typing
if (e.key === '+' && (e.currentTarget.selectionStart === 0 || !phone)) {
return;
}
// Block any non-digit
if (!/^\d$/.test(e.key)) {
e.preventDefault();
}
};
const isDark = theme === 'dark';
return (
<div className="space-y-1.5 w-full">
<div className="flex gap-2 w-full">
{/* Country Code Dropdown */}
<div className="relative shrink-0 w-[105px]">
<select
value={dialCode}
onChange={handleDialCodeSelect}
disabled={disabled}
className={`w-full rounded-xl px-2.5 py-2.5 text-xs font-semibold appearance-none pr-6 cursor-pointer focus:outline-none transition-colors ${
isDark
? 'bg-slate-950 border border-slate-800 text-white focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
>
{COUNTRY_CODES.map((cc) => (
<option key={`${cc.country}-${cc.code}`} value={cc.code}>
{cc.label} ({cc.country})
</option>
))}
</select>
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400 text-[10px]">
▼
</div>
</div>
{/* Numeric-Only Local Phone Input */}
<input
id={id}
type="tel"
inputMode="numeric"
autoComplete="tel-national"
value={phone}
onChange={handlePhoneInputChange}
onKeyDown={handleKeyDown}
placeholder={activeRule.placeholder || 'Mobile Number'}
maxLength={activeRule.maxLength}
disabled={disabled}
className={`min-w-0 flex-1 rounded-xl px-3.5 py-2.5 text-xs sm:text-sm font-semibold focus:outline-none transition-colors ${
isDark
? 'bg-slate-950 border border-slate-800 text-white placeholder:text-slate-600 focus:border-indigo-500'
: 'bg-white border border-slate-200 text-slate-800 placeholder:text-slate-400 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500'
} ${error ? 'border-rose-500 focus:border-rose-500' : ''} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
/>
</div>
{/* Helper text or Error message */}
<div className="flex justify-between items-center text-[10px] px-0.5">
{error ? (
<p className="text-rose-500 font-bold">{error}</p>
) : (
<p className={isDark ? 'text-slate-400 font-medium' : 'text-slate-500 font-medium'}>
{activeRule.label || activeRule.country}:{' '}
{activeRule.minLength === activeRule.maxLength
? `Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.minLength} to ${activeRule.maxLength} digits`}
</p>
)}
<span className={`font-mono font-semibold ${phone.length === activeRule.maxLength ? 'text-emerald-500' : isDark ? 'text-slate-500' : 'text-slate-400'}`}>
{phone.length}/{activeRule.maxLength}
</span>
</div>
</div>
);
};