Completed
Pull Request — develop (#123)
by Xaver
01:03
created

language.js ➔ ... ➔ setSelectLocale   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
nc 1
dl 0
loc 4
rs 10
nop 1
1
define(['polyglot', 'moment', 'helper'], function (Polyglot, moment, helper) {
2
  'use strict';
3
  return function (config) {
4
    function languageSelect(el) {
5
      var select = document.createElement('select');
6
      select.className = 'language-switch';
7
      select.addEventListener('change', setSelectLocale);
8
      el.appendChild(select);
9
10
      // Keep english
11
      select.innerHTML = '<option>Language</option>';
12
      for (var i = 0; i < config.supportedLocale.length; i++) {
13
        select.innerHTML += '<option value="' + config.supportedLocale[i] + '">' + config.supportedLocale[i] + '</option>';
14
      }
15
    }
16
17
    function setSelectLocale(event) {
18
      localStorage.setItem('language', getLocale(event.target.value));
19
      location.reload();
20
    }
21
22
    function setLocale(lang) {
23
      localStorage.setItem('language', getLocale(lang));
24
      location.reload();
25
    }
26
27
    function getLocale(input) {
28
      var language = input || localStorage.getItem('language') || navigator.languages && navigator.languages[0] || navigator.language || navigator.userLanguage;
29
      var locale = config.supportedLocale[0];
30
      config.supportedLocale.some(function (item) {
31
        if (language.indexOf(item) !== -1) {
32
          locale = item;
33
          return true;
34
        }
35
        return false;
36
      });
37
      return locale;
38
    }
39
40
    function setTranslation(json) {
41
      _.extend(json);
42
43
      if (moment.locale(_.locale()) !== _.locale()) {
44
        moment.defineLocale(_.locale(), {
45
          longDateFormat: {
46
            LT: 'HH:mm',
47
            LTS: 'HH:mm:ss',
48
            L: 'DD.MM.YYYY',
49
            LL: 'D. MMMM YYYY',
50
            LLL: 'D. MMMM YYYY HH:mm',
51
            LLLL: 'dddd, D. MMMM YYYY HH:mm'
52
          },
53
          calendar: json.momentjs.calendar,
54
          relativeTime: json.momentjs.relativeTime
55
        });
56
      }
57
    }
58
59
    window._ = new Polyglot({ locale: getLocale(), allowMissing: true });
60
    helper.getJSON('locale/' + _.locale() + '.json?' + config.cacheBreaker).then(setTranslation);
61
62
    return {
63
      languageSelect: languageSelect,
64
      setLocale: setLocale
65
    };
66
  };
67
});
68