235 lines
9.0 KiB
TypeScript
235 lines
9.0 KiB
TypeScript
import React, { useState, useRef, useEffect, useMemo } from 'react';
|
|
import { Search, ChevronDown, Check, X } from 'lucide-react';
|
|
import { SORTED_COUNTRY_CODES, getCountryRuleByName, type CountryCode } from '../../constants/countries';
|
|
|
|
export interface CountrySelectProps {
|
|
value: string;
|
|
onChange: (country: string) => void;
|
|
theme?: 'dark' | 'light';
|
|
size?: 'sm' | 'md';
|
|
showCurrency?: boolean;
|
|
showDialCode?: boolean;
|
|
disabled?: boolean;
|
|
className?: string;
|
|
placeholder?: string;
|
|
}
|
|
|
|
export const CountrySelect: React.FC<CountrySelectProps> = ({
|
|
value,
|
|
onChange,
|
|
theme = 'light',
|
|
size = 'md',
|
|
showCurrency = false,
|
|
showDialCode = true,
|
|
disabled = false,
|
|
className = '',
|
|
placeholder = 'Select country',
|
|
}) => {
|
|
const [isOpen, setIsOpen] = useState(false);
|
|
const [searchQuery, setSearchQuery] = useState('');
|
|
const containerRef = useRef<HTMLDivElement>(null);
|
|
const searchInputRef = useRef<HTMLInputElement>(null);
|
|
|
|
const selectedRule = useMemo(() => {
|
|
return getCountryRuleByName(value);
|
|
}, [value]);
|
|
|
|
// Focus search input when dropdown opens
|
|
useEffect(() => {
|
|
if (isOpen) {
|
|
setTimeout(() => {
|
|
searchInputRef.current?.focus();
|
|
}, 50);
|
|
} else {
|
|
setSearchQuery('');
|
|
}
|
|
}, [isOpen]);
|
|
|
|
// Handle click outside to close dropdown
|
|
useEffect(() => {
|
|
const handleClickOutside = (event: MouseEvent) => {
|
|
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
|
setIsOpen(false);
|
|
}
|
|
};
|
|
|
|
const handleKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') {
|
|
setIsOpen(false);
|
|
}
|
|
};
|
|
|
|
if (isOpen) {
|
|
document.addEventListener('mousedown', handleClickOutside);
|
|
document.addEventListener('keydown', handleKeyDown);
|
|
}
|
|
|
|
return () => {
|
|
document.removeEventListener('mousedown', handleClickOutside);
|
|
document.removeEventListener('keydown', handleKeyDown);
|
|
};
|
|
}, [isOpen]);
|
|
|
|
// Filter countries alphabetically by country name, dial code, or currency
|
|
const filteredCountries = useMemo(() => {
|
|
if (!searchQuery.trim()) {
|
|
return SORTED_COUNTRY_CODES;
|
|
}
|
|
const q = searchQuery.toLowerCase().trim();
|
|
return SORTED_COUNTRY_CODES.filter((c: CountryCode) => {
|
|
const matchName = c.country.toLowerCase().includes(q);
|
|
const matchCode = c.code.toLowerCase().includes(q);
|
|
const matchCurrency = c.currency ? c.currency.toLowerCase().includes(q) : false;
|
|
return matchName || matchCode || matchCurrency;
|
|
});
|
|
}, [searchQuery]);
|
|
|
|
const getCurrencySymbol = (curr: string) => {
|
|
if (curr === 'INR') return '₹';
|
|
if (curr === 'EUR') return '€';
|
|
return '$';
|
|
};
|
|
|
|
const getFlag = (cc: CountryCode) => {
|
|
return cc.label ? cc.label.split(' ')[0] : '🌐';
|
|
};
|
|
|
|
const isDark = theme === 'dark';
|
|
|
|
return (
|
|
<div ref={containerRef} className={`relative w-full ${className}`}>
|
|
{/* Trigger Button */}
|
|
<button
|
|
type="button"
|
|
disabled={disabled}
|
|
onClick={() => !disabled && setIsOpen(!isOpen)}
|
|
className={`w-full flex items-center justify-between text-left transition-colors duration-150 rounded-xl focus:outline-none ${
|
|
size === 'sm' ? 'px-3 py-2 text-xs font-semibold' : 'px-4 py-2.5 text-sm font-semibold'
|
|
} ${
|
|
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' : 'cursor-pointer'}`}
|
|
>
|
|
<div className="flex items-center gap-2 truncate pr-2">
|
|
{selectedRule ? (
|
|
<>
|
|
<span className="text-base shrink-0 leading-none">{getFlag(selectedRule)}</span>
|
|
<span className="truncate">{selectedRule.country}</span>
|
|
{showDialCode && (
|
|
<span className={`text-[11px] font-mono shrink-0 ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
|
|
({selectedRule.code})
|
|
</span>
|
|
)}
|
|
{showCurrency && (
|
|
<span className={`text-[11px] font-normal truncate shrink-0 ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
· {selectedRule.currency} {getCurrencySymbol(selectedRule.currency)}
|
|
</span>
|
|
)}
|
|
</>
|
|
) : (
|
|
<span className={isDark ? 'text-slate-500' : 'text-slate-400'}>{placeholder}</span>
|
|
)}
|
|
</div>
|
|
<ChevronDown
|
|
className={`h-4 w-4 shrink-0 transition-transform duration-200 ${
|
|
isOpen ? 'rotate-180' : ''
|
|
} ${isDark ? 'text-slate-500' : 'text-slate-400'}`}
|
|
/>
|
|
</button>
|
|
|
|
{/* Dropdown Menu */}
|
|
{isOpen && (
|
|
<div
|
|
className={`absolute left-0 right-0 top-full mt-1.5 z-50 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 name 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>
|
|
|
|
{/* Options List */}
|
|
<div className="max-h-56 overflow-y-auto overscroll-contain py-1">
|
|
{filteredCountries.length === 0 ? (
|
|
<div className={`p-4 text-center text-xs ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
No countries found matching “{searchQuery}”
|
|
</div>
|
|
) : (
|
|
filteredCountries.map((c) => {
|
|
const isSelected = c.country.toLowerCase() === value.toLowerCase();
|
|
return (
|
|
<button
|
|
key={`${c.country}-${c.code}`}
|
|
type="button"
|
|
onClick={() => {
|
|
onChange(c.country);
|
|
setIsOpen(false);
|
|
setSearchQuery('');
|
|
}}
|
|
className={`w-full flex items-center justify-between px-3.5 py-2 text-left text-xs transition-colors cursor-pointer ${
|
|
isSelected
|
|
? 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(c)}</span>
|
|
<span className="truncate">{c.country}</span>
|
|
<span className={`text-[10px] font-mono shrink-0 ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
({c.code})
|
|
</span>
|
|
{showCurrency && (
|
|
<span className={`text-[10px] shrink-0 font-normal ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
|
· {c.currency} {getCurrencySymbol(c.currency)}
|
|
</span>
|
|
)}
|
|
</div>
|
|
{isSelected && <Check className="h-3.5 w-3.5 shrink-0 text-indigo-500" />}
|
|
</button>
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|