summaryrefslogtreecommitdiffstats
path: root/lib/utils/i18n.js
blob: c3253b78aa99bc7f1626b87b92d4d89d2789a22c (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
var _ = require("lodash");
var path = require("path");
var fs = require("fs");

var i18n = require("i18n");

var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/")
var DEFAULT_LANGUAGE = "en";
var LOCALES = _.map(fs.readdirSync(I18N_PATH), function(lang) {
    return path.basename(lang, ".json");
});

i18n.configure({
    locales: LOCALES,
    directory: I18N_PATH,
    defaultLocale: DEFAULT_LANGUAGE,
    updateFiles: false
});

var compareLocales = function(lang, locale) {
    var langMain = _.first(lang.split("-"));
    var langSecond = _.last(lang.split("-"));

    var localeMain = _.first(locale.split("-"));
    var localeSecond = _.last(locale.split("-"));

    if (locale == lang) return 100;
    if (localeMain == langMain) return 50;
    if (localeSecond == langSecond) return 20;
    return 0;
};

var normalizeLanguage = _.memoize(function(lang) {
    var language = _.chain(LOCALES)
        .values()
        .map(function(locale) {
            return {
                locale: locale,
                score: compareLocales(lang, locale)
            }
        })
        .filter(function(lang) {
            return lang.score > 0;
        })
        .sortBy("score")
        .pluck("locale")
        .last()
        .value();
    return language || lang;
});

var translate = function(locale, phrase) {
    var args = Array.prototype.slice.call(arguments, 2);

    return i18n.__.apply({}, [{
        locale: locale,
        phrase: phrase
    }].concat(args));
};

var getCatalog = function(locale) {
    locale = normalizeLanguage(locale);
    return i18n.getCatalog(locale);
};

var getLocales = function() {
    return LOCALES;
};

var hasLocale = function(locale) {
    return _.contains(LOCALES, locale);
}

module.exports = {
    __: translate,
    normalizeLanguage: normalizeLanguage,
    getCatalog: getCatalog,
    getLocales: getLocales,
    hasLocale: hasLocale
};