Skip to content

Commit 53b6c34

Browse files
committed
fix: Allow for region-specific locales in l10n (BL-14005)
1 parent 30b48ee commit 53b6c34

File tree

1 file changed

+46
-11
lines changed
  • components/language-chooser/react/common

1 file changed

+46
-11
lines changed
Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,68 @@
11
import { i18n } from "@lingui/core";
2+
import availableLocales from "../../../../available-locales.json";
23

34
/**
45
* Initialize the i18n instance with the specified locale and messages
5-
* @param locale The locale to activate
6+
* @param locale The locale to activate (can be region-specific like 'es-ES' or base locale like 'es')
67
*/
78
export async function initI18n(locale: string) {
9+
let targetLocale = getBestAvailableLocale(locale);
10+
811
try {
9-
// Dynamic import of the messages.ts file
1012
const { messages } = await import(
11-
`../../../../locales/${locale}/messages.ts`
13+
`../../../../locales/${targetLocale}/messages.ts`
1214
);
1315

1416
if (!messages) {
15-
throw new Error(`No messages found for locale "${locale}"`);
17+
throw new Error(`No messages found for locale "${targetLocale}"`);
1618
}
1719

18-
i18n.load(locale, messages);
19-
i18n.activate(locale);
20+
i18n.load(targetLocale, messages);
21+
i18n.activate(targetLocale);
2022
} catch (error) {
21-
console.error(`Failed to load messages for locale "${locale}":`, error);
22-
23-
// Fallback to English if the requested locale fails to load
24-
if (locale !== "en") {
23+
console.error(
24+
`Failed to load messages for locale "${targetLocale}":`,
25+
error
26+
);
27+
// If even English fails, we'll return i18n without any messages loaded
28+
if (targetLocale !== "en") {
29+
targetLocale = "en";
2530
console.log("Falling back to English locale");
26-
return initI18n("en");
31+
try {
32+
const { messages } = await import(`../../../../locales/en/messages.ts`);
33+
if (messages) {
34+
i18n.load("en", messages);
35+
i18n.activate("en");
36+
}
37+
} catch (fallbackError) {
38+
console.error("Failed to load English messages:", fallbackError);
39+
}
2740
}
2841
}
2942

3043
return i18n;
3144
}
3245

46+
function getBestAvailableLocale(requestedLocale: string) {
47+
// First check if the exact locale is available
48+
if (availableLocales.includes(requestedLocale)) {
49+
return requestedLocale;
50+
}
51+
// Then check if base locale is available
52+
const baseLocale = requestedLocale.split("-")[0];
53+
if (availableLocales.includes(baseLocale)) {
54+
console.log(
55+
`Using base locale "${baseLocale}" for region-specific locale "${requestedLocale}"`
56+
);
57+
return baseLocale;
58+
}
59+
// Finally fall back to English
60+
else {
61+
console.log(
62+
`Locale "${requestedLocale}" not available; falling back to English`
63+
);
64+
return "en";
65+
}
66+
}
67+
3368
export { i18n };

0 commit comments

Comments
 (0)