feat(store): add search bar, alphabetical sorting, and country code display to phone input (issue #84)

- Replace native HTML select in PhoneInput with a custom searchable popover dropdown
- Sort country options alphabetically using SORTED_COUNTRY_CODES
- Display flag, country name, and dial code clearly for each option
- Support search filtering by country name, formatted dial code (+XX), and raw numeric code
- Apply seamlessly to Registration (AuthModal) and User Profile (ProfileDrawer)
This commit is contained in:
ShivaniKhaire 2026-11-17 13:12:57 +05:30
parent 401ebb40d5
commit 1567a96c54
1 changed files with 193 additions and 25 deletions

View File

@ -1,5 +1,12 @@
import React from 'react';
import { COUNTRY_CODES, getCountryRuleByDialCode, getCountryRuleByName } from '../../constants/countries';
import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Search, ChevronDown, Check, X } from 'lucide-react';
import {
COUNTRY_CODES,
SORTED_COUNTRY_CODES,
getCountryRuleByDialCode,
getCountryRuleByName,
type CountryCode,
} from '../../constants/countries';
import { cleanPhoneInput } from '../../utils/validation';
export interface PhoneInputProps {
@ -27,6 +34,11 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
id = 'phone-input',
clearOnDialCodeChange = false,
}) => {
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const dropdownRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
let activeRule = getCountryRuleByDialCode(dialCode);
if (!activeRule && country) {
activeRule = getCountryRuleByName(country);
@ -35,18 +47,79 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
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');
// Focus search input when dropdown opens
useEffect(() => {
if (isDropdownOpen) {
setTimeout(() => {
searchInputRef.current?.focus();
}, 50);
} else {
setSearchQuery('');
}
}, [isDropdownOpen]);
// Handle click outside to close dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsDropdownOpen(false);
}
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setIsDropdownOpen(false);
}
};
if (isDropdownOpen) {
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
};
}, [isDropdownOpen]);
// Filter countries alphabetically by country name or dial code
const filteredCountryCodes = useMemo(() => {
if (!searchQuery.trim()) {
return SORTED_COUNTRY_CODES;
}
const q = searchQuery.toLowerCase().trim();
return SORTED_COUNTRY_CODES.filter((c: CountryCode) => {
const matchCountry = c.country.toLowerCase().includes(q);
const matchCode = c.code.toLowerCase().includes(q);
const rawCode = c.code.replace('+', '');
const matchRaw = rawCode.includes(q);
return matchCountry || matchCode || matchRaw;
});
}, [searchQuery]);
const getFlag = (cc: CountryCode) => {
return cc.label ? cc.label.split(' ')[0] : '🌐';
};
const isSelected = (cc: CountryCode) => {
if (country) {
return cc.country.toLowerCase() === country.toLowerCase() && cc.code === dialCode;
}
return cc.code === dialCode;
};
const handleSelectCountry = (cc: CountryCode) => {
if (onDialCodeChange) {
onDialCodeChange(newCode, newCountry);
onDialCodeChange(cc.code, cc.country);
}
if (clearOnDialCodeChange) {
onPhoneChange('');
} else if (rule) {
onPhoneChange(cleanPhoneInput(phone, rule.maxLength, false));
} else {
onPhoneChange(cleanPhoneInput(phone, cc.maxLength, false));
}
setIsDropdownOpen(false);
setSearchQuery('');
};
const handlePhoneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
@ -108,27 +181,123 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
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}
{/* Searchable Country Code Dropdown */}
<div ref={dropdownRef} className="relative shrink-0">
<button
type="button"
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 ${
onClick={() => !disabled && setIsDropdownOpen(!isDropdownOpen)}
className={`w-[110px] flex items-center justify-between rounded-xl px-2.5 py-2.5 text-xs font-semibold 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 className="flex items-center gap-1.5 truncate">
<span className="text-sm shrink-0 leading-none">{getFlag(activeRule)}</span>
<span className="font-mono text-xs font-bold">{activeRule.code}</span>
</div>
<ChevronDown
className={`h-3.5 w-3.5 shrink-0 text-slate-400 transition-transform duration-200 ${
isDropdownOpen ? 'rotate-180' : ''
}`}
/>
</button>
{/* Searchable Dropdown Popover */}
{isDropdownOpen && (
<div
className={`absolute left-0 top-full mt-1.5 z-50 w-72 sm:w-80 rounded-2xl shadow-2xl border overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-150 ${
isDark
? 'bg-slate-900 border-slate-800 text-white'
: 'bg-white border-slate-200 text-slate-800'
}`}
>
{/* Search Box */}
<div
className={`p-2.5 border-b shrink-0 ${
isDark ? 'border-slate-800 bg-slate-950/60' : 'border-slate-100 bg-slate-50/70'
}`}
>
<div className="relative">
<Search
className={`absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 ${
isDark ? 'text-slate-500' : 'text-slate-400'
}`}
/>
<input
ref={searchInputRef}
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search country or code..."
className={`w-full rounded-xl pl-8 pr-8 py-1.5 text-xs 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'
}`}
/>
{searchQuery && (
<button
type="button"
onClick={() => setSearchQuery('')}
className={`absolute right-2.5 top-1/2 -translate-y-1/2 p-0.5 rounded-full hover:bg-slate-200/50 ${
isDark ? 'text-slate-400 hover:text-white' : 'text-slate-400 hover:text-slate-600'
}`}
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{/* Alphabetically Sorted Options List */}
<div className="max-h-60 overflow-y-auto overscroll-contain py-1">
{filteredCountryCodes.length === 0 ? (
<div
className={`p-4 text-center text-xs ${
isDark ? 'text-slate-500' : 'text-slate-400'
}`}
>
No country codes found matching &ldquo;{searchQuery}&rdquo;
</div>
) : (
filteredCountryCodes.map((cc) => {
const selected = isSelected(cc);
return (
<button
key={`${cc.country}-${cc.code}`}
type="button"
onClick={() => handleSelectCountry(cc)}
className={`w-full flex items-center justify-between px-3.5 py-2 text-left text-xs transition-colors cursor-pointer ${
selected
? isDark
? 'bg-indigo-600/20 text-indigo-400 font-bold'
: 'bg-indigo-50 text-indigo-700 font-bold'
: isDark
? 'hover:bg-slate-800/80 text-slate-200'
: 'hover:bg-slate-50 text-slate-700'
}`}
>
<div className="flex items-center gap-2.5 min-w-0 pr-2">
<span className="text-base shrink-0 leading-none">{getFlag(cc)}</span>
<span className="truncate">{cc.country}</span>
<span
className={`text-[11px] font-mono shrink-0 ${
isDark ? 'text-slate-400' : 'text-slate-500'
}`}
>
({cc.code})
</span>
</div>
{selected && <Check className="h-3.5 w-3.5 shrink-0 text-indigo-500" />}
</button>
);
})
)}
</div>
</div>
)}
</div>
{/* Numeric-Only Local Phone Input */}
@ -170,4 +339,3 @@ export const PhoneInput: React.FC<PhoneInputProps> = ({
</div>
);
};