From f9a77c5c27aede4e5978eb55d9b7af781b680a1d Mon Sep 17 00:00:00 2001 From: João Augusto Costa Branco Marado Torres Date: Tue, 24 Jun 2025 12:08:41 -0300 Subject: feat!: initial commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: João Augusto Costa Branco Marado Torres --- src/utils/lang.ts | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/utils/lang.ts (limited to 'src/utils/lang.ts') 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; + } +} -- cgit v1.2.3