Skip to content

Commit

Permalink
fix: 🐛 Add fallback for full locales (#2961)
Browse files Browse the repository at this point in the history
Added a safety check at the end of the getLng function. This check verifies if translations exist for the language portion of a locale (e.g., 'en' from 'en-US') when the full locale isn't found in the resources object. This prevents errors when translations exist for a base language but not for a specific regional variant.
  • Loading branch information
rique223 authored Nov 12, 2024
1 parent ba14487 commit 4b4640a
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/i18n/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,28 @@ const getLng = async (): Promise<keyof typeof resources | undefined> => {

const locale = app.getSystemLocale();

let [languageCode, countryCode] = locale.split(/[-_]/) as [
string,
string | null,
];
let [languageCode, countryCode] = locale.split(/[-_]/);
if (!languageCode || languageCode.length !== 2) {
return fallbackLng;
}

languageCode = languageCode.toLowerCase();

if (!countryCode || countryCode.length !== 2) {
countryCode = null;
} else {
countryCode = countryCode.toUpperCase();
}
const isCountryCodeInexistentOrNonStandard =
!countryCode || countryCode.length !== 2;
countryCode = isCountryCodeInexistentOrNonStandard
? ''
: countryCode.toUpperCase();

const lng = countryCode ? `${languageCode}-${countryCode}` : languageCode;

if (hasLng(lng)) {
return lng;
}

return undefined;
return Object.keys(resources).find((language) =>
language.startsWith(languageCode)
) as keyof typeof resources | undefined;
};

export let getLanguage = 'en';
Expand Down

0 comments on commit 4b4640a

Please sign in to comment.