Created
April 24, 2019 19:21
-
-
Save quarrant/5d1a7fc156daadd4fdbe03b32ed05978 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { observable, action, computed } from 'mobx'; | |
import { Platform, NativeModules } from 'react-native'; | |
import replace from 'lodash/replace'; | |
enum Locales { | |
ru = 'ru', | |
en = 'en' | |
} | |
type TLocale = keyof typeof Locales; | |
type TLocales = { [key in TLocale]: string }; | |
type TDictionary = { [key: string]: TLocales }; | |
class Localization { | |
@observable private _locale: TLocale; | |
@observable private dictionary: TDictionary; | |
constructor(dictionary: TDictionary, locale?: TLocale | undefined) { | |
this._locale = this.processDefaultLocale(locale); | |
this.dictionary = dictionary; | |
} | |
private processDefaultLocale(locale: TLocale | undefined) { | |
if (locale) return locale; | |
return Platform.select({ | |
ios: NativeModules.SettingsManager.settings.AppleLocale, | |
android: NativeModules.I18nManager.localeIdentifier | |
}).substring(0, 2); | |
} | |
@computed get locale() { | |
return this._locale; | |
} | |
@action switch(locale: TLocale | undefined) { | |
this._locale = this.processDefaultLocale(locale); | |
} | |
translate(text: string, params: Record<string, any> = {}) { | |
if ( | |
this.dictionary && | |
this.dictionary[text] && | |
this.dictionary[text][this._locale] | |
) { | |
return Object.keys(params).reduce((acc: string, param) => { | |
return replace(acc, new RegExp(`{${param}}`, 'g'), params[param]); | |
}, this.dictionary[text][this._locale]); | |
} | |
return text; | |
} | |
} | |
export default new Localization({ | |
"someText": { | |
"ru": "Какой-то текст", | |
"en": "Some text" | |
} | |
}); |
Author
quarrant
commented
Apr 24, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment