-
Notifications
You must be signed in to change notification settings - Fork 1
/
i18n.js
130 lines (106 loc) · 3.15 KB
/
i18n.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* @module i18n
* @desc RequireJS-модуль интернационализации
* @author ankostyuk
*/
define(function(require) {'use strict';
require('lodash');
//
var root = window,
CONTEXT_GLUE = '\u0004',
bundle = {},
pluralFormFuncs = {},
langBundle = null,
langPluralFormIndex = null;
var config = {
escape: true
};
function setConfig(options) {
_.extend(config, options);
}
function setBundle(arg) {
if (_.isArray(arg)) {
makeBundle(arg);
} else if (_.isObject(arg)) {
makeBundle([arg]);
} else {
throw new Error('arg is must be object or array');
}
}
function setLang(lang) {
langBundle = bundle[lang];
if (!langBundle) {
throw new Error('Lang is not supported: ' + lang);
}
langPluralFormIndex = pluralFormFuncs[lang];
}
function makeBundle(bundleList) {
var bundleJSON = bundleList[0],
i, b;
for (i = 1; i < bundleList.length; i++) {
b = bundleList[i];
_.each(b, function(langBundle, lang){
if (_.has(bundleJSON, lang)) {
_.extend(bundleJSON[lang], langBundle);
} else {
bundleJSON[lang] = langBundle;
}
});
}
bundle = bundleJSON;
pluralFormFuncs = buildPluralFormFuncs();
}
function buildPluralFormFuncs() {
var r = {};
_.each(bundle, function(langBundle, lang){
var ruleCode = langBundle['']['pluralForms']['ruleCode'];
r[lang] = new Function('n', 'return (' + ruleCode + ');');
});
return r;
}
function getMessage(key, context, index) {
var r = key,
messages = langBundle[context ? (context + CONTEXT_GLUE + key) : key];
if (_.isArray(messages)) {
var message = messages[index];
if (message && message !== '') {
r = message;
}
}
if (config.escape) {
r = _.escape(r);
}
return r;
}
//
function translateTemplate(templateString) {
var template = _.template(templateString, null, config.templateSettings);
return template();
}
//
var _tr = root._tr = function(key) {
return getMessage(key, null, 1);
};
var _trc = root._trc = function(key, context) {
return getMessage(key, context, 1);
};
var _trn = root._trn = function(key, n) {
return getMessage(key, null, 1 + langPluralFormIndex(n));
};
var _trnc = root._trnc = function(key, n, context) {
return getMessage(key, context, 1 + langPluralFormIndex(n));
};
//
return {
setConfig: setConfig,
setBundle: setBundle,
setLang: setLang,
translateTemplate: translateTemplate,
translateFuncs: {
_tr: _tr,
_trc: _trc,
_trn: _trn,
_trnc: _trnc
}
};
});