-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlocale.tsx
More file actions
89 lines (72 loc) · 2.22 KB
/
locale.tsx
File metadata and controls
89 lines (72 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { i18n } from '@lingui/core';
import { Skeleton } from '@mantine/core';
import { useEffect, useState } from 'react';
import { I18nProvider } from '@lingui/react';
/**
* Attempt to load the locale file for the given locale, returning null if it fails
*/
async function tryLoadLocale(locale: string): Promise<any> {
try {
const messages = await import(`./locales/${locale}/messages.ts`);
return messages;
} catch (error) {
console.warn(`Failed to load locale ${locale}`);
return null;
}
}
/**
* Helper function to dynamically load frontend translations,
* based on the provided locale.
*/
async function loadPluginLocale(locale: string) {
let messages = null;
// Find the most specific locale file possible, with fallbacks to less specific locales if necessary
messages = await tryLoadLocale(locale);
if (!messages && locale.includes('-')) {
const fallbackLocale = locale.split('-')[0];
console.debug(`Locale ${locale} not found, trying fallback locale ${fallbackLocale}`);
messages = await tryLoadLocale(fallbackLocale);
}
if (!messages && locale.includes('_')) {
const fallbackLocale = locale.split('_')[0];
console.debug(`Locale ${locale} not found, trying fallback locale ${fallbackLocale}`);
messages = await tryLoadLocale(fallbackLocale);
}
if (!messages && locale !== 'en') {
console.debug(`Locale ${locale} not found, trying fallback locale en`);
messages = await tryLoadLocale('en');
}
if (messages) {
i18n.load(locale, messages);
i18n.activate(locale);
} else {
console.error(`Failed to load any locale for ${locale}`);
}
}
// Wrapper component for loading dynamic translations
export function LocalizedComponent({
locale,
children
}: {
locale: string,
children: React.ReactNode
}) {
const [loaded, setLoaded] = useState(false);
// Reload componentwhen the locale changes
useEffect(() => {
setLoaded(false);
loadPluginLocale(locale).then(() => {
setLoaded(true);
});
}, [locale]);
if (!loaded) {
return (
<Skeleton w='100%' animate />
);
}
return (
<I18nProvider i18n={i18n}>
{children}
</I18nProvider>
);
}