Browse Source
feat: implement mobile-first shop interface with pages, components, and api integration
main
feat: implement mobile-first shop interface with pages, components, and api integration
main
41 changed files with 2812 additions and 939 deletions
-
2.env
-
139index.html
-
18package-lock.json
-
4package.json
-
11src/components/account/HabibCoinsBanner.tsx
-
1src/components/bridge/HabibBridgeProviders.tsx
-
2src/components/checkout/AddressCard.tsx
-
3src/components/checkout/CartItemCard.tsx
-
2src/components/checkout/PaymentMethodCard.tsx
-
669src/components/common/PhoneNumberInput.tsx
-
1257src/components/common/ShimmerSkeletons.tsx
-
2src/components/layout/BottomNavBar.tsx
-
68src/components/layout/MobileShell.tsx
-
1src/components/layout/TopHeader.tsx
-
67src/components/modals/AddressFormSheet.tsx
-
7src/components/modals/LoginRequiredModal.tsx
-
81src/components/modals/OrderSummarySheet.tsx
-
82src/components/modals/PaymentMethodsSheet.tsx
-
31src/components/modals/ShipmentTrackingSheet.tsx
-
38src/components/orders/OrderFilterTabs.tsx
-
86src/context/ShopAppContext.tsx
-
32src/hooks/use-animated-presence.ts
-
13src/hooks/useSmartBack.ts
-
298src/index.css
-
44src/lib/cookies.ts
-
42src/lib/http.ts
-
403src/lib/phone.ts
-
54src/lib/shopApi.ts
-
21src/pages/account/LanguageSettingPage.tsx
-
134src/pages/account/ProviderRequestPage.tsx
-
7src/pages/account/ShopAccountPage.tsx
-
15src/pages/catalog/ShopSinglePage.tsx
-
3src/pages/chat/ShopChatPage.tsx
-
15src/pages/checkout/ShopBuy01Page.tsx
-
19src/pages/checkout/ShopCartPage.tsx
-
2src/pages/checkout/ShopPayResultPage.tsx
-
1src/pages/checkout/ShopPaymentMethodsPage.tsx
-
67src/pages/checkout/ShopPaymentPage.tsx
-
1src/pages/orders/ShopOrderDetailPage.tsx
-
7src/pages/orders/ShopOrdersPage.tsx
-
2vite.config.ts
@ -1,3 +1,5 @@ |
|||
# Set to true to fall back to mock data when backend responses are empty or offline |
|||
VITE_USE_MOCK_DATA=false |
|||
VITE_BACKEND_ORIGIN=http://127.0.0.1:8000 |
|||
|
|||
|
|||
@ -0,0 +1,669 @@ |
|||
import React, { useEffect, useMemo, useRef, useState } from 'react'; |
|||
import { createPortal } from 'react-dom'; |
|||
import { useAnimatedPresence } from '../../hooks/use-animated-presence'; |
|||
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; |
|||
import { |
|||
getDialCodeForCountryName, |
|||
getPlaceholderForDialCode, |
|||
getSupportedCountryOptions, |
|||
parsePhoneParts, |
|||
resolveRegionFromDialCode, |
|||
validatePhoneNumber, |
|||
} from '../../lib/phone'; |
|||
import { EmptyStateBox } from './ShimmerSkeletons'; |
|||
|
|||
export interface PhoneNumberInputProps { |
|||
id?: string; |
|||
value: string; |
|||
onChange: (nextValue: string, isValid: boolean, e164: string | null) => void; |
|||
countryHint?: string; |
|||
defaultDialCode?: string; |
|||
required?: boolean; |
|||
bare?: boolean; |
|||
height?: number; |
|||
borderRadius?: number; |
|||
backgroundColor?: string; |
|||
borderColor?: string; |
|||
fontSize?: number; |
|||
showError?: boolean; |
|||
errorMessage?: string | null; |
|||
} |
|||
|
|||
export const PhoneNumberInput: React.FC<PhoneNumberInputProps> = ({ |
|||
id, |
|||
value, |
|||
onChange, |
|||
countryHint, |
|||
defaultDialCode = '+1', |
|||
required = true, |
|||
bare = false, |
|||
height = 44, |
|||
borderRadius = 12, |
|||
backgroundColor = '#ffffff', |
|||
borderColor = '#d7dbe2', |
|||
fontSize = 13, |
|||
showError = false, |
|||
errorMessage, |
|||
}) => { |
|||
const resolvedDefaultDial = useMemo( |
|||
() => |
|||
countryHint |
|||
? getDialCodeForCountryName(countryHint, defaultDialCode) |
|||
: defaultDialCode, |
|||
[countryHint, defaultDialCode] |
|||
); |
|||
|
|||
const initialParts = useMemo( |
|||
() => parsePhoneParts(value, resolvedDefaultDial, countryHint), |
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|||
[] |
|||
); |
|||
|
|||
const [dialCode, setDialCode] = useState<string>(initialParts.dialCode); |
|||
const [selectedRegion, setSelectedRegion] = useState<string>( |
|||
initialParts.regionCode |
|||
); |
|||
const [nationalInput, setNationalInput] = useState<string>( |
|||
initialParts.nationalInput |
|||
); |
|||
const [touched, setTouched] = useState(false); |
|||
const [pickerOpen, setPickerOpen] = useState(false); |
|||
const [searchQuery, setSearchQuery] = useState(''); |
|||
const listRef = useRef<HTMLDivElement | null>(null); |
|||
const lastEmittedValueRef = useRef<string>(value); |
|||
const userSelectedCountryRef = useRef<boolean>(false); |
|||
const prevCountryHintRef = useRef<string | undefined>(countryHint); |
|||
|
|||
const { shouldRender: shouldRenderSheet, isClosing: isSheetClosing } = |
|||
useAnimatedPresence(pickerOpen, 200); |
|||
|
|||
const closeSheet = () => { |
|||
setPickerOpen(false); |
|||
setSearchQuery(''); |
|||
}; |
|||
|
|||
useHardwareBackHandler(() => { |
|||
closeSheet(); |
|||
return true; |
|||
}, pickerOpen); |
|||
|
|||
// Sync only when external value changes from outside (e.g. profile loaded or address modal opened)
|
|||
useEffect(() => { |
|||
if (value === lastEmittedValueRef.current) return; |
|||
lastEmittedValueRef.current = value; |
|||
|
|||
if (!value) { |
|||
setNationalInput(''); |
|||
if (!userSelectedCountryRef.current) { |
|||
setDialCode(resolvedDefaultDial); |
|||
setSelectedRegion(resolveRegionFromDialCode(resolvedDefaultDial)); |
|||
} |
|||
return; |
|||
} |
|||
|
|||
const parsed = parsePhoneParts( |
|||
value, |
|||
dialCode || resolvedDefaultDial, |
|||
countryHint |
|||
); |
|||
setDialCode(parsed.dialCode); |
|||
setSelectedRegion(parsed.regionCode); |
|||
setNationalInput(parsed.nationalInput); |
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|||
}, [value]); |
|||
|
|||
// Update dial code only if countryHint prop itself changes and user hasn't picked a code or typed a number
|
|||
useEffect(() => { |
|||
if (countryHint === prevCountryHintRef.current) return; |
|||
prevCountryHintRef.current = countryHint; |
|||
if (!countryHint || userSelectedCountryRef.current || nationalInput.trim()) { |
|||
return; |
|||
} |
|||
const nextDial = getDialCodeForCountryName(countryHint, defaultDialCode); |
|||
setDialCode(nextDial); |
|||
setSelectedRegion(resolveRegionFromDialCode(nextDial)); |
|||
}, [countryHint, defaultDialCode, nationalInput]); |
|||
|
|||
// Ensure list starts scrolled at the top when opened or when search query changes
|
|||
useEffect(() => { |
|||
if (pickerOpen && listRef.current) { |
|||
listRef.current.scrollTop = 0; |
|||
} |
|||
}, [pickerOpen, searchQuery]); |
|||
|
|||
const countries = useMemo(() => getSupportedCountryOptions('en'), []); |
|||
|
|||
const activeCountry = useMemo(() => { |
|||
const bySelectedRegion = countries.find( |
|||
(c) => c.region === selectedRegion && c.dialCode === dialCode |
|||
); |
|||
if (bySelectedRegion) return bySelectedRegion; |
|||
const fallbackRegion = resolveRegionFromDialCode(dialCode); |
|||
return ( |
|||
countries.find((c) => c.region === fallbackRegion) || |
|||
countries.find((c) => c.dialCode === dialCode) || |
|||
null |
|||
); |
|||
}, [countries, dialCode, selectedRegion]); |
|||
|
|||
const filteredCountries = useMemo(() => { |
|||
const q = searchQuery.trim().toLowerCase(); |
|||
if (!q) return countries; |
|||
const digits = q.replace(/\D/g, ''); |
|||
return countries |
|||
.filter( |
|||
(c) => |
|||
c.name.toLowerCase().includes(q) || |
|||
c.region.toLowerCase().includes(q) || |
|||
c.dialCode.includes(q) || |
|||
(digits.length > 0 && c.callingCode.includes(digits)) |
|||
) |
|||
.sort((a, b) => { |
|||
if (digits) { |
|||
const aExact = a.callingCode === digits; |
|||
const bExact = b.callingCode === digits; |
|||
if (aExact && !bExact) return -1; |
|||
if (!aExact && bExact) return 1; |
|||
const aStarts = a.callingCode.startsWith(digits); |
|||
const bStarts = b.callingCode.startsWith(digits); |
|||
if (aStarts && !bStarts) return -1; |
|||
if (!aStarts && bStarts) return 1; |
|||
} |
|||
const aStartsName = a.name.toLowerCase().startsWith(q); |
|||
const bStartsName = b.name.toLowerCase().startsWith(q); |
|||
if (aStartsName && !bStartsName) return -1; |
|||
if (!aStartsName && bStartsName) return 1; |
|||
return a.name.localeCompare(b.name, 'en'); |
|||
}); |
|||
}, [countries, searchQuery]); |
|||
|
|||
const validation = useMemo( |
|||
() => validatePhoneNumber(dialCode, nationalInput, selectedRegion), |
|||
[dialCode, nationalInput, selectedRegion] |
|||
); |
|||
|
|||
const hasError = |
|||
!bare && |
|||
(showError || (touched && nationalInput.trim().length > 0)) && |
|||
!validation.isValid; |
|||
|
|||
const placeholderText = bare |
|||
? 'Phone number' |
|||
: `${getPlaceholderForDialCode(dialCode)}${required ? ' *' : ''}`; |
|||
|
|||
const emitChange = ( |
|||
nextDial: string, |
|||
nextNational: string, |
|||
nextRegion: string |
|||
) => { |
|||
const res = validatePhoneNumber(nextDial, nextNational, nextRegion); |
|||
const combined = nextNational ? `${nextDial} ${nextNational}` : ''; |
|||
lastEmittedValueRef.current = combined; |
|||
onChange(combined, res.isValid, res.e164); |
|||
}; |
|||
|
|||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
|||
const raw = e.target.value; |
|||
if (bare) { |
|||
setNationalInput(raw); |
|||
lastEmittedValueRef.current = raw; |
|||
onChange(raw, true, raw); |
|||
return; |
|||
} |
|||
|
|||
const nextNational = raw.replace(/[^\d]/g, ''); |
|||
setNationalInput(nextNational); |
|||
emitChange(dialCode, nextNational, selectedRegion); |
|||
}; |
|||
|
|||
const handleSelectCountry = (nextDialCode: string, nextRegion: string) => { |
|||
userSelectedCountryRef.current = true; |
|||
setDialCode(nextDialCode); |
|||
setSelectedRegion(nextRegion); |
|||
closeSheet(); |
|||
emitChange(nextDialCode, nationalInput, nextRegion); |
|||
}; |
|||
|
|||
return ( |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}> |
|||
<div |
|||
dir="ltr" |
|||
style={{ |
|||
width: '100%', |
|||
height, |
|||
padding: '0 15px', |
|||
borderRadius, |
|||
backgroundColor, |
|||
border: `1px solid ${hasError ? '#d44747' : borderColor}`, |
|||
boxSizing: 'border-box', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
gap: 8, |
|||
}} |
|||
> |
|||
{bare ? ( |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 400, |
|||
fontSize, |
|||
lineHeight: '20px', |
|||
color: '#292a2e', |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
+23 |
|||
</span> |
|||
) : ( |
|||
<button |
|||
type="button" |
|||
onClick={() => setPickerOpen(true)} |
|||
aria-label="Select country code" |
|||
style={{ |
|||
display: 'inline-flex', |
|||
alignItems: 'center', |
|||
gap: 5, |
|||
background: 'transparent', |
|||
border: 'none', |
|||
padding: 0, |
|||
cursor: 'pointer', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize, |
|||
lineHeight: '20px', |
|||
color: '#292a2e', |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
{activeCountry?.flag && ( |
|||
<span aria-hidden="true" style={{ fontSize: fontSize + 1 }}> |
|||
{activeCountry.flag} |
|||
</span> |
|||
)} |
|||
<span>{dialCode}</span> |
|||
<svg |
|||
aria-hidden="true" |
|||
width="10" |
|||
height="6" |
|||
viewBox="0 0 10 6" |
|||
fill="none" |
|||
style={{ |
|||
flexShrink: 0, |
|||
color: '#73889d', |
|||
transform: pickerOpen ? 'rotate(180deg)' : 'none', |
|||
transition: 'transform 180ms ease', |
|||
}} |
|||
> |
|||
<path |
|||
d="M1 1L5 5L9 1" |
|||
stroke="currentColor" |
|||
strokeWidth="1.5" |
|||
strokeLinecap="round" |
|||
strokeLinejoin="round" |
|||
/> |
|||
</svg> |
|||
</button> |
|||
)} |
|||
|
|||
<div |
|||
style={{ |
|||
width: 1, |
|||
height: 17, |
|||
backgroundColor: '#292a2e', |
|||
flexShrink: 0, |
|||
}} |
|||
/> |
|||
|
|||
<input |
|||
id={id} |
|||
type="tel" |
|||
inputMode="tel" |
|||
required={required} |
|||
className="habib-search-input" |
|||
value={bare ? value : nationalInput} |
|||
maxLength={bare ? undefined : 15} |
|||
onChange={handleInputChange} |
|||
onBlur={() => setTouched(true)} |
|||
placeholder={placeholderText} |
|||
style={{ |
|||
flex: 1, |
|||
minWidth: 0, |
|||
height: '100%', |
|||
border: 'none', |
|||
outline: 'none', |
|||
padding: 0, |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 400, |
|||
fontSize, |
|||
lineHeight: '20px', |
|||
color: '#111111', |
|||
backgroundColor: 'transparent', |
|||
}} |
|||
/> |
|||
</div> |
|||
|
|||
{hasError && ( |
|||
<span |
|||
role="alert" |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize: 11, |
|||
lineHeight: '15px', |
|||
color: '#d44747', |
|||
paddingLeft: 2, |
|||
}} |
|||
> |
|||
{errorMessage || validation.error || 'Enter a valid phone number'} |
|||
</span> |
|||
)} |
|||
|
|||
{shouldRenderSheet && |
|||
!bare && |
|||
typeof document !== 'undefined' && |
|||
createPortal( |
|||
<div |
|||
className={`habib-sheet-backdrop${isSheetClosing ? ' is-closing' : ''}`} |
|||
onClick={closeSheet} |
|||
style={{ |
|||
position: 'fixed', |
|||
inset: 0, |
|||
backgroundColor: 'rgba(17, 17, 17, 0.9)', |
|||
zIndex: 140, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'flex-end', |
|||
}} |
|||
> |
|||
<div |
|||
className={`habib-bottom-sheet${isSheetClosing ? ' is-closing' : ''}`} |
|||
onClick={(e) => e.stopPropagation()} |
|||
style={{ |
|||
height: '78dvh', |
|||
maxHeight: 620, |
|||
backgroundColor: '#f3f1ef', |
|||
padding: |
|||
'22px var(--page-px, 16px) calc(20px + var(--safe-bottom, 0px))', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 14, |
|||
overflow: 'hidden', |
|||
boxSizing: 'border-box', |
|||
}} |
|||
> |
|||
{/* Sheet Header */} |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
gap: 12, |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 15, |
|||
lineHeight: '20px', |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
Select Country Code |
|||
</span> |
|||
<button |
|||
type="button" |
|||
className="habib-icon-btn" |
|||
onClick={closeSheet} |
|||
aria-label="Close country selector" |
|||
style={{ |
|||
width: 24, |
|||
height: 24, |
|||
background: 'transparent', |
|||
border: 'none', |
|||
padding: 0, |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-modal-close-cross.svg" |
|||
alt="" |
|||
style={{ width: 11.67, height: 11.67, display: 'block' }} |
|||
/> |
|||
</button> |
|||
</div> |
|||
|
|||
{/* Search Input matching Habib Shop SearchBar design */} |
|||
<div |
|||
style={{ |
|||
position: 'relative', |
|||
width: '100%', |
|||
height: 50, |
|||
borderRadius: 15, |
|||
backgroundColor: '#ffffff', |
|||
border: '1px solid #e5e2dd', |
|||
boxSizing: 'border-box', |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-search-magnifier.svg" |
|||
alt="Search" |
|||
style={{ |
|||
position: 'absolute', |
|||
left: 9, |
|||
top: 13, |
|||
width: 23.83, |
|||
height: 24, |
|||
pointerEvents: 'none', |
|||
}} |
|||
/> |
|||
<input |
|||
type="search" |
|||
enterKeyHint="search" |
|||
value={searchQuery} |
|||
onChange={(e) => setSearchQuery(e.target.value)} |
|||
className="habib-search-input" |
|||
placeholder="Search country name or code (+1, +98...)" |
|||
aria-label="Search country name or code" |
|||
style={{ |
|||
width: '100%', |
|||
height: '100%', |
|||
borderRadius: 15, |
|||
padding: searchQuery |
|||
? '15px 36px 17px 39px' |
|||
: '15px 12px 17px 39px', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 400, |
|||
fontSize: 12, |
|||
lineHeight: '18px', |
|||
color: '#111111', |
|||
backgroundColor: 'transparent', |
|||
boxSizing: 'border-box', |
|||
}} |
|||
/> |
|||
{searchQuery && ( |
|||
<button |
|||
type="button" |
|||
className="habib-icon-btn" |
|||
onClick={() => setSearchQuery('')} |
|||
aria-label="Clear search" |
|||
style={{ |
|||
position: 'absolute', |
|||
right: 10, |
|||
top: '50%', |
|||
transform: 'translateY(-50%)', |
|||
width: 22, |
|||
height: 22, |
|||
borderRadius: '50%', |
|||
backgroundColor: 'rgba(115, 136, 157, 0.14)', |
|||
border: 'none', |
|||
padding: 0, |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-modal-close-cross.svg" |
|||
alt="" |
|||
style={{ width: 8.5, height: 8.5, display: 'block' }} |
|||
/> |
|||
</button> |
|||
)} |
|||
</div> |
|||
|
|||
{/* Scrollable Country List */} |
|||
<div |
|||
ref={listRef} |
|||
style={{ |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 8, |
|||
overflowY: 'auto', |
|||
overscrollBehavior: 'contain', |
|||
flex: 1, |
|||
minHeight: 0, |
|||
paddingTop: 2, |
|||
paddingBottom: 6, |
|||
}} |
|||
> |
|||
{filteredCountries.length > 0 ? ( |
|||
filteredCountries.map((country) => { |
|||
const selected = |
|||
country.dialCode === dialCode && |
|||
country.region === activeCountry?.region; |
|||
return ( |
|||
<button |
|||
key={`${country.region}-${country.dialCode}`} |
|||
type="button" |
|||
onClick={() => |
|||
handleSelectCountry(country.dialCode, country.region) |
|||
} |
|||
style={{ |
|||
width: '100%', |
|||
minHeight: 52, |
|||
padding: '11px 12px', |
|||
borderRadius: 15, |
|||
background: selected |
|||
? 'linear-gradient(180deg, #fff7e9 0%, #fdf9f4 100%)' |
|||
: '#ffffff', |
|||
border: selected |
|||
? '1px solid #d78e06' |
|||
: '1px solid transparent', |
|||
boxSizing: 'border-box', |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
gap: 12, |
|||
flexShrink: 0, |
|||
textAlign: 'left', |
|||
transition: |
|||
'background-color 180ms ease, border-color 180ms ease', |
|||
}} |
|||
> |
|||
{/* Radio Indicator 20x20 matching AddressCard / PaymentMethodCard */} |
|||
<div |
|||
style={{ |
|||
width: 20, |
|||
height: 20, |
|||
borderRadius: 10, |
|||
backgroundColor: selected ? '#d78e06' : 'transparent', |
|||
border: selected ? undefined : '1px solid #dbdbdb', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
flexShrink: 0, |
|||
transition: |
|||
'background-color 180ms ease, border-color 180ms ease', |
|||
}} |
|||
> |
|||
{selected && ( |
|||
<div |
|||
className="habib-radio-dot" |
|||
style={{ |
|||
width: 8, |
|||
height: 8, |
|||
borderRadius: '50%', |
|||
backgroundColor: '#ffffff', |
|||
}} |
|||
/> |
|||
)} |
|||
</div> |
|||
|
|||
{/* Flag Badge */} |
|||
<div |
|||
style={{ |
|||
width: 30, |
|||
height: 30, |
|||
borderRadius: 9, |
|||
backgroundColor: selected |
|||
? 'rgba(215, 142, 6, 0.14)' |
|||
: 'rgba(208, 208, 208, 0.25)', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
fontSize: 16, |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
{country.flag} |
|||
</div> |
|||
|
|||
{/* Country Name */} |
|||
<span |
|||
style={{ |
|||
flex: 1, |
|||
minWidth: 0, |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 13, |
|||
lineHeight: '18px', |
|||
color: '#292a2e', |
|||
overflow: 'hidden', |
|||
textOverflow: 'ellipsis', |
|||
whiteSpace: 'nowrap', |
|||
}} |
|||
> |
|||
{country.name} |
|||
</span> |
|||
|
|||
{/* Dial Code Pill */} |
|||
<span |
|||
dir="ltr" |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 12, |
|||
lineHeight: '17px', |
|||
color: selected ? '#d78e06' : '#73889d', |
|||
backgroundColor: selected |
|||
? 'rgba(215, 142, 6, 0.12)' |
|||
: '#f3f1ef', |
|||
padding: '3px 8px', |
|||
borderRadius: 8, |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
{country.dialCode} |
|||
</span> |
|||
</button> |
|||
); |
|||
}) |
|||
) : ( |
|||
<EmptyStateBox message="No countries found." compact /> |
|||
)} |
|||
</div> |
|||
</div> |
|||
</div>, |
|||
document.body |
|||
)} |
|||
</div> |
|||
); |
|||
}; |
|||
1257
src/components/common/ShimmerSkeletons.tsx
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
@ -0,0 +1,32 @@ |
|||
import { useEffect, useState } from 'react'; |
|||
|
|||
/** |
|||
* Keeps a modal or sheet mounted briefly after `isOpen` turns false so CSS |
|||
* exit animations (slide-down / fade-out) can finish before unmounting. |
|||
*/ |
|||
export function useAnimatedPresence( |
|||
isOpen: boolean, |
|||
exitDurationMs = 200 |
|||
): { |
|||
shouldRender: boolean; |
|||
isClosing: boolean; |
|||
} { |
|||
const [rendered, setRendered] = useState(isOpen); |
|||
|
|||
useEffect(() => { |
|||
if (isOpen) { |
|||
setRendered(true); |
|||
return; |
|||
} |
|||
if (!rendered) return; |
|||
const timer = window.setTimeout(() => { |
|||
setRendered(false); |
|||
}, exitDurationMs); |
|||
return () => window.clearTimeout(timer); |
|||
}, [isOpen, rendered, exitDurationMs]); |
|||
|
|||
return { |
|||
shouldRender: isOpen || rendered, |
|||
isClosing: !isOpen && rendered, |
|||
}; |
|||
} |
|||
@ -0,0 +1,403 @@ |
|||
import libphonenumber from 'google-libphonenumber'; |
|||
|
|||
const { |
|||
PhoneNumberUtil, |
|||
PhoneNumberFormat, |
|||
PhoneNumberType, |
|||
} = libphonenumber; |
|||
|
|||
const phoneUtil = PhoneNumberUtil.getInstance(); |
|||
|
|||
export interface CountryPhoneOption { |
|||
region: string; |
|||
name: string; |
|||
callingCode: string; |
|||
dialCode: string; |
|||
flag: string; |
|||
} |
|||
|
|||
export interface PhoneValidationResult { |
|||
isValid: boolean; |
|||
e164: string | null; |
|||
international: string | null; |
|||
national: string | null; |
|||
regionCode: string | null; |
|||
error: string | null; |
|||
} |
|||
|
|||
const PRIMARY_REGION_BY_CALLING_CODE: Record<string, string> = { |
|||
'1': 'US', |
|||
'7': 'RU', |
|||
'39': 'IT', |
|||
'44': 'GB', |
|||
'61': 'AU', |
|||
'90': 'TR', |
|||
'92': 'PK', |
|||
'93': 'AF', |
|||
'98': 'IR', |
|||
'961': 'LB', |
|||
'964': 'IQ', |
|||
'965': 'KW', |
|||
'966': 'SA', |
|||
'968': 'OM', |
|||
'971': 'AE', |
|||
'973': 'BH', |
|||
'974': 'QA', |
|||
}; |
|||
|
|||
const COUNTRY_NAME_ALIASES: Record<string, string> = { |
|||
'united states': 'US', |
|||
'united states of america': 'US', |
|||
usa: 'US', |
|||
us: 'US', |
|||
america: 'US', |
|||
'united kingdom': 'GB', |
|||
uk: 'GB', |
|||
britain: 'GB', |
|||
england: 'GB', |
|||
iran: 'IR', |
|||
'islamic republic of iran': 'IR', |
|||
iraq: 'IQ', |
|||
lebanon: 'LB', |
|||
syria: 'SY', |
|||
'saudi arabia': 'SA', |
|||
'united arab emirates': 'AE', |
|||
uae: 'AE', |
|||
kuwait: 'KW', |
|||
bahrain: 'BH', |
|||
qatar: 'QA', |
|||
oman: 'OM', |
|||
pakistan: 'PK', |
|||
afghanistan: 'AF', |
|||
india: 'IN', |
|||
turkey: 'TR', |
|||
turkiye: 'TR', |
|||
germany: 'DE', |
|||
france: 'FR', |
|||
canada: 'CA', |
|||
australia: 'AU', |
|||
}; |
|||
|
|||
let cachedCountryOptions: CountryPhoneOption[] | null = null; |
|||
|
|||
function regionToFlag(region: string): string { |
|||
const codePoints = region |
|||
.toUpperCase() |
|||
.split('') |
|||
.map((char) => 127397 + char.charCodeAt(0)); |
|||
return String.fromCodePoint(...codePoints); |
|||
} |
|||
|
|||
export function getSupportedCountryOptions(locale = 'en'): CountryPhoneOption[] { |
|||
if (cachedCountryOptions && locale === 'en') { |
|||
return cachedCountryOptions; |
|||
} |
|||
|
|||
const regions = phoneUtil.getSupportedRegions(); |
|||
const displayNames = |
|||
typeof Intl !== 'undefined' && typeof Intl.DisplayNames === 'function' |
|||
? new Intl.DisplayNames([locale, 'en'], { type: 'region' }) |
|||
: null; |
|||
|
|||
const list: CountryPhoneOption[] = []; |
|||
for (const region of regions) { |
|||
try { |
|||
const callingCodeNum = phoneUtil.getCountryCodeForRegion(region); |
|||
if (!callingCodeNum) continue; |
|||
const callingCode = String(callingCodeNum); |
|||
const name = displayNames?.of(region) || region; |
|||
list.push({ |
|||
region, |
|||
name, |
|||
callingCode, |
|||
dialCode: `+${callingCode}`, |
|||
flag: regionToFlag(region), |
|||
}); |
|||
} catch { |
|||
// ignore unsupported region
|
|||
} |
|||
} |
|||
|
|||
list.sort((a, b) => a.name.localeCompare(b.name, locale)); |
|||
if (locale === 'en') { |
|||
cachedCountryOptions = list; |
|||
} |
|||
return list; |
|||
} |
|||
|
|||
export function resolveRegionFromDialCode(dialCode: string): string { |
|||
const cleanCode = dialCode.replace(/[^\d]/g, ''); |
|||
if (!cleanCode) return 'US'; |
|||
if (PRIMARY_REGION_BY_CALLING_CODE[cleanCode]) { |
|||
return PRIMARY_REGION_BY_CALLING_CODE[cleanCode]; |
|||
} |
|||
try { |
|||
const region = phoneUtil.getRegionCodeForCountryCode(Number(cleanCode)); |
|||
return region && region !== 'ZZ' ? region : 'US'; |
|||
} catch { |
|||
return 'US'; |
|||
} |
|||
} |
|||
|
|||
export function resolveRegionFromCountryName( |
|||
countryName?: string | null |
|||
): string | null { |
|||
if (!countryName) return null; |
|||
const trimmed = countryName.trim(); |
|||
if (!trimmed) return null; |
|||
|
|||
const upper = trimmed.toUpperCase(); |
|||
const supported = phoneUtil.getSupportedRegions(); |
|||
if (upper.length === 2 && supported.includes(upper as never)) { |
|||
return upper; |
|||
} |
|||
|
|||
const lower = trimmed.toLowerCase(); |
|||
if (COUNTRY_NAME_ALIASES[lower]) { |
|||
return COUNTRY_NAME_ALIASES[lower]; |
|||
} |
|||
|
|||
const options = getSupportedCountryOptions('en'); |
|||
const exact = options.find((opt) => opt.name.toLowerCase() === lower); |
|||
if (exact) return exact.region; |
|||
|
|||
const partial = options.find( |
|||
(opt) => |
|||
opt.name.toLowerCase().includes(lower) || |
|||
lower.includes(opt.name.toLowerCase()) |
|||
); |
|||
return partial ? partial.region : null; |
|||
} |
|||
|
|||
export function getDialCodeForCountryName( |
|||
countryName?: string | null, |
|||
fallback = '+1' |
|||
): string { |
|||
const region = resolveRegionFromCountryName(countryName); |
|||
if (!region) return fallback; |
|||
try { |
|||
const code = phoneUtil.getCountryCodeForRegion(region); |
|||
return code ? `+${code}` : fallback; |
|||
} catch { |
|||
return fallback; |
|||
} |
|||
} |
|||
|
|||
export function sanitizeDialCode(value: string, fallback = '+1'): string { |
|||
const digits = value.replace(/[^\d]/g, ''); |
|||
return digits ? `+${digits}` : fallback; |
|||
} |
|||
|
|||
export function getPlaceholderForDialCode(dialCode: string): string { |
|||
try { |
|||
const cleanCode = dialCode.replace(/[^\d]/g, ''); |
|||
if (!cleanCode) return 'Phone number'; |
|||
if (cleanCode === '98') return '9123456789'; |
|||
|
|||
const region = resolveRegionFromDialCode(cleanCode); |
|||
const example = |
|||
phoneUtil.getExampleNumberForType(region, PhoneNumberType.MOBILE) || |
|||
phoneUtil.getExampleNumber(region); |
|||
|
|||
if (!example) return 'Phone number'; |
|||
return String(example.getNationalNumberOrDefault()); |
|||
} catch { |
|||
return 'Phone number'; |
|||
} |
|||
} |
|||
|
|||
export function parsePhoneParts( |
|||
rawPhone?: string | null, |
|||
fallbackDialCode = '+1', |
|||
countryHint?: string | null |
|||
): { dialCode: string; nationalInput: string; regionCode: string } { |
|||
const defaultDial = fallbackDialCode |
|||
? sanitizeDialCode(fallbackDialCode) |
|||
: countryHint |
|||
? getDialCodeForCountryName(countryHint, '+1') |
|||
: '+1'; |
|||
const defaultRegion = resolveRegionFromDialCode(defaultDial); |
|||
|
|||
if (!rawPhone || !rawPhone.trim()) { |
|||
return { |
|||
dialCode: defaultDial, |
|||
nationalInput: '', |
|||
regionCode: defaultRegion, |
|||
}; |
|||
} |
|||
|
|||
const trimmed = rawPhone.trim(); |
|||
|
|||
// 1. If stored as "<+dialCode>" or "<+dialCode> <nationalBody>", split directly without altering the body
|
|||
const splitMatch = trimmed.match(/^\+(\d{1,4})(?:\s+(.*))?$/); |
|||
if (splitMatch) { |
|||
const dialCode = `+${splitMatch[1]}`; |
|||
const nationalInput = (splitMatch[2] || '').replace(/[^\d]/g, ''); |
|||
return { |
|||
dialCode, |
|||
nationalInput, |
|||
regionCode: resolveRegionFromDialCode(dialCode), |
|||
}; |
|||
} |
|||
|
|||
// 2. If compact international E.164 (e.g. "+989102036523" from backend API), extract code + national digits
|
|||
if (trimmed.startsWith('+')) { |
|||
try { |
|||
const parsed = phoneUtil.parse(trimmed); |
|||
const cc = parsed.getCountryCode(); |
|||
const nat = parsed.getNationalNumber(); |
|||
if (cc && nat !== undefined) { |
|||
const dialCode = `+${cc}`; |
|||
const regionCode = |
|||
phoneUtil.getRegionCodeForNumber(parsed) || |
|||
resolveRegionFromDialCode(dialCode); |
|||
return { |
|||
dialCode, |
|||
nationalInput: String(nat), |
|||
regionCode, |
|||
}; |
|||
} |
|||
} catch { |
|||
const compactDigits = trimmed.slice(1).replace(/[^\d]/g, ''); |
|||
for (let len = 1; len <= 3 && len <= compactDigits.length; len += 1) { |
|||
const candidateCode = compactDigits.slice(0, len); |
|||
const region = phoneUtil.getRegionCodeForCountryCode( |
|||
Number(candidateCode) |
|||
); |
|||
if (region && region !== 'ZZ') { |
|||
const dialCode = `+${candidateCode}`; |
|||
return { |
|||
dialCode, |
|||
nationalInput: compactDigits.slice(len), |
|||
regionCode: resolveRegionFromDialCode(dialCode), |
|||
}; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
// 3. Plain national number (e.g. "09102036523") — keep body digits intact
|
|||
const digitsOnly = trimmed.replace(/[^\d]/g, ''); |
|||
if (digitsOnly.length === 11 && digitsOnly.startsWith('09')) { |
|||
return { |
|||
dialCode: '+98', |
|||
nationalInput: digitsOnly, |
|||
regionCode: 'IR', |
|||
}; |
|||
} |
|||
|
|||
return { |
|||
dialCode: defaultDial, |
|||
nationalInput: digitsOnly, |
|||
regionCode: defaultRegion, |
|||
}; |
|||
} |
|||
|
|||
export function validatePhoneNumber( |
|||
dialCode: string, |
|||
nationalInput: string, |
|||
regionOverride?: string | null |
|||
): PhoneValidationResult { |
|||
const cleanCode = sanitizeDialCode(dialCode, '+1'); |
|||
const digits = nationalInput.replace(/[^\d]/g, ''); |
|||
|
|||
if (!digits) { |
|||
return { |
|||
isValid: false, |
|||
e164: null, |
|||
international: null, |
|||
national: null, |
|||
regionCode: null, |
|||
error: 'Phone number is required', |
|||
}; |
|||
} |
|||
|
|||
const cleanCodeDigits = cleanCode.replace(/[^\d]/g, ''); |
|||
const region = |
|||
(regionOverride && regionOverride.length === 2 |
|||
? regionOverride.toUpperCase() |
|||
: null) || resolveRegionFromDialCode(cleanCode); |
|||
|
|||
// Strip leading trunk 0 only for libphonenumber parsing (except Italy +39)
|
|||
const nationalForParse = |
|||
cleanCodeDigits !== '39' && digits.startsWith('0') |
|||
? digits.replace(/^0+/, '') |
|||
: digits; |
|||
|
|||
if (!nationalForParse) { |
|||
return { |
|||
isValid: false, |
|||
e164: null, |
|||
international: null, |
|||
national: null, |
|||
regionCode: null, |
|||
error: 'Enter a valid phone number for the selected country code', |
|||
}; |
|||
} |
|||
|
|||
try { |
|||
const parsed = phoneUtil.parse(`${cleanCode}${nationalForParse}`, region); |
|||
if ( |
|||
String(parsed.getCountryCode()) !== cleanCodeDigits || |
|||
!phoneUtil.isPossibleNumber(parsed) || |
|||
!phoneUtil.isValidNumber(parsed) |
|||
) { |
|||
return { |
|||
isValid: false, |
|||
e164: null, |
|||
international: null, |
|||
national: null, |
|||
regionCode: null, |
|||
error: 'Enter a valid phone number for the selected country code', |
|||
}; |
|||
} |
|||
|
|||
return { |
|||
isValid: true, |
|||
e164: phoneUtil.format(parsed, PhoneNumberFormat.E164), |
|||
international: phoneUtil.format(parsed, PhoneNumberFormat.INTERNATIONAL), |
|||
national: phoneUtil.format(parsed, PhoneNumberFormat.NATIONAL), |
|||
regionCode: phoneUtil.getRegionCodeForNumber(parsed) || region, |
|||
error: null, |
|||
}; |
|||
} catch { |
|||
return { |
|||
isValid: false, |
|||
e164: null, |
|||
international: null, |
|||
national: null, |
|||
regionCode: null, |
|||
error: 'Enter a valid phone number with country code', |
|||
}; |
|||
} |
|||
} |
|||
|
|||
export function isValidPhoneString( |
|||
rawPhone?: string | null, |
|||
countryHint?: string | null |
|||
): boolean { |
|||
if (!rawPhone || !rawPhone.trim()) return false; |
|||
const defaultDial = countryHint |
|||
? getDialCodeForCountryName(countryHint, '+1') |
|||
: '+1'; |
|||
const parts = parsePhoneParts(rawPhone, defaultDial, countryHint); |
|||
return validatePhoneNumber(parts.dialCode, parts.nationalInput, parts.regionCode) |
|||
.isValid; |
|||
} |
|||
|
|||
export function formatPhoneForDisplay( |
|||
rawPhone?: string | null, |
|||
countryHint?: string | null |
|||
): string { |
|||
if (!rawPhone || !rawPhone.trim()) return ''; |
|||
const defaultDial = countryHint |
|||
? getDialCodeForCountryName(countryHint, '+1') |
|||
: '+1'; |
|||
const parts = parsePhoneParts(rawPhone, defaultDial, countryHint); |
|||
const validated = validatePhoneNumber( |
|||
parts.dialCode, |
|||
parts.nationalInput, |
|||
parts.regionCode |
|||
); |
|||
return validated.international || rawPhone.trim(); |
|||
} |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue