UNPKG

@rockpack/localazer

Version:

This module can help you organize localization in your React application

68 lines (67 loc) 3 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.getID = exports.components = void 0; var react_1 = require("react"); var valid_types_1 = require("valid-types"); var utils_1 = require("./utils"); var jed_1 = require("./jed"); exports.components = {}; var uid = 0; exports.getID = function () { return uid++; }; var LocalizationObserver = /** @class */ (function (_super) { __extends(LocalizationObserver, _super); function LocalizationObserver(props) { var _this = _super.call(this, props) || this; _this.changeLocalization(_this.props.currentLanguage); return _this; } LocalizationObserver.prototype.componentDidUpdate = function (prevProps) { if (this.props.currentLanguage !== prevProps.currentLanguage) { this.changeLocalization(this.props.currentLanguage); } }; LocalizationObserver.prototype.changeLocalization = function (locale) { locale = this.props.languages[locale] ? locale : this.props.defaultLanguage; var localeData = this.props.languages[locale] ? this.props.languages[locale] : utils_1.getDefault(this.props.defaultLanguage, this.props.defaultLocaleData); this.updateComponents(localeData, locale); }; LocalizationObserver.prototype.updateComponents = function (localeData, locale) { if (localeData && valid_types_1.isObject(localeData.locale_data) && valid_types_1.isObject(localeData.locale_data.messages)) { if (valid_types_1.isFunction(this.props.onChange) && valid_types_1.isString(locale)) { this.props.onChange(locale); } jed_1.i18n.options = localeData; Object.keys(exports.components) .forEach(function (id) { if (valid_types_1.isDefined(exports.components[id])) { exports.components[id].forceUpdate(); } }); } }; LocalizationObserver.prototype.render = function () { return this.props.children; }; LocalizationObserver.defaultProps = { currentLanguage: 'en', defaultLanguage: 'en', languages: {}, defaultLocaleData: null }; return LocalizationObserver; }(react_1.Component)); exports.default = LocalizationObserver;