/
i18n.js
executable file
·746 lines (675 loc) · 19.3 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
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
/**
* Internationalisation tools
* @module ys/i18n
* @requires base, cache, get
*/
var
NS = 'ys',
DEFAULT_LOCALE = 'en_US',
CACHE_LOCALE = 'loc',
locale_cache = new Y.CacheOffline({
sandbox: (Y.config.cacheprefix || '')+'locale'
}),
/**
* I18n object for an unique translation
*/
I18n = function(config)
{
I18n.superclass.constructor.apply(this, arguments);
},
/**
* Manager of all translation in the app
*/
I18nManager = function(config)
{
I18nManager.superclass.constructor.apply(this, arguments);
};
/**
* Whitelisting the DOMNodeRemovedFromDocument event to use it on
* I18n's node destruction
*/
Y.mix(Y.Node.DOM_EVENTS, {
DOMNodeRemovedFromDocument: true
});
/**
* I18n object helps to get a live translation of text.
* @class I18nManager.I18n
* @namespace Y.ys
* @extends Y.Base
* @constructor
* @param {Object} config Object with configuration property name/value
* pairs. The object can be used to provide default values for the objects
* published attributes.
*
* <p>
* The config object can also contain the following non-attribute
* properties, providing a convenient way to configure events listeners and
* plugins for the instance, as part of the constructor call:
* </p>
*
* <dl>
* <dt>params</dt>
* <dd>Object of name/value text to replace @@name@@ into
* translation</dd>
* <dt></dt>
* </dl>
*/
Y.extend(I18n, Y.Base, {
/**
* Autokill flag. Set to false if you don't want your I18n object to be
* destroyed when Node is not present in DOM.
* @property _autokill
* @private
*/
_autokill: true,
/**
* Initialize a i18n object
* @method initializer
* @protected
*/
initializer: function(config)
{
/**
* Add new attrs for each params in the params attr
* and call insertTranslation method on one of them change
*/
if (config.params)
{
Y.each(
config.params,
function(v, k)
{
this.addAttr(k, {broadcast: 1});
this.after(
k+'Change',
function()
{
this._insertTranslation();
},
this
);
},
this
);
this.setAttrs(config.params);
}
/**
* After locale change, call the changeLanguage method to update the
* node
*/
this.after(
'localeChange',
function(e)
{
this.getLocalizedString();
}
);
/**
* Set translation in node asynchronously
*/
this.after(
'translationChange',
function(e)
{
this._insertTranslation();
}
);
this._checklife = Y.later(
5000,
this,
function()
{
if (this._autokill &&
!Y.one('#'+this.get('id')))
{
this.destroy();
// IE <= 8 seems to have problems with this delete
try
{
delete this;
}
catch(e)
{}
}
},
null,
true
);
},
destructor: function()
{
this._checklife.cancel();
},
/**
* Load the translations file, and get the localized string from the key
* Call is asynchronized, so it will update `translation` attr when
* it'll be load, and so, fire `translationChange` event.
* @method getLocalizedString
* @public
*/
getLocalizedString: function()
{
Y.namespace(NS).I18nManager.getLocalizedString({
key: this.get('key'),
locale: this.get('locale'),
callback: Y.bind(
function(text)
{
this.set(
'translation',
text
);
},
this
)
});
},
/**
* Get a localized string from key
* key has the form : 'module~key'
* @method localize
* @param {boolean} tostring Set to true if you want a node as a string
* to set as innerHTML of a parent node. Default is Y.Node object to
* be append in a parent node. You can set a
* callback function to do whatever you want with the translation when it's
* loaded. The callback will be called everytime the translation change.
* @return Y.Node|string
* @public
*/
localize: function(tostring)
{
var node, t;
/**
* Load the locale
*/
this.getLocalizedString();
t = this._insertTranslation();
/**
* Create the string node
*/
node = '<span id="'+this.get('id')+'">'+
t+
'</span>';
/**
* Create a node from the string
*/
if (tostring !== true)
{
node = Y.Node.create(node);
node.i18n = this;
this.set('node', node);
}
/**
* A callback has been given. This callback will be called everytime the
* translation change. The callback take the translation as first param.
*/
if (typeof tostring === 'function')
{
this._autokill = false;
this.after(
'translationChange',
function(e, fn)
{
fn(this._insertTranslation());
},
this,
tostring
);
tostring(t);
}
/**
* If tostring is true, a string will returned instead of a Node
* object. It's usefull for templates not already instancied.
*/
return node;
},
/**
* Get node from attr or from dom
* @method getNode
* @return Y.Node
* @public
*/
getNode: function()
{
var node = this.get('node');
if (!node)
{
/**
* No node set, try to get it in DOM from the ID given to the
* string node
*/
node = Y.one('#'+this.get('id'));
this.set('node', node);
}
return node;
},
/**
* Replace translation string with uptodate params in the node span
* container
* @method _insertTranslation
* @return string
* @protected
*/
_insertTranslation: function()
{
var node = this.getNode()
t = this.get('translation');
t = t && t.replace(
/@@(.[^(@@)]*?)@@/gi,
Y.bind(
function(a, b)
{
var v = this.get(b);
return v ? v : '';
},
this
),
t
);
if (node)
{
try
{
node.set(
'innerHTML',
t
);
}
catch(e)
{
node.set(
'innerText',
t
);
}
node.fire('i18n:change', {translation: t});
}
return t;
},
/**
* Destruct the node and purge all its events listeners
* @method destructor
* @protected
*/
destructor: function()
{
var node = this.get('node');
if (node)
{
Y.Event.purgeElement(node, true);
node.remove();
}
}
},
{
NAME: 'I18n',
ATTRS: {
/**
* A random GUID generated at the instanciation
* @attribute id
* @private
*/
id: {
valueFn: function()
{
return Y.guid();
}
},
/**
* Language code for the translation
* @attribute locale
* @public
*/
locale: {
value: null,
/**
* Fired when locale code has changed
* @event localeChange
*/
broadcast: 1
},
/**
* Translation key
* @attribute key
* @public
*/
key: {
value: null
},
/**
* Container node
* @attribute node
* @private
*/
node: {
setter: function(n)
{
if (n)
{
n.on(
'DOMNodeRemovedFromDocument',
function()
{
this.set('node', null);
this.destroy();
},
this
);
n.destroy = Y.bind(
function()
{
this.destroy();
},
this
);
}
return n;
}
},
/**
* Translation text
* @attribute translation
* @public
*/
translation: {
value: ' ', /* fix a bug with chrome when sometime an empty
* span filled later doesn't change its content
* size
*/
/**
* Fired when translated text has changed
* @event translationChange
*/
broadcast: 1
}
}
});
/**
* I18nManager helps to create new translations and globally set locale code
* @class I18nManager
* @namespace Y.ys
* @extends Y.Base
* @constructor
*/
Y.extend(I18nManager, Y.Base, {
_locales: null,
_loading: null,
/**
* Initialize the manager and set the default locale code : from the
* browser or from the app_config
* @method initializer
* @protected
*/
initializer: function()
{
this._locales = {};
this._loading = {};
/**
* Bind locale change event to set all the instancied I18n locale
*/
this.after(
'localeChange',
function()
{
var keys = this.get('keys'),
locale = this.get('locale');
Y.each(
keys,
function(I18n)
{
if (I18n)
{
I18n.set('locale', locale);
}
}
);
},
this
);
},
/**
* Get a localized string from key
* key has the form : 'module~key'
* @method localize
* @param {string} key The key of the locale to translate. Must have the
* form `file~key`. `key` can have /[a-zA-Z0-9\.\-_]/ characters.
* @param {object} params Parameters to give to the translation. The
* translation must have some @@name@@ keyword to place the parameter.
* @param {boolean|Function} tostring True if you want a string to insert in
* a innerHTML. Default if you want a Y.Node to append in DOM. You can set a
* callback function to do whatever you want with the translation when it's
* loaded. The callback will be called everytime the translation change.
* @example <pre>
* __('file~key', null, Y.bind(
* function(text)
* {
* this.one('input').setAttribute('placeholder', text);
* },
* this
* ));
* // The placeholder attribute will be updated when the locale will be
* // loaded and everytime the use change the global locale.
* </pre>
* @return string|Y.Node
* @public
*/
localize: function(key, params, tostring)
{
var el = this.createKey(key, params);
params || (params = {});
return el.localize(tostring);
},
/**
* Create a new key
* @method createKey
* @param {string} key The key of the locale to translate. Must have the
* form `file~key`. `key` can have /[a-zA-Z0-9\.\-_]/ characters.
* @param {object} params Parameters to give to the translation. The
* translation must have some @@name@@ keyword to place the parameter.
* @return Y.ys.I18n
* @public
*/
createKey: function(key, params)
{
var i = new I18n({
key: key,
locale: this.get('locale'),
params: params
}),
keys = this.get('keys');
keys[i.get('id')] = i;
this.set('keys', keys);
return i;
},
_loadLocales: function(locale, callback)
{
if (this._loading[locale])
{
this._loading[locale].push(callback);
return;
}
this._loading[locale] = [callback];
Y.Get.script(
(Y.config.localepath || '/locales/') +locale+'.js',
{
onSuccess: Y.bind(
function(locale)
{
var locales = window['__ys_locales_'+locale];
this._locales[locale] = Y.clone(locales);
try{
delete window['__ys_locales_'+locale];
}
catch(e)
{
window['__ys_locales_'+locale] = null;
}
Y.each(
this._loading[locale],
function(fn)
{
fn();
}
);
this._loading[locale] = [];
},
this,
locale
)
}
);
},
getLocalizedString: function(config)
{
config = config || {};
var locale = config.locale || this.get('locale'),
locales = this._locales[locale],
key = config.key,
text;
if (!key) return;
if (!locales)
{
return this._loadLocales(
this.get('locale'),
Y.bind(
this.getLocalizedString,
this,
{
key: key,
callback: config.callback
}
)
);
}
text = locales[key.replace(/~/, '.')];
if (!text)
{
Y.log('undefined locale : '+key);
}
config.callback && config.callback(text);
return text;
}
},
{
NAME: 'I18nManager',
ATTRS: {
/**
* Global language configuration
* @attribute locale
* @public
*/
locale: {
valueFn: function()
{
var clocale = locale_cache.retrieve(CACHE_LOCALE);
return clocale ?
clocale.response :
(navigator.language || navigator.userLanguage || DEFAULT_LOCALE);
},
/**
* Function to set the locale after verifying its validity. Set the
* default if invalid
* @method set('locale')
* @public
*/
setter: function(locale)
{
var found = false,
dft = navigator.language || navigator.userLanguage || DEFAULT_LOCALE;
/**
* Look into config if asked locale is available
*/
if (Y.config.locales)
{
Y.Array.some(
Y.config.locales,
function(l)
{
if (l.locale === locale)
{
locale = l.locale;
return (found = true);
}
if (l.sameas)
{
Y.Array.some(
l.sameas,
function(s)
{
if (s === locale)
{
locale = l.locale;
return (found = true);
}
}
);
}
if (true === l['default'])
{
dft = l.locale
}
return found;
}
);
/**
* Looking for locale name in 2 caracters
*/
if (!found && Y.Lang.isString(locale))
{
locale = locale.substring(0,2);
Y.Array.some(
Y.config.locales,
function(l)
{
if (l.locale.substring(0,2) === locale)
{
locale = l.locale;
return (found = true);
}
return found;
}
);
}
}
if (!found)
{
locale = dft;
}
locale_cache.add(CACHE_LOCALE, locale);
return locale;
},
/**
* Fired when the locale has been changed
* @event localeChange
*/
broadcast: 1
},
/**
* Collection of I18n objects
* @attribute keys
* @protected
*/
keys: {
valueFn: function()
{
return {};
}
}
}
});
/**
* Instanciate new I18nManager in the ys namespace
*/
Y.namespace(NS).I18nManager = new I18nManager();
Y.namespace(NS).I18nManager.I18n = I18n;
/**
* Create a usefull global function : __()
* @method window.__
* @param {string} key Translation key
* @param {object} param Object of params to give to the locale
* @param {boolean} tostring Do you want a Node or a string ?
*/
window.__ = function(key, params, tostring)
{
return Y.ys.I18nManager.localize(key, params, tostring);
};