-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
110 lines (91 loc) · 2.88 KB
/
index.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
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'riot'], function (exports, riot) {
factory((root.i18n = exports), riot);
});
} else if (typeof exports === 'object') {
// CommonJS
factory(exports, require('riot'));
} else {
// Browser globals
factory((root.i18n = {}), root.riot);
}
}(this, function (exports, riot) {
var DEFAULT_LANG = 'en';
function I18n() {
this._entities = {}
this._default = DEFAULT_LANG
this._language = this._default
var obs = riot.observable()
this.on = obs.on
this.off = obs.off
this.trigger = obs.trigger
this.on('lang', this.setLanguage)
}
I18n.prototype.dictionary = function(dict) {
this._entities = dict;
}
I18n.prototype.defaultLanguage = function(lang) {
this._default = lang;
}
I18n.prototype.localise = function(key, data) {
var substitute, locale;
function flatten(n, f, d, k) {
k = k || "", f = f || {}, d = d || 0
var nObj = n && !n.length,
nKeys = nObj ? Object.keys(n).length : 0;
if (nObj && nKeys > 0) {
var i;
for (i in n) {
if (k.split('.').length > d) { k = k.split('.').splice(0, d).join('.') }
k = (d == 0) ? i : k + "." + i, f = flatten(n[i], f, d + 1, k)
}
} else f[k] = n;
return f;
}
if (!this._entities[this._language]) {
// When a language is not provided,
// treat the key as substitution
substitute = key;
}
if (!substitute) {
locale = flatten(this._entities[this._language]);
if (!locale[key]) {
// When a translation is not
// provided, just return the original text.
substitute = key
} else {
// return the language substitue for the original text
substitute = locale[key];
}
}
if (data) {
var _data = flatten(data),
_key;
for (_key in _data) {
substitute = substitute.replace(new RegExp("{" + _key + "}", "g"), _data[_key]);
}
}
return substitute;
}
I18n.prototype.setLanguage = function(lang) {
this._language = lang || this._default
this.trigger('update')
}
I18n.prototype.getLanguage = function() {
return this._language
}
var i18n = new I18n(),
property;
for (property in i18n) {
exports[property] = i18n[property];
}
riot.mixin('i18n', { i18n: exports })
//
//
// BEGIN RIOT TAGS
// END RIOT TAGS
//
//
}));