UNPKG

@aws-amplify/core

Version:
116 lines (114 loc) 3.21 kB
'use strict'; // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", { value: true }); exports.I18n = void 0; const Logger_1 = require("../Logger"); const logger = new Logger_1.ConsoleLogger('I18n'); /** * Language translation utility. */ class I18n { constructor() { /** * @private */ this._options = null; /** * @private */ this._lang = null; /** * @private */ this._dict = {}; } /** * Sets the default language from the configuration when required. */ setDefaultLanguage() { // Default to window language if not set in instance if (!this._lang && typeof window !== 'undefined' && window && window.navigator) { this._lang = window.navigator.language; } logger.debug(this._lang); } /** * @method * Explicitly setting language * @param {String} lang */ setLanguage(lang) { this._lang = lang; } /** * @method * Get value * @param {String} key * @param {String} defVal - Default value */ get(key, defVal = undefined) { this.setDefaultLanguage(); if (!this._lang) { return typeof defVal !== 'undefined' ? defVal : key; } const lang = this._lang; let val = this.getByLanguage(key, lang); if (val) { return val; } if (lang.indexOf('-') > 0) { val = this.getByLanguage(key, lang.split('-')[0]); } if (val) { return val; } return typeof defVal !== 'undefined' ? defVal : key; } /** * @method * Get value according to specified language * @param {String} key * @param {String} language - Specified langurage to be used * @param {String} defVal - Default value */ getByLanguage(key, language, defVal = null) { if (!language) { return defVal; } const langDict = this._dict[language]; if (!langDict) { return defVal; } return langDict[key]; } /** * @method * Add vocabularies for one language * @param {String} language - Language of the dictionary * @param {Object} vocabularies - Object that has key-value as dictionary entry */ putVocabulariesForLanguage(language, vocabularies) { let langDict = this._dict[language]; if (!langDict) { langDict = this._dict[language] = {}; } this._dict[language] = { ...langDict, ...vocabularies }; } /** * @method * Add vocabularies for one language * @param {Object} vocabularies - Object that has language as key, * vocabularies of each language as value */ putVocabularies(vocabularies) { Object.keys(vocabularies).forEach(key => { this.putVocabulariesForLanguage(key, vocabularies[key]); }); } } exports.I18n = I18n; //# sourceMappingURL=I18n.js.map