aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-web/src/main/js/translate.js
blob: 14444700c15c76ad602f60fc1af2b1719f22cc0d (plain)
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
(function() {
  window.suppressTranslationWarnings = false;

  window.t = function() {
    if (!window.messages) {
      return window.translate.apply(this, arguments);
    }

    var args = Array.prototype.slice.call(arguments, 0),
        key = args.join('.');
    return window.messages[key] != null ? window.messages[key] : key;
  };

  window.tp = function() {
    var args = Array.prototype.slice.call(arguments, 0),
      key = args.shift(),
      message = window.messages[key];
    if (message) {
      args.forEach(function(p, i) {
        message = message.replace('{' + i + '}', p);
      });
    }
    return message || (key + ' ' + args.join(' '));
  };


  window.translate = function() {
    var args = Array.prototype.slice.call(arguments, 0),
        tokens = args.reduce(function(prev, current) {
          return prev.concat(current.split('.'));
        }, []),
        key = tokens.join('.'),
        start = window.SS && window.SS.phrases,
        found = !!start,
        result = '';

    if (found) {
      result = tokens.reduce(function(prev, current) {
        if (!current || !prev[current]) {
          found = false;
        }
        return current ? prev[current] : prev;
      }, start);
    }

    return found ? result : key;
  };


  window.requestMessages = function() {
    var currentLocale = window.pageLang,
        cachedLocale = localStorage.getItem('l10n.locale');
    if (cachedLocale !== currentLocale) {
      localStorage.removeItem('l10n.timestamp');
    }

    var bundleTimestamp = localStorage.getItem('l10n.timestamp'),
        params = { locale: currentLocale };
    if (bundleTimestamp !== null) {
      params.ts = bundleTimestamp;
    }

    var apiUrl = baseUrl + '/api/l10n/index';
    return jQuery.ajax({
      url: apiUrl,
      data: params,
      dataType: 'json',
      statusCode: {
        304: function() {
          window.messages = JSON.parse(localStorage.getItem('l10n.bundle'));
        }
      }
    }).done(function(bundle, textStatus, jqXHR) {
      if(bundle !== undefined) {
        bundleTimestamp = new Date().toISOString();
        bundleTimestamp = bundleTimestamp.substr(0, bundleTimestamp.indexOf('.')) + '+0000';
        localStorage.setItem('l10n.timestamp', bundleTimestamp);
        localStorage.setItem('l10n.locale', currentLocale);

        window.messages = bundle;
        localStorage.setItem('l10n.bundle', JSON.stringify(bundle));
      } else if (jqXHR.status === 304) {
        window.messages = JSON.parse(localStorage.getItem('l10n.bundle'));
      }
    });
  };
})();