All files / src/lib/i18n index.js

0% Statements 0/27
0% Branches 0/11
0% Functions 0/5
0% Lines 0/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95                                                                                                                                                                                             
import { default as en } from './lang/en-US';
import { default as tr } from './lang/tr-TR';
import { default as de } from './lang/de-DE';
 
import { default as template } from './template.html';
/**
 * @classdesc Internalization controller. If not efined
 * tries to get localization value from browser.
 * Or expects it's defined in 2 small letters
 * language code like `en` for `English`
 */
export class Localization {
  /**
   *
   * @param {string} lang Language code.
   */
  constructor(lang = 'en') {
    if (typeof lang !== 'string') {
      lang = navigator.language;
    }
 
    this.all = {
      en,
      de,
      tr,
    };
    this.lang = lang.slice(0, 2).toLowerCase();
 
    this.tmpl = window.document.createElement('div');
    this.tmpl.innerHTML = template;
 
    switch (this.lang) {
      case 'en': {
        this.dict = en;
        break;
      }
      case 'tr': {
        this.dict = tr;
        break;
      }
      case 'de': {
        this.dict = de;
        break;
      }
      default: {
        this.dict = en;
      }
    }
  }
 
  /**
   *
   * @param {string} key Key name of identifier.
   * @return {string} Message in selected langauge.
   */
  message(key) {
    return this.dict[key].message;
  }
  /**
   * Gets html markup from sample templates.
   * @param {string} key name of identifier.
   * @return {string} HTML-markup as sample.
   */
  sample(key) {
    const tmpl = this.tmpl.querySelector(`#${key}`);
 
    const clone = window.document.importNode(tmpl, true);
 
    return clone.innerHTML;
  }
 
  /**
   * Update all language related fileds using attribute data-i18n.
   * @param {{}} shadowRoot
   */
  update(shadowRoot) {
    const items = shadowRoot.querySelectorAll('[data-i18n]');
    const self = this;
    [].forEach.call(items, (item) => {
      switch (item.dataset.i18n) {
        case 'LANGUAGE_LABEL': {
          item.innerText = this.all[item.value].LANGUAGE_LABEL.message;
          if (item.value === self.lang) {
            item.setAttribute('selected', true);
          }
          break;
        }
        default: {
          item.innerText = this.message(item.dataset.i18n);
        }
      }
    });
  }
}