blob: 2ce8fe4301745a33d18faf5a842e01602646d9bb (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
export const LANGUAGE_DEFAULTS = Object.freeze({
pt: "PT",
en: "GB",
fr: "FR",
});
/**
* AI thought me this.
*
* Explanation:
* * Each letter in a 2-letter country code is converted to a Regional
* Indicator Symbol, which together form the emoji flag.
* * 'A'.charCodeAt(0) is 65, and '🇦' starts at 0x1F1E6 → offset of 127397
* (0x1F1A5).
* * So 'A' → '🇦', 'B' → '🇧', etc.
*
* The flags are the combination of those emojis making the country code like
* Portugal -> PT.
*/
export function getFlagEmojiFromLocale(locale: string): string {
let countryCode: string | undefined;
const parts = locale.split("-");
const lang = parts[0].toLowerCase();
if (parts.length === 2) {
countryCode = parts[1].toUpperCase();
} else if (lang in LANGUAGE_DEFAULTS) {
countryCode = LANGUAGE_DEFAULTS[lang as keyof typeof LANGUAGE_DEFAULTS];
}
if (!countryCode) return "";
return [...countryCode]
.map((c) => String.fromCodePoint(c.charCodeAt(0) + 127397))
.join("");
}
export function getLanguageNameFromLocale(locale: string): string {
try {
return new Intl.DisplayNames([locale], {
type: "language",
fallback: "code",
}).of(locale) ?? "";
} catch {
return "";
}
}
export function isValidLocale(locale: string): boolean {
try {
Intl.getCanonicalLocales(locale);
return true;
} catch {
return false;
}
}
|