Repository navigation
Expand file tree
/
Copy pathLocalization.js
More file actions
89 lines (63 loc) · 2.25 KB
/
Copy pathLocalization.js
File metadata and controls
89 lines (63 loc) · 2.25 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 memoize from 'lodash.memoize'; // Use for caching/memoize for better performance
import { I18n } from "i18n-js";
import { I18nManager } from 'react-native';
import { getLocales } from 'expo-localization';
// make object
export const translator = new I18n();
// translate is helper function to get the word with the current language
export const translate = memoize(
// including missing names
(key, config) => translator.t(key, config).includes('missing') ? key : translator.t(key, config),
// cache
(key, config) => (config ? key + JSON.stringify(config) : key),
);
// to ge the tranlation
const translationGetters = {
// lazy requires (metro bundler does not support symlinks)
en: () => require('./assets/locales/en.json'),
};
// set the default language if the default language of the device isn't exist
const fallback = {
languageCode: 'en',
textDirection: 'ltr'
};
// check if the text direction is RTL
const isRTL = (textDirection) => {
return textDirection === 'rtl';
};
// set the language
export const init = () => {
// default language
let { languageCode, textDirection } = getLocales()[0] || fallback;
// set the default language
changeLanguage(languageCode, textDirection);
};
// get the current language
export const getLanguage = () => {
return translator.locale;
}
// get the current text direction
export const getTextDirection = () => {
return I18nManager.isRTL ? 'rtl' : 'ltr';
}
// change the current language
export const changeLanguage = (languageCode, textDirection) => {
// set the default language if the default language of the device isn't exist
const fallback = { languageCode: 'en', textDirection: 'ltr' };
// check if the language exist
if(!translationGetters[languageCode]){
// set the default language
languageCode = fallback.languageCode;
textDirection = fallback.textDirection;
}
// clear translation cache
translate.cache.clear();
// update layout direction
I18nManager.forceRTL(isRTL(textDirection));
I18nManager.allowRTL(isRTL(textDirection));
// set i18n-js config
translator.translations = {
[languageCode]: translationGetters[languageCode](),
};
translator.locale = languageCode;
}