forked from i18next/i18next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18next.js
2751 lines (2509 loc) · 92.9 KB
/
i18next.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// i18next, v1.7.3
// Copyright (c)2014 Jan Mühlemann (jamuhl).
// Distributed under MIT license
// http://i18next.com
(function() {
// add indexOf to non ECMA-262 standard compliant browsers
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
// add lastIndexOf to non ECMA-262 standard compliant browsers
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = len;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) {
n = 0;
} else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
for (; k >= 0; k--) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Add string trim for IE8.
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
var root = this
, $ = root.jQuery || root.Zepto
, i18n = {}
, resStore = {}
, currentLng
, replacementCounter = 0
, languages = []
, initialized = false;
// Export the i18next object for **CommonJS**.
// If we're not in CommonJS, add `i18n` to the
// global object or to jquery.
if (typeof module !== 'undefined' && module.exports) {
module.exports = i18n;
} else {
if ($) {
$.i18n = $.i18n || i18n;
}
root.i18n = root.i18n || i18n;
}
// defaults
var o = {
lng: undefined,
load: 'all',
preload: [],
lowerCaseLng: false,
returnObjectTrees: false,
fallbackLng: ['dev'],
fallbackNS: [],
detectLngQS: 'setLng',
ns: 'translation',
fallbackOnNull: true,
fallbackOnEmpty: false,
fallbackToDefaultNS: false,
nsseparator: ':',
keyseparator: '.',
selectorAttr: 'data-i18n',
debug: false,
resGetPath: 'locales/__lng__/__ns__.json',
resPostPath: 'locales/add/__lng__/__ns__',
getAsync: true,
postAsync: true,
resStore: undefined,
useLocalStorage: false,
localStorageExpirationTime: 7*24*60*60*1000,
dynamicLoad: false,
sendMissing: false,
sendMissingTo: 'fallback', // current | all
sendType: 'POST',
ajaxFromFile: false,
interpolationPrefix: '__',
interpolationSuffix: '__',
reusePrefix: '$t(',
reuseSuffix: ')',
pluralSuffix: '_plural',
pluralNotFound: ['plural_not_found', Math.random()].join(''),
contextNotFound: ['context_not_found', Math.random()].join(''),
escapeInterpolation: false,
setJqueryExt: true,
defaultValueFromContent: true,
useDataAttrOptions: false,
cookieExpirationTime: undefined,
useCookie: true,
cookieName: 'i18next',
cookieDomain: undefined,
objectTreeKeyHandler: undefined,
postProcess: undefined,
parseMissingKey: undefined,
shortcutFunction: 'sprintf' // or: defaultValue
};
function _extend(target, source) {
if (!source || typeof source === 'function') {
return target;
}
for (var attr in source) { target[attr] = source[attr]; }
return target;
}
function _each(object, callback, args) {
var name, i = 0,
length = object.length,
isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
if (args) {
if (isObj) {
for (name in object) {
if (callback.apply(object[name], args) === false) {
break;
}
}
} else {
for ( ; i < length; ) {
if (callback.apply(object[i++], args) === false) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if (isObj) {
for (name in object) {
if (callback.call(object[name], name, object[name]) === false) {
break;
}
}
} else {
for ( ; i < length; ) {
if (callback.call(object[i], i, object[i++]) === false) {
break;
}
}
}
}
return object;
}
var _entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function _escape(data) {
if (typeof data === 'string') {
return data.replace(/[&<>"'\/]/g, function (s) {
return _entityMap[s];
});
}else{
return data;
}
}
function _ajax(options) {
// v0.5.0 of https://github.com/goloroden/http.js
var getXhr = function (callback) {
// Use the native XHR object if the browser supports it.
if (window.XMLHttpRequest) {
return callback(null, new XMLHttpRequest());
} else if (window.ActiveXObject) {
// In Internet Explorer check for ActiveX versions of the XHR object.
try {
return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
} catch (e) {
return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
}
}
// If no XHR support was found, throw an error.
return callback(new Error());
};
var encodeUsingUrlEncoding = function (data) {
if(typeof data === 'string') {
return data;
}
var result = [];
for(var dataItem in data) {
if(data.hasOwnProperty(dataItem)) {
result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
}
}
return result.join('&');
};
var utf8 = function (text) {
text = text.replace(/\r\n/g, '\n');
var result = '';
for(var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i);
if(c < 128) {
result += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
result += String.fromCharCode((c >> 6) | 192);
result += String.fromCharCode((c & 63) | 128);
} else {
result += String.fromCharCode((c >> 12) | 224);
result += String.fromCharCode(((c >> 6) & 63) | 128);
result += String.fromCharCode((c & 63) | 128);
}
}
return result;
};
var base64 = function (text) {
var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
text = utf8(text);
var result = '',
chr1, chr2, chr3,
enc1, enc2, enc3, enc4,
i = 0;
do {
chr1 = text.charCodeAt(i++);
chr2 = text.charCodeAt(i++);
chr3 = text.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if(isNaN(chr2)) {
enc3 = enc4 = 64;
} else if(isNaN(chr3)) {
enc4 = 64;
}
result +=
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while(i < text.length);
return result;
};
var mergeHeaders = function () {
// Use the first header object as base.
var result = arguments[0];
// Iterate through the remaining header objects and add them.
for(var i = 1; i < arguments.length; i++) {
var currentHeaders = arguments[i];
for(var header in currentHeaders) {
if(currentHeaders.hasOwnProperty(header)) {
result[header] = currentHeaders[header];
}
}
}
// Return the merged headers.
return result;
};
var ajax = function (method, url, options, callback) {
// Adjust parameters.
if(typeof options === 'function') {
callback = options;
options = {};
}
// Set default parameter values.
options.cache = options.cache || false;
options.data = options.data || {};
options.headers = options.headers || {};
options.jsonp = options.jsonp || false;
options.async = options.async === undefined ? true : options.async;
// Merge the various header objects.
var headers = mergeHeaders({
'accept': '*/*',
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
}, ajax.headers, options.headers);
// Encode the data according to the content-type.
var payload;
if (headers['content-type'] === 'application/json') {
payload = JSON.stringify(options.data);
} else {
payload = encodeUsingUrlEncoding(options.data);
}
// Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
// if neccessary.
if(method === 'GET') {
// Setup the query string.
var queryString = [];
if(payload) {
queryString.push(payload);
payload = null;
}
// Handle caching.
if(!options.cache) {
queryString.push('_=' + (new Date()).getTime());
}
// If neccessary prepare the query string for a JSONP call.
if(options.jsonp) {
queryString.push('callback=' + options.jsonp);
queryString.push('jsonp=' + options.jsonp);
}
// Merge the query string and attach it to the url.
queryString = queryString.join('&');
if (queryString.length > 1) {
if (url.indexOf('?') > -1) {
url += '&' + queryString;
} else {
url += '?' + queryString;
}
}
// Make a JSONP call if neccessary.
if(options.jsonp) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
return;
}
}
// Since we got here, it is no JSONP request, so make a normal XHR request.
getXhr(function (err, xhr) {
if(err) return callback(err);
// Open the request.
xhr.open(method, url, options.async);
// Set the request headers.
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
// Handle the request events.
xhr.onreadystatechange = function () {
if(xhr.readyState === 4) {
var data = xhr.responseText || '';
// If no callback is given, return.
if(!callback) {
return;
}
// Return an object that provides access to the data as text and JSON.
callback(xhr.status, {
text: function () {
return data;
},
json: function () {
return JSON.parse(data);
}
});
}
};
// Actually send the XHR request.
xhr.send(payload);
});
};
// Define the external interface.
var http = {
authBasic: function (username, password) {
ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
},
connect: function (url, options, callback) {
return ajax('CONNECT', url, options, callback);
},
del: function (url, options, callback) {
return ajax('DELETE', url, options, callback);
},
get: function (url, options, callback) {
return ajax('GET', url, options, callback);
},
head: function (url, options, callback) {
return ajax('HEAD', url, options, callback);
},
headers: function (headers) {
ajax.headers = headers || {};
},
isAllowed: function (url, verb, callback) {
this.options(url, function (status, data) {
callback(data.text().indexOf(verb) !== -1);
});
},
options: function (url, options, callback) {
return ajax('OPTIONS', url, options, callback);
},
patch: function (url, options, callback) {
return ajax('PATCH', url, options, callback);
},
post: function (url, options, callback) {
return ajax('POST', url, options, callback);
},
put: function (url, options, callback) {
return ajax('PUT', url, options, callback);
},
trace: function (url, options, callback) {
return ajax('TRACE', url, options, callback);
}
};
var methode = options.type ? options.type.toLowerCase() : 'get';
http[methode](options.url, options, function (status, data) {
if(options.ajaxFromFile) {
status = _xhrSuccessStatus[xhr.status] || xhr.status
}
if (status === 200) {
options.success(data.json(), status, null);
} else {
options.error(data.text(), status, null);
}
});
}
var _cookie = {
create: function(name,value,minutes,domain) {
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime()+(minutes*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
domain = (domain)? "domain="+domain+";" : "";
document.cookie = name+"="+value+expires+";"+domain+"path=/";
},
read: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
remove: function(name) {
this.create(name,"",-1);
}
};
var cookie_noop = {
create: function(name,value,minutes,domain) {},
read: function(name) { return null; },
remove: function(name) {}
};
// Deal with strange response codes
// Comes from JQuery ajax source
// Suggested by @iwege
var _xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
};
// move dependent functions to a container so that
// they can be overriden easier in no jquery environment (node.js)
var f = {
extend: $ ? $.extend : _extend,
each: $ ? $.each : _each,
ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
detectLanguage: detectLanguage,
escape: _escape,
log: function(str) {
if (o.debug && typeof console !== "undefined") console.log(str);
},
toLanguages: function(lng) {
var languages = [];
if (typeof lng === 'string' && lng.indexOf('-') > -1) {
var parts = lng.split('-');
lng = o.lowerCaseLng ?
parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
if (o.load !== 'unspecific') languages.push(lng);
if (o.load !== 'current') languages.push(parts[0]);
} else {
languages.push(lng);
}
for (var i = 0; i < o.fallbackLng.length; i++) {
if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(o.fallbackLng[i]);
}
return languages;
},
regexEscape: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
xhrSuccessStatus: _xhrSuccessStatus
};
function init(options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
// override defaults with passed in options
f.extend(o, options);
delete o.fixLng; /* passed in each time */
// create namespace object if namespace is passed in as string
if (typeof o.ns == 'string') {
o.ns = { namespaces: [o.ns], defaultNs: o.ns};
}
// fallback namespaces
if (typeof o.fallbackNS == 'string') {
o.fallbackNS = [o.fallbackNS];
}
// fallback languages
if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
o.fallbackLng = [o.fallbackLng];
}
// escape prefix/suffix
o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
if (!o.lng) o.lng = f.detectLanguage();
if (o.lng) {
// set cookie with lng set (as detectLanguage will set cookie on need)
if (o.useCookie) f.cookie.create(o.cookieName, o.lng, o.cookieExpirationTime, o.cookieDomain);
} else {
o.lng = o.fallbackLng[0];
if (o.useCookie) f.cookie.remove(o.cookieName);
}
languages = f.toLanguages(o.lng);
currentLng = languages[0];
f.log('currentLng set to: ' + currentLng);
var lngTranslate = translate;
if (options.fixLng) {
lngTranslate = function(key, options) {
options = options || {};
options.lng = options.lng || lngTranslate.lng;
return translate(key, options);
};
lngTranslate.lng = currentLng;
}
pluralExtensions.setCurrentLng(currentLng);
// add JQuery extensions
if ($ && o.setJqueryExt) addJqueryFunct();
// jQuery deferred
var deferred;
if ($ && $.Deferred) {
deferred = $.Deferred();
}
// return immidiatly if res are passed in
if (o.resStore) {
resStore = o.resStore;
initialized = true;
if (cb) cb(lngTranslate);
if (deferred) deferred.resolve(lngTranslate);
if (deferred) return deferred.promise();
return;
}
// languages to load
var lngsToLoad = f.toLanguages(o.lng);
if (typeof o.preload === 'string') o.preload = [o.preload];
for (var i = 0, l = o.preload.length; i < l; i++) {
var pres = f.toLanguages(o.preload[i]);
for (var y = 0, len = pres.length; y < len; y++) {
if (lngsToLoad.indexOf(pres[y]) < 0) {
lngsToLoad.push(pres[y]);
}
}
}
// else load them
i18n.sync.load(lngsToLoad, o, function(err, store) {
resStore = store;
initialized = true;
if (cb) cb(lngTranslate);
if (deferred) deferred.resolve(lngTranslate);
});
if (deferred) return deferred.promise();
}
function preload(lngs, cb) {
if (typeof lngs === 'string') lngs = [lngs];
for (var i = 0, l = lngs.length; i < l; i++) {
if (o.preload.indexOf(lngs[i]) < 0) {
o.preload.push(lngs[i]);
}
}
return init(cb);
}
function addResourceBundle(lng, ns, resources) {
if (typeof ns !== 'string') {
resources = ns;
ns = o.ns.defaultNs;
} else if (o.ns.namespaces.indexOf(ns) < 0) {
o.ns.namespaces.push(ns);
}
resStore[lng] = resStore[lng] || {};
resStore[lng][ns] = resStore[lng][ns] || {};
f.extend(resStore[lng][ns], resources);
}
function removeResourceBundle(lng, ns) {
if (typeof ns !== 'string') {
ns = o.ns.defaultNs;
}
resStore[lng] = resStore[lng] || {};
resStore[lng][ns] = {};
}
function setDefaultNamespace(ns) {
o.ns.defaultNs = ns;
}
function loadNamespace(namespace, cb) {
loadNamespaces([namespace], cb);
}
function loadNamespaces(namespaces, cb) {
var opts = {
dynamicLoad: o.dynamicLoad,
resGetPath: o.resGetPath,
getAsync: o.getAsync,
customLoad: o.customLoad,
ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
};
// languages to load
var lngsToLoad = f.toLanguages(o.lng);
if (typeof o.preload === 'string') o.preload = [o.preload];
for (var i = 0, l = o.preload.length; i < l; i++) {
var pres = f.toLanguages(o.preload[i]);
for (var y = 0, len = pres.length; y < len; y++) {
if (lngsToLoad.indexOf(pres[y]) < 0) {
lngsToLoad.push(pres[y]);
}
}
}
// check if we have to load
var lngNeedLoad = [];
for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
var needLoad = false;
var resSet = resStore[lngsToLoad[a]];
if (resSet) {
for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
if (!resSet[namespaces[b]]) needLoad = true;
}
} else {
needLoad = true;
}
if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
}
if (lngNeedLoad.length) {
i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
var todo = namespaces.length * lngNeedLoad.length;
// load each file individual
f.each(namespaces, function(nsIndex, nsValue) {
// append namespace to namespace array
if (o.ns.namespaces.indexOf(nsValue) < 0) {
o.ns.namespaces.push(nsValue);
}
f.each(lngNeedLoad, function(lngIndex, lngValue) {
resStore[lngValue] = resStore[lngValue] || {};
resStore[lngValue][nsValue] = store[lngValue][nsValue];
todo--; // wait for all done befor callback
if (todo === 0 && cb) {
if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
cb();
}
});
});
});
} else {
if (cb) cb();
}
}
function setLng(lng, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
} else if (!options) {
options = {};
}
options.lng = lng;
return init(options, cb);
}
function lng() {
return currentLng;
}
function addJqueryFunct() {
// $.t shortcut
$.t = $.t || translate;
function parse(ele, key, options) {
if (key.length === 0) return;
var attr = 'text';
if (key.indexOf('[') === 0) {
var parts = key.split(']');
key = parts[1];
attr = parts[0].substr(1, parts[0].length-1);
}
if (key.indexOf(';') === key.length-1) {
key = key.substr(0, key.length-2);
}
var optionsToUse;
if (attr === 'html') {
optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
ele.html($.t(key, optionsToUse));
} else if (attr === 'text') {
optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
ele.text($.t(key, optionsToUse));
} else if (attr === 'prepend') {
optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
ele.prepend($.t(key, optionsToUse));
} else if (attr === 'append') {
optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
ele.append($.t(key, optionsToUse));
} else if (attr.indexOf("data-") === 0) {
var dataAttr = attr.substr(("data-").length);
optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
var translated = $.t(key, optionsToUse);
//we change into the data cache
ele.data(dataAttr, translated);
//we change into the dom
ele.attr(attr, translated);
} else {
optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
ele.attr(attr, $.t(key, optionsToUse));
}
}
function localize(ele, options) {
var key = ele.attr(o.selectorAttr);
if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
if (!key) return;
var target = ele
, targetSelector = ele.data("i18n-target");
if (targetSelector) {
target = ele.find(targetSelector) || ele;
}
if (!options && o.useDataAttrOptions === true) {
options = ele.data("i18n-options");
}
options = options || {};
if (key.indexOf(';') >= 0) {
var keys = key.split(';');
$.each(keys, function(m, k) {
if (k !== '') parse(target, k, options);
});
} else {
parse(target, key, options);
}
if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
}
// fn
$.fn.i18n = function (options) {
return this.each(function() {
// localize element itself
localize($(this), options);
// localize childs
var elements = $(this).find('[' + o.selectorAttr + ']');
elements.each(function() {
localize($(this), options);
});
});
};
}
function applyReplacement(str, replacementHash, nestedKey, options) {
if (!str) return str;
options = options || replacementHash; // first call uses replacement hash combined with options
if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
, suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
, unEscapingSuffix = 'HTML'+suffix;
f.each(replacementHash, function(key, value) {
var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
if (typeof value === 'object' && value !== null) {
str = applyReplacement(str, value, nextKey, options);
} else {
if (options.escapeInterpolation || o.escapeInterpolation) {
str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), value);
str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.escape(value));
} else {
str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), value);
}
// str = options.escapeInterpolation;
}
});
return str;
}
// append it to functions
f.applyReplacement = applyReplacement;
function applyReuse(translated, options) {
var comma = ',';
var options_open = '{';
var options_close = '}';
var opts = f.extend({}, options);
delete opts.postProcess;
while (translated.indexOf(o.reusePrefix) != -1) {
replacementCounter++;
if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
var index_of_opening = translated.lastIndexOf(o.reusePrefix);
var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
var token = translated.substring(index_of_opening, index_of_end_of_closing);
var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
if (token_without_symbols.indexOf(comma) != -1) {
var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {
var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
try {
opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
} catch (e) {
}
}
}
var translated_token = _translate(token_without_symbols, opts);
translated = translated.replace(token, translated_token);
}
return translated;
}
function hasContext(options) {
return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
}
function needsPlural(options) {
return (options.count !== undefined && typeof options.count != 'string' && options.count !== 1);
}
function exists(key, options) {
options = options || {};
var notFound = _getDefaultValue(key, options)
, found = _find(key, options);
return found !== undefined || found === notFound;
}
function translate(key, options) {
options = options || {};
if (!initialized) {
f.log('i18next not finished initialization. you might have called t function before loading resources finished.')