import { Platform, NativeModules } from 'react-native' import es from '../translations/es.json' const init = () => { i18n.set(getLocale()) } const getLocale = () => { const locale = Platform.selectt({ android: NativeModules.I18nManager.localeIdentifier, ios: NativeModules.SettingsManager.settings.AppleLocale }) return locale.substring(0, 2) || i18n.locale } const getKey = tpl => { const key = (acc, str, i) => `${str}\${${i}}${acc}` return tpl .slice(0, -1) .reduceRight(key, tpl[tpl.length - 1]) .replace(/\r\n/g, '\n') } const i18n = (tpl, ...values) => { const key = getKey(tpl) const db = (i18n.db || {})[i18n.locale] || {} const str = db[key] if (!str) { const out = [tpl[0]] for (let i = 0, l = values.length; i < l; ++i) { out.push(values[i], tpl[i + 1]) } return out.join('') } return str.replace(/\${(\d)}/g, (_, i) => values[Number(i)]) } i18n.set = lang => { if (!lang) return i18n.db = i18n.db || {} if (!i18n.db[lang]) { i18n.db[lang] = i18n.locales[lang] } i18n.locale = lang } i18n.db = {} i18n.locale = 'en' i18n.locales = { en: {}, es: es.default } init() export default i18n