MCPcopy Create free account
hub / github.com/reactnativecn/react-native-update / I18n

Class I18n

src/i18n.ts:7–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5type TranslationValues = Record<string, string | number>;
6
7class I18n {
8 private currentLocale: 'zh' | 'en' = 'en';
9 private translations = {
10 zh: zhTranslations,
11 en: enTranslations,
12 };
13
14 /**
15 * Set locale directly
16 * @param locale - 'zh' or 'en'
17 */
18 setLocale(locale: 'zh' | 'en') {
19 this.currentLocale = locale;
20 }
21
22 /**
23 * Get current locale
24 */
25 getLocale(): 'zh' | 'en' {
26 return this.currentLocale;
27 }
28
29 /**
30 * Translate a key with optional interpolation
31 * @param key - Translation key
32 * @param values - Values for interpolation (optional)
33 * @returns Translated string with interpolated values
34 */
35 t(key: TranslationKey, values?: TranslationValues): string {
36 const translation =
37 this.translations[this.currentLocale][
38 key as keyof (typeof this.translations)[typeof this.currentLocale]
39 ];
40
41 if (!translation) {
42 // Fallback to the other locale if key not found
43 const fallbackLocale = this.currentLocale === 'zh' ? 'en' : 'zh';
44 const fallbackTranslation =
45 this.translations[fallbackLocale][
46 key as keyof (typeof this.translations)[typeof fallbackLocale]
47 ];
48
49 if (!fallbackTranslation) {
50 // If still not found, return the key itself
51 return String(key);
52 }
53
54 return this.interpolate(fallbackTranslation, values);
55 }
56
57 return this.interpolate(translation, values);
58 }
59
60 /**
61 * Interpolate values into a string template
62 * Supports {{key}} syntax
63 * @param template - String template with {{key}} placeholders
64 * @param values - Values to interpolate

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected