UNPKG

@hsui/core

Version:

Hundsun frontend runtime core framework

72 lines (70 loc) 1.95 kB
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import I18nPath from './path'; import { isArray, isPlainObject, isNull, isString } from '../utils'; export var i18ns = []; var I18n = /*#__PURE__*/function () { /** * lightweight i18n * @param {object} options * - locale * - messages */ function I18n(options) { _classCallCheck(this, I18n); this.locale = options.locale || 'en-US'; this.messages = options.messages || {}; // window.__hCoreReference var root = window.__hCoreReference__.root; this._root = options.root || root || null; this._path = new I18nPath(); this.watchLocale(); i18ns.push(this); } _createClass(I18n, [{ key: "watchLocale", value: function watchLocale() { // sync with vue-i18n root if (this._root && this._root.$i18n) { // locale watcher var _this = this; this.localeWatcher = this._root.$i18n.vm.$watch('locale', function (val) { _this.locale = val; }, { immediate: true }); } return null; } // string support only }, { key: "_translate", value: function _translate(message, key) { var pathRet = this._path.getPathValue(message, key); if (isArray(pathRet) || isPlainObject(pathRet)) { return pathRet; } var ret; if (isNull(pathRet) && isPlainObject(message)) { ret = message[key]; } else if (isString(pathRet)) { ret = pathRet; } else { return null; } return !isString(ret) ? ret.join('') : ret; } }, { key: "t", value: function t(key) { if (!key) return ''; var message = this.messages[this.locale]; if (message) { return this._translate(message, key); } return ''; } }]); return I18n; }(); export { I18n as default };