Skip to content

Commit a5943ad

Browse files
Merge pull request #92 from inventree/locale-fix
Locale loading fix
2 parents 18ff11c + 6d20965 commit a5943ad

1 file changed

Lines changed: 41 additions & 2 deletions

File tree

  • plugin_creator/template/{{ cookiecutter.plugin_name }}/frontend/src

plugin_creator/template/{{ cookiecutter.plugin_name }}/frontend/src/locale.tsx

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,54 @@ import { useEffect, useState } from 'react';
55
import { I18nProvider } from '@lingui/react';
66

77

8+
/**
9+
* Attempt to load the locale file for the given locale, returning null if it fails
10+
*/
11+
async function tryLoadLocale(locale: string): Promise<any> {
12+
try {
13+
const messages = await import(`./locales/${locale}/messages.ts`);
14+
return messages;
15+
} catch (error) {
16+
console.warn(`Failed to load locale ${locale}`);
17+
return null;
18+
}
19+
}
20+
21+
822
/**
923
* Helper function to dynamically load frontend translations,
1024
* based on the provided locale.
1125
*/
1226
async function loadPluginLocale(locale: string) {
13-
const { messages } = await import(`./locales/${locale}/messages.ts`);
14-
27+
28+
let messages = null;
29+
30+
// Find the most specific locale file possible, with fallbacks to less specific locales if necessary
31+
messages = await tryLoadLocale(locale);
32+
33+
if (!messages && locale.includes('-')) {
34+
const fallbackLocale = locale.split('-')[0];
35+
console.debug(`Locale ${locale} not found, trying fallback locale ${fallbackLocale}`);
36+
messages = await tryLoadLocale(fallbackLocale);
37+
}
38+
39+
if (!messages && locale.includes('_')) {
40+
const fallbackLocale = locale.split('_')[0];
41+
console.debug(`Locale ${locale} not found, trying fallback locale ${fallbackLocale}`);
42+
messages = await tryLoadLocale(fallbackLocale);
43+
}
44+
45+
if (!messages && locale !== 'en') {
46+
console.debug(`Locale ${locale} not found, trying fallback locale en`);
47+
messages = await tryLoadLocale('en');
48+
}
49+
50+
if (messages) {
1551
i18n.load(locale, messages);
1652
i18n.activate(locale);
53+
} else {
54+
console.error(`Failed to load any locale for ${locale}`);
55+
}
1756
}
1857

1958

0 commit comments

Comments
 (0)