diff options
author | João Augusto Costa Branco Marado Torres <torres.dev@disroot.org> | 2025-06-24 12:08:41 -0300 |
---|---|---|
committer | João Augusto Costa Branco Marado Torres <torres.dev@disroot.org> | 2025-06-24 12:50:43 -0300 |
commit | f9a77c5c27aede4e5978eb55d9b7af781b680a1d (patch) | |
tree | d545e325ba1ae756fc2eac66fac1001b6753c40d /src/utils/lang.ts |
feat!: initial commit
Signed-off-by: João Augusto Costa Branco Marado Torres <torres.dev@disroot.org>
Diffstat (limited to 'src/utils/lang.ts')
-rw-r--r-- | src/utils/lang.ts | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/src/utils/lang.ts b/src/utils/lang.ts new file mode 100644 index 0000000..2ce8fe4 --- /dev/null +++ b/src/utils/lang.ts @@ -0,0 +1,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; + } +} |