t8on
Version:
Set up, format and translate phrases easily
99 lines (75 loc) • 2.61 kB
JavaScript
;
exports.__esModule = true;
exports.default = Translation;
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Translation() {
var _this = this;
var dictionary = {};
this.currentLocale = null;
this.fallbackLocale = null;
this.dictionary = function () {
return dictionary;
};
this.load = function (locale, pairs) {
if (!(locale in dictionary)) {
dictionary[locale] = {};
}
(0, _merge2.default)(dictionary[locale], pairs);
return _this;
};
this.loadRoot = function (root) {
(0, _merge2.default)(dictionary, root);
return _this;
};
this.setLocale = function (locale, dic) {
dictionary[locale] = dic;
return _this;
};
this.translate = function (phrase, locale) {
if (!(locale in dictionary) || !(phrase in dictionary[locale])) {
if (!_this.fallbackLocale || locale === _this.fallbackLocale) {
return '';
}
return _this.translate(phrase, _this.fallbackLocale);
}
return dictionary[locale][phrase];
};
this.translateTo = function (locale) {
return function (phrase) {
return _this.translate(phrase, locale);
};
};
this.translateCurrent = function (phrase) {
return _this.translate(phrase, _this.currentLocale || '');
};
this.format = function (phrase, locale) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
if (!(locale in dictionary) || !(phrase in dictionary[locale])) {
if (!_this.fallbackLocale || locale === _this.fallbackLocale) {
return '';
}
return _this.format.apply(_this, [phrase, _this.fallbackLocale].concat(args));
}
return dictionary[locale][phrase].replace(/%(\S)/g, function (_, i) {
return args[i];
});
};
this.formatTo = function (locale) {
return function (phrase) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
return _this.format.apply(_this, [phrase, locale].concat(args));
};
};
this.formatCurrent = function (phrase) {
for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return _this.format.apply(_this, [phrase, _this.currentLocale || ''].concat(args));
};
}