This repository has been archived by the owner on Mar 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathangular-internationalization.js
595 lines (523 loc) · 27.9 KB
/
angular-internationalization.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
angular.module('angular-i18n', ['ng'])
// create our localization service
.provider('$i18n', [function () {
return {
_fileURL: '/i18n/|LANG|.json',
_fileURLLanguageToken: /\|LANG\|/,
_fileURLPartToken: /\|PART\|/,
_allowPartialFileLoading: false,
_useBaseHrefTag: false,
_baseHref: '',
_defaultLanguage: 'en-US',
_language: null,
_fallback: null,
_debug: false,
_onTranslationFailed: null,
get allowPartialFileLoading() {
return this._allowPartialFileLoading;
},
set allowPartialFileLoading(value) {
this._allowPartialFileLoading = value;
return this;
},
get baseHref() {
return this._baseHref;
},
get debug() {
return this._debug;
},
set debug(value) {
this._debug = value;
return this;
},
get defaultLanguage() {
return this._defaultLanguage;
},
set defaultLanguage(lang) {
this._defaultLanguage = lang;
return this;
},
get fallback() {
return this._fallback;
},
set fallback(json) {
this._fallback = json;
return this;
},
get fileURL() {
return this._fileURL;
},
set fileURL(url) {
this._fileURL = url;
return this;
},
get fileURLLanguageToken() {
return this._fileURLLanguageToken;
},
set fileURLLanguageToken(value) {
this._fileURLLanguageToken = value;
return this;
},
get fileURLPartToken() {
return this._fileURLPartToken;
},
set fileURLPartToken(value) {
this._fileURLPartToken = value;
return this;
},
get language() {
return this._language;
},
set language(lang) {
this._language = lang;
return this;
},
get onTranslationFailed() {
return this._onTranslationFailed;
},
set onTranslationFailed(func) {
if (func === null || func && {}.toString.call(func) == '[object Function]') {
this._onTranslationFailed = func;
}
else {
throw new TypeError('the argument func of displayUntranslated(func) must be a function');
}
return this;
},
get useBaseHrefTag() {
return this._useBaseHrefTag;
},
set useBaseHrefTag(value) {
this._useBaseHrefTag = value;
if (this._useBaseHrefTag) {
var bases = document.getElementsByTagName('base');
if (bases.length > 0) {
this._baseHref = bases[0].href;
}
}
else {
this._baseHref = '';
}
return this;
},
$get: ['$http', '$rootScope', '$window', '$q', '$log',
function ($http, $rootScope, $window, $q, $log) {
var _this = this;
return {
_dictionary: {},
_promises: {},
get debug() {
return _this.debug;
},
set debug(value) {
_this.debug = value;
return this;
},
get language() {
return _this.language || $window.navigator.userLanguage
|| $window.navigator.language || _this.defaultLanguage;
},
set language(lang) {
_this.language = lang;
return this;
},
get onTranslationFailed() {
return _this.onTranslationFailed;
},
set onTranslationFailed(func) {
_this.onTranslationFailed = func;
return this;
},
_checkSectionParameter: function (section) {
section = angular.isDefined(section) && section !== null ? section : 'all';
if (!angular.isString(section)) {
throw new Error('section parameter must be of type string');
}
if (!_this.allowPartialFileLoading && section !== 'all') {
throw new Error('Partial loading has been disabled by the provider.');
}
return section;
},
_getLanguageAndTranslate: function (value, section, placeholders) {
return this._translate(value, this.language, section, placeholders);
},
_translate: function (value, lang, section, placeholders) {
var translated;
// return an empty string for undefined value
if (value === undefined || value === null) {
return '';
}
section = this._checkSectionParameter(section);
placeholders = placeholders ? placeholders : [];
if (!this._dictionary || !this._dictionary[lang]) {
if (_this.fallback && typeof _this.fallback === "object" && _this.fallback[value]) {
translated = _this.fallback[value];
}
}
else {
//is it still loading
if (this.isTranslationLoading(lang, section)) {
return null; // mmMMMmmm. Patient you must be.
}
else {
//Is there the dictionary missing ?
if (!this.hasDictionary(lang, section))
{
throw new Error('The section you are trying to access does not exist');
}
//Is the section missing ?
if (!this.isTranslationLoaded(lang, section)) {
throw new Error('The section you are trying to access does not exist');
}
//Is the translation missing ?
if (!this.hasTranslation(lang, section, value))
{
throw new Error('The translation for \'' + value + '\' in the section \''
+ section + '\' for \'' + lang + '\' does not exist');
}
}
translated = this._dictionary[lang].sections[section].translation
? this._dictionary[lang].sections[section].translation[value]
: null;
}
if (translated === null) {
translated = vsprintf(value, placeholders);
}
else {
translated = vsprintf(translated, placeholders);
}
return translated;
},
hasDictionary: function (lang, section) {
return this.isTranslationLoaded(lang, section);
},
hasTranslation: function (lang, section, key) {
return (
this.isTranslationLoaded(lang, section)
&& this._dictionary[lang].sections[section].translation !== null
&& (angular.isDefined(key)
? this._dictionary[lang].sections[section].translation[key] !== undefined
: this._dictionary[lang].sections[section].translation !== null)
);
},
isTranslationLoading: function (lang, section) {
return (this._dictionary[lang]
&& this._dictionary[lang].sections[section]
&& (
this._dictionary[lang].sections[section].loading === true
));
},
isTranslationLoaded: function (lang, section) {
return (this._dictionary[lang]
&& this._dictionary[lang].sections[section]
&& (
this._dictionary[lang].sections[section].loaded === true
));
},
addTranslation: function (lang, json, section) {
if (!_this.allowPartialFileLoading && section !== 'all') {
throw new Error('Partial loading has been disabled by the provider.');
}
if (!this._dictionary[lang]) {
this._dictionary[lang] =
{
sections: {}
}
}
if (!this._promises[lang]) {
this._promises[lang] =
{
sections: {}
}
}
this._loadTranslationFileSucceed(json, lang, section);
},
removeTranslation: function (lang, section) {
section = angular.isDefined(section) && section !== null ? section : 'all';
if(!_this.allowPartialFileLoading)
{
if(section !== 'all')
{
throw new Error('removeTranslation: You cannot pass a section when not allowing partial file loading with allowPartialFileLoading()')
}
}
else if( !this.isTranslationLoaded(lang, section))
{
return;
}
delete this._dictionary[lang].sections[section];
},
switchTranslation: function(lang, section) {
section = angular.isDefined(section) && section !== null ? section : 'all';
this.language = lang;
this.loadTranslation(lang, section);
},
loadTranslation: function (lang, section) {
var self = this,
deferrer,
loadedFilePromise;
section = this._checkSectionParameter(section);
if (this._dictionary[lang]
&& this._dictionary[lang].sections[section]
&& (this._dictionary[lang].sections[section].loading === true
|| this._dictionary[lang].sections[section].loaded === true)) {
return;
}
// create the translation object
if (!this._dictionary[lang]) {
this._dictionary[lang] = {
sections: {}
};
}
this._dictionary[lang].sections[section] = {
loaded: false,
loading: true,
translation: null
};
// we will store the promise here.
if (!this._promises[lang]) {
this._promises[lang] = {sections: {}};
}
if (!this._promises[lang].sections[section]) {
this._promises[lang].sections[section] = {};
}
// create the promise we will return
deferrer = $q.defer();
loadedFilePromise = deferrer.promise;
loadedFilePromise.success = function (fn) {
loadedFilePromise.then(fn);
return loadedFilePromise;
};
loadedFilePromise.error = function (fn) {
loadedFilePromise.then(null, fn);
return loadedFilePromise;
};
var _loadTranslationFile = function (lang, section, urlIndex) {
var url;
if (angular.isArray(_this._fileURL)) {
urlIndex = angular.isDefined(urlIndex) ? urlIndex : 0;
url = _this._fileURL[urlIndex];
}
else {
url = _this._fileURL
}
url = url.replace(_this._fileURLLanguageToken, lang.replace('-', '_'));
if (_this._allowPartialFileLoading) {
if (!_this._fileURLPartToken.test(url)) {
throw new Error('The file URL hasn\'t defined a token for partial loading');
}
url = url.replace(_this._fileURLPartToken, section);
}
url = _this.baseHref + url;
return $http({method: "GET", url: url, cache: false})
.then(function (response) {
deferrer.resolve();
self._loadTranslationFileSucceed(response.data, lang, section);
},
function () {
if (angular.isNumber(urlIndex)) {
urlIndex++;
}
// we tried all the url none can be resolved
if (typeof _this._fileURL === 'string' || urlIndex === _this._fileURL.length) {
self._dictionary[lang].sections[section].loaded = true;
self._dictionary[lang].sections[section].loading = false;
self._dictionary[lang].sections[section].translation = null;
deferrer.reject('Could not reach any of the provided URL\'s');
var urls = angular.isArray(_this._fileURL) ? _this._fileURL.join(', ') : _this._fileURL;
for (var promiseObject in self._promises[lang].sections[section]) {
if (self._promises[lang].sections[section].hasOwnProperty(promiseObject)) {
self._promises[lang].sections[section][promiseObject]
.deferrer
.reject("Could not load translation files from " + urls);
delete self._promises[lang].sections[section][promiseObject];
}
}
}
// try the next url
else {
_loadTranslationFile(lang, section, urlIndex)
}
});
};
// if we have an array of urls try resolve until one is valid
_loadTranslationFile(lang, section);
return loadedFilePromise;
},
// loading translation file for current language succceed
_loadTranslationFileSucceed: function (data, lang, section) {
var self = this,
translation;
section = this._checkSectionParameter(section);
// store the returned array in the dictionary
self._dictionary[lang].sections[section] = {
loading: false,
loaded: true,
translation: data
};
// loop into any promises yet to be resolved for this language
if( self._promises[lang] && self._promises[lang] && self._promises[lang].sections[section])
{
for (var promiseObject in self._promises[lang].sections[section]) {
if (self._promises[lang].sections[section].hasOwnProperty(promiseObject)) {
try {
translation = self._translate.apply(self, self._promises[lang].sections[section][promiseObject].arguments);
self._promises[lang].sections[section][promiseObject].deferrer.resolve(translation);
}
catch (e) {
self._promises[lang].sections[section][promiseObject].deferrer.reject(e.message);
$log.error(e);
}
delete self._promises[lang].sections[section][promiseObject];
}
}
}
// broadcast that the file has been loaded
$rootScope.$broadcast('i18n.file.loaded', lang, section, data);
},
translate: function (value, section, placeholders) {
var self = this;
section = this._checkSectionParameter(section);
// define the language used when translation was called
var lang = self.language,
deferrer = null,
args = Array.prototype.slice.call(arguments);
// add the language to the argument array
args.splice(1, 0, lang);
var addPromise = function (value, lang, section, placeholders, instant) {
instant = typeof instant !== 'undefined' ? instant : false;
var deferrer = null,
promise = null;
// a promise exists for this value for this language returns it
if (self._promises[lang] &&
self._promises[lang].sections[section] &&
self._promises[lang].sections[section][value]
) {
return self._promises[lang].sections[section][value].deferrer;
}
// no promise exists for this value, create it
else {
deferrer = $q.defer();
promise = deferrer.promise;
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
if (!instant) {
self._promises[lang].sections[section][value] = {arguments: arguments, deferrer: deferrer};
}
return deferrer;
}
};
if (value === '') {
var failedDeferrer = addPromise(value, lang, section, placeholders, true);
failedDeferrer.reject('No translation IDs were provided');
return failedDeferrer.promise;
}
// we haven't load the file yet
if (!this._dictionary[lang]
|| (!this._dictionary[lang].sections[section])
|| (!this._dictionary[lang].sections[section].loading
&& !this._dictionary[lang].sections[section].loaded)) {
this.loadTranslation(lang, section);
}
// we have called the loading process but we are still waiting on the file
if (this._dictionary[lang].sections[section].loading) {
return addPromise(value, lang, section, placeholders).promise;
}
// the translation file finished loading
if (this._dictionary[lang]
&& !this._dictionary[lang].sections[section].loading
&& this._dictionary[lang].sections[section].loaded) {
deferrer = addPromise(value, lang, section, placeholders, true);
// unsuccessfully
if (this._dictionary[lang].sections[section].translation === null
|| typeof this._dictionary[lang].sections[section].translation !== "object") {
deferrer.reject("The translation file doesn't exist");
}
// successfully
else {
var translation;
try {
translation = self._translate(value, lang, section, placeholders);
deferrer.resolve(translation);
}
catch (e) {
deferrer.reject(e.message);
$log.error(e);
}
}
return deferrer.promise;
}
}
};
}]
};
}])
.filter('i18n', ['$i18n', '$sce', '$compile', '$log', function ($i18n, $sce, $compile, $log) {
var currentLanguage = null;
var myFilter = function (translationId, object) {
if (translationId && !angular.isString(translationId)) {
throw new Error('i18n filter error: The translation id must be a string');
}
object = object ? object : {};
if (angular.isDefined(object)) {
if (angular.isDefined(object.section) && !angular.isString(object.section)) {
throw new Error('i18n filter error: The section id must be a string');
}
if (angular.isDefined(object.placeholders)
&& Object.prototype.toString.call(object.placeholders) !== '[object Array]') {
throw new Error('i18n filter error: The placeholders must be an array');
}
}
// load translation file (if needed)
$i18n.loadTranslation($i18n.language, object.section, object.placeholders);
try {
var translation = $i18n._getLanguageAndTranslate.call($i18n, translationId, object.section, object.placeholders);
}
catch (e) {
if ($i18n.debug && $i18n.onTranslationFailed) {
translation = $sce.trustAsHtml($i18n.onTranslationFailed($i18n.language, translationId, object.section, object.placeholders));
$log.error(e);
}
else {
throw e;
}
}
return translation;
};
myFilter.$stateful = true;
return myFilter;
}])
.directive('i18n', ['$i18n', '$compile', '$log', function ($i18n, $compile, $log) {
return {
scope: {
i18n: '=',
i18nParameters: '=?'
},
priority: 0,
restrict: "A",
link: function (scope, elm, attrs) {
scope.i18nParameters = angular.extend({}, scope.i18nParameters);
$i18n.translate(scope.i18n, scope.i18nParameters.section, scope.i18nParameters.placeholders)
.success(function (translated) {
elm.text(translated)
})
.error(function (stringError) {
if ($i18n.debug && $i18n.onTranslationFailed) {
var translation = $i18n.onTranslationFailed($i18n.language, scope.i18n, scope.i18nParameters.section, scope.i18nParameters.placeholders);
elm.html(translation);
$compile(translation, scope);
$log.error(stringError);
}
else {
throw new Error(stringError);
}
})
}
}
}]);