| 1 |
/** |
| 2 |
* Phone helpers for admin displays. Reads the localized `window.yatraPhoneData` |
| 3 |
* (countries + dial-code priority + flag base URL) to turn a stored |
| 4 |
* "+<code><number>" value into a flag + readable number. Mirrors the server-side |
| 5 |
* FormatHelper detection so front and back agree. |
| 6 |
* |
| 7 |
* A value with no leading "+" (a legacy national-only number) is returned as-is |
| 8 |
* with no flag — never reinterpreted. |
| 9 |
*/ |
| 10 |
|
| 11 |
export interface PhoneCountry { |
| 12 |
iso: string; |
| 13 |
name: string; |
| 14 |
dial: string; |
| 15 |
} |
| 16 |
|
| 17 |
interface PhoneData { |
| 18 |
countries?: PhoneCountry[]; |
| 19 |
priority?: Record<string, string>; |
| 20 |
flagBase?: string; |
| 21 |
} |
| 22 |
|
| 23 |
function phoneData(): PhoneData { |
| 24 |
return ( |
| 25 |
(window as unknown as { yatraPhoneData?: PhoneData }).yatraPhoneData || {} |
| 26 |
); |
| 27 |
} |
| 28 |
|
| 29 |
export interface DetectedPhone { |
| 30 |
iso: string; |
| 31 |
dial: string; |
| 32 |
national: string; |
| 33 |
} |
| 34 |
|
| 35 |
/** Detect country from a value beginning with "+". Longest-prefix match, then priority tiebreak. */ |
| 36 |
export function detectPhoneCountry(raw: string): DetectedPhone | null { |
| 37 |
raw = (raw || "").trim(); |
| 38 |
if (!raw || raw.charAt(0) !== "+") return null; |
| 39 |
const digits = raw.replace(/\D+/g, ""); |
| 40 |
if (!digits) return null; |
| 41 |
const countries = phoneData().countries || []; |
| 42 |
const priority = phoneData().priority || {}; |
| 43 |
for (let len = Math.min(4, digits.length); len >= 1; len--) { |
| 44 |
const prefix = digits.slice(0, len); |
| 45 |
const matches = countries.filter((c) => c.dial === prefix); |
| 46 |
if (matches.length) { |
| 47 |
const iso = priority[prefix] || matches[0].iso; |
| 48 |
return { iso, dial: prefix, national: digits.slice(len) }; |
| 49 |
} |
| 50 |
} |
| 51 |
return null; |
| 52 |
} |
| 53 |
|
| 54 |
/** URL of a country's flag SVG, or "" if the flag base isn't localized. */ |
| 55 |
export function flagUrl(iso: string): string { |
| 56 |
const base = phoneData().flagBase || ""; |
| 57 |
return base ? `${base}${String(iso).toLowerCase()}.svg` : ""; |
| 58 |
} |
| 59 |
|
| 60 |
/** Human-readable form: "+977 9806015400" for international, unchanged for legacy. */ |
| 61 |
export function formatPhone(raw: string): string { |
| 62 |
const d = detectPhoneCountry(raw); |
| 63 |
if (!d) return raw; |
| 64 |
return `+${d.dial}${d.national ? " " + d.national : ""}`; |
| 65 |
} |
| 66 |
|