forked from eligrey/l10n.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
l10ns.js
273 lines (250 loc) · 11.1 KB
/
l10ns.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*! version v1.0.1 */
/*
* l10n.js
*
* Adapted with pluralization by Chua Chee How. http://rojakcoder.com
* By Eli Grey, http://eligrey.com
* Licensed under the X11/MIT License
* See LICENSE.md
*/
/*global XMLHttpRequest, setTimeout, document, navigator, ActiveXObject*/
/*jslint plusplus: true, continue: true, evil: true*/
(function () {
"use strict";
var load_queues = {}, localizations = {},
// the official format is application/vnd.oftn.l10n+json, though l10n.js will also
// accept application/x-l10n+json and application/l10n+json
l10n_js_media_type = /^\s*application\/(?:vnd\.oftn\.|x-)?l10n\+json\s*(?:$|;)/i,
XHR,
array_index_of = Array.prototype.indexOf || function (item) {
var len = this.length, i = 0;
for (i = 0; i < len; i++) {
if (this.hasOwnProperty(i) && this[i] === item) {
return i;
}
}
return -1;
},
request_JSON = function (uri) {
var req = new XHR();
// sadly, this has to be blocking to allow for a graceful degrading API
req.open("GET", uri, false);
req.send(null);
if (req.status !== 200) {
// warn about error without stopping execution
setTimeout(function () {
// Error messages are not localized as not to cause an infinite loop
var l10n_err = new Error("Unable to load localization data: " + uri);
l10n_err.name = "Localization Error";
throw l10n_err;
}, 0);
return {};
}
return JSON.parse(req.responseText);
},
load = function (data) {
// don't handle function['toLocaleString'](indentationAmount:Number)
if (arguments.length > 0 && typeof data !== "number") {
if (typeof data === 'string') {
load(request_JSON(data));
} else if (data === false) {
// reset all localizations
localizations = {};
} else {
// Extend current localizations instead of completely overwriting them
var locale, localization, message;
for (locale in data) {
if (data.hasOwnProperty(locale)) {
localization = data[locale];
locale = locale.toLowerCase();
if (!localizations.hasOwnProperty(locale) || localization === false) {
// reset locale if not existing or reset flag is specified
localizations[locale] = {};
}
if (localization === false) {
continue;
}
// URL specified
if (typeof localization === 'string') {
if (String.locale.toLowerCase().indexOf(locale) === 0) {
localization = request_JSON(localization);
} else {
// queue loading locale if not needed
if (!load_queues.hasOwnProperty(locale)) {
load_queues[locale] = [];
}
load_queues[locale].push(localization);
continue;
}
}
for (message in localization) {
if (localization.hasOwnProperty(message)) {
localizations[locale][message] = localization[message];
}
}
}
}
}
}
// Return what function['toLocaleString']() normally returns
return Function.prototype.toLocaleString.apply(String, arguments);
},
process_load_queue = function (locale) {
var queue = load_queues[locale],
i,
len = queue.length,
localization;
for (i = 0; i < len; i++) {
localization = {};
localization[locale] = request_JSON(queue[i]);
load(localization);
}
delete load_queues[locale];
},
use_default,
/**
* Evaluates the plural statements to get the correct index in the array.
* The plurality evaluation statement has to be coordinated with
* the plural forms i.e. if plural=(n!=1), then use "cats" for the
* first cell and "cat" for the second cell.
* On the other hand, if plural=(n==1), first cell should be "cat"
* and second cell should be "cats".
*/
parsePlural = function (pluralForms, n) {
//n is used in eval()
var re = /^nplurals=[0-9];\s*plural=\(([n!=><(?:\s+\|\|\s+)(?:\s+&&\s+)%0-9]{3,})\)/i,
evalResult,
result = re.exec(pluralForms);
if (result && result[1]) {
evalResult = eval(result[1]);
if (evalResult === true) {
return 0;
}
if (evalResult === false) {
return 1;
}
return evalResult;
}
return 0;
},
getPlural = function (localization, position, this_val) {
if (localization['&plurals']) {
if (localization['&plurals'][position] &&
localization['&plurals'][position][this_val]) {
return localization['&plurals'][position][this_val];
}
if (localization['&plurals'][0] &&
localization['&plurals'][0][this_val]) {
return localization['&plurals'][0][this_val];
}
} else if (localization[this_val]) {
return localization[this_val];
}
},
/**
* The actual function called when calling toLocaleString.
*/
localize = function (cardinality) {
var pluralForms, plural, position,
using_default = use_default,
current_locale = String[using_default ? 'defaultLocale' : 'locale'],
parts = current_locale.toLowerCase().split("-"),
i = parts.length,
this_val = this.valueOf(),
locale;
use_default = false;
// Iterate through locales starting at most-specific until a localization is found
do {
locale = parts.slice(0, i).join("-");
// load locale if not loaded
if (load_queues[locale]) {
process_load_queue(locale);
}
if (localizations[locale]) {
pluralForms = localizations[locale]['&plural-forms'];
if (pluralForms) {
if (typeof pluralForms === 'function') {
if (cardinality === null || cardinality === undefined) {
position = 0;
} else {
position = pluralForms(cardinality);
}
plural = getPlural(localizations[locale], position, this_val);
//only return if plural form is found
if (plural) {
return plural.replace('__n__', cardinality);
}
} else {
if (cardinality === null || cardinality === undefined ||
pluralForms.indexOf('nplurals=1') !== -1) {
//i.e. nplurals=1, use [0]
plural = getPlural(localizations[locale], 0, this_val);
//only return if plural form is found
if (plural) {
return plural.replace('__n__', cardinality);
}
}
if (pluralForms.indexOf('nplurals=2') !== -1) {
position = parsePlural(pluralForms, cardinality);
plural = getPlural(localizations[locale], position, this_val);
//only return if plural form is found
if (plural) {
return plural.replace('__n__', cardinality);
}
}
}
}
if (localizations[locale][this_val]) {
return localizations[locale][this_val];
}
}
//not returning anything will result in fallback
} while (i-- > 1);
if (!using_default && String.defaultLocale) {
use_default = true;
return localize.call(this_val, cardinality);
}
return this_val;
},
rel, elt, elts = document.getElementsByTagName("link"),
i = elts.length,
localization;
String.toLocaleString = load;
String.prototype.toLocaleString = localize;
if (XMLHttpRequest === undefined && ActiveXObject !== undefined) {
XHR = function () {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (ignore) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (ignore) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (ignore) {}
throw new Error("XMLHttpRequest not supported by this browser.");
};
} else {
XHR = XMLHttpRequest;
}
String.defaultLocale = String.defaultLocale || "";
String.locale = (navigator && (navigator.language || navigator.userLanguage)) || "";
if (document !== undefined) {
while (i--) {
elt = elts[i];
rel = (elt.getAttribute("rel") || "").toLowerCase().split(/\s+/);
if (l10n_js_media_type.test(elt.type)) {
if (array_index_of.call(rel, "localizations") !== -1) {
// multiple localizations
load(elt.getAttribute("href"));
} else if (array_index_of.call(rel, "localization") !== -1) {
// single localization
localization = {};
localization[(elt.getAttribute("hreflang") || "").toLowerCase()] =
elt.getAttribute("href");
load(localization);
}
}
}
}
}());