onix-core
Version:
Onix library core
98 lines • 3.85 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.i18n = exports._ = void 0;
const tslib_1 = require("tslib");
const intl_messageformat_1 = require("intl-messageformat");
const warning_1 = tslib_1.__importDefault(require("warning"));
const enTranslation = tslib_1.__importStar(require("./i18n/en-us.json"));
const esTranslation = tslib_1.__importStar(require("./i18n/es-es.json"));
const ruTranslation = tslib_1.__importStar(require("./i18n/ru-ru.json"));
const defaultLocale = "en-us";
let initialized = false;
class IntlManager {
constructor() {
this.currentLocale = defaultLocale;
this.strings = {};
this.setLocale = (value) => {
if (value) {
if (value.length === 2) {
value = value + "-" + value;
}
const msg = new intl_messageformat_1.IntlMessageFormat('', value);
const locale = msg.resolvedOptions().locale;
if (locale) {
this.currentLocale = locale.toLowerCase();
}
else {
this.currentLocale = defaultLocale;
}
}
return this.currentLocale;
};
this.safeT = (category, locale, key) => {
let result = key;
if (this.strings[locale] && this.strings[locale][category] && this.strings[locale][category][key]) {
result = this.strings[locale][category][key];
}
return result;
};
this.t = (category, key, args) => {
let message = this.safeT(category, this.currentLocale, key);
if (message === key) {
message = this.safeT(category, defaultLocale, key);
}
warning_1.default(message !== key, `Empty string for category ${category} and key ${key}.`);
const formatter = new intl_messageformat_1.IntlMessageFormat(message, this.currentLocale);
const result = formatter.format(args);
if (result) {
if (typeof result === "string") {
return result;
}
else {
return result.join(" ");
}
}
return message;
};
this.registerStrings = (lang, category, strings) => {
if (this.strings[lang] === undefined) {
this.strings[lang] = {};
}
if (this.strings[lang][category] === undefined) {
this.strings[lang][category] = {};
}
for (const key in strings) {
this.strings[lang][category][key] = strings[key];
}
};
this.registerCategories = (lang, strings) => {
for (const category in strings) {
this.registerStrings(lang, category, strings[category]);
}
};
this.register = (i18n) => {
if (!initialized) {
this.registerCategories("en-us", enTranslation);
this.registerCategories("es-es", esTranslation);
this.registerCategories("ru-ru", ruTranslation);
initialized = true;
}
if (i18n !== undefined) {
this.registerCategories(this.currentLocale, i18n);
}
};
if ((window !== undefined) && (window["navigator"])) {
this.setLocale(window.navigator.language);
}
this.register();
}
}
const manager = new IntlManager();
exports._ = manager.t;
var i18n;
(function (i18n) {
i18n.setLocale = manager.setLocale;
i18n.register = manager.register;
i18n.registerCategories = manager.registerCategories;
})(i18n = exports.i18n || (exports.i18n = {}));
//# sourceMappingURL=i18n.js.map