@re-flex/i18n
Version:
Re-flex UI Lozalization Package
83 lines (82 loc) • 2.8 kB
JavaScript
import ObjectPath from "@re-flex/object-path";
class I18nCore {
updater;
httpConfig;
browserLanguage = (navigator.languages && navigator.languages[0]) || navigator.language;
initialLanguage = "en";
currentLanguage = "en";
resources = new ObjectPath({});
languages;
namespaces;
constructor() {
this.currentLanguage = "en";
this.initialLanguage = "en";
}
httpBackendAdapter() {
if (!!this.httpConfig) {
const pathMapper = this.namespaces.map((namespace) => {
let rObject = {
lng: this.currentLanguage,
ns: namespace,
};
return {
namespace,
path: this.httpConfig.path.replace(/{{\s*\w+\s*}}/gim, (t) => {
let key = t.replace(/{{\s*|\s*}}/gim, "");
return rObject[key];
}),
};
});
Promise.all(pathMapper.map(({ namespace, path }) => fetch(path, { headers: this.httpConfig?.headers })
.then((r) => {
return r.json();
})
.then((result) => ({ [namespace]: result })))).then((namespaces) => {
this.resources = new ObjectPath(Object.assign({}, ...namespaces));
if (this.updater)
this.updater();
});
}
else {
console.warn("HTTP config is not assigned");
}
}
init(config) {
const { initialLanguage, httpConfig, resources, languages, namespaces } = config;
if (!!resources)
this.resources = new ObjectPath(resources);
if (!!languages)
this.languages = languages;
if (!!namespaces)
this.namespaces = namespaces;
if (!!initialLanguage) {
this.initialLanguage = initialLanguage;
this.currentLanguage = initialLanguage;
}
if (!!httpConfig) {
this.httpConfig = httpConfig;
this.httpBackendAdapter();
}
}
onLoadNamepaces(cb) { }
onChangeLanguage(cb) { }
changeLanguage(lang) {
this.currentLanguage = lang;
this.httpBackendAdapter();
if (this.updater)
this.updater();
}
translate(path, rObject) {
let getWords = this.resources.get([this.currentLanguage, path].join("."));
if (getWords === undefined)
return path;
if (!!rObject) {
getWords = getWords.replace(/{{\s*\w+\s*}}/gim, (t) => {
let key = t.replace(/{{\s*|\s*}}/gim, "");
return rObject[key];
});
}
return getWords;
}
}
export const I18n = new I18nCore();