Repository navigation
Expand file tree
/
Copy pathi18n-msg.html
More file actions
337 lines (270 loc) · 10 KB
/
Copy pathi18n-msg.html
File metadata and controls
337 lines (270 loc) · 10 KB
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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="observer.html">
<!-- Copyright Eric Bidelman <ebidel@gmail.com> -->
<!--
`<i18n-msg>` is a client-side solution for i18n message string replacement. It is modeled off the [Chrome extension i18n API](https://developer.chrome.com/extensions/i18n), which uses a `messages.json` file format.
The file contains localized strings for the language in question.
To set the language across your site, define `I18nMsg.lang` in your main page:
document.addEventListener('HTMLImportsLoaded', function() {
I18nMsg.lang = 'es';
// I18nMsg.url = 'locales'; // optionally use custom folder for locales.
Platform.performMicrotaskCheckpoint();
});
<b>Note:</b> this is done in `HTMLImportsLoaded` so `I18nMsg` will be defined by
the time you set `I18nMsg.lang`. This timing is necessary under the polyfill and is
<b>not needed if the browser supports HTML Imports</b>, natively.
<b>Note:</b> you must call `Platform.performMicrotaskCheckpoint()` whenever
making a change to the `I18nMsg` object. This is required due to the removal
of `Object.observe()`.
### Message files
Setting a language instructs `<i18n-msg>` to read message ids from a predefined
file on your server. For example, `I18nMsg.lang = 'es'` will use `locales/es.json`.
`I18nMsg.lang = 'fr'` would use message strings from `locales/fr.json`.
The directory name can be configured by using the `messagesUrl` property, but the file
cannot. `<i18n-msg>` will always attempt to use messages from `<messagesUrl>/<LANG_YOU_SET>.json`.
You can also set and/or change this location globally, at any time, by setting `I18nMsg.url`.
<b>Example</b> - using a custom locales folder, setting it globally for all `<i18n-msg>` instances:
I18nMsg.url = 'locales';
<b>Example</b> - set locales folder path on individual element:
<i18n-msg messages-url="path/to/locales">fallback text</i18n-msg>
<b>Note:</b> message files are read once and reused for all instances of `<i18n-msg>`.
### Fallback text
If an appropriate message file can't be found, the `textContent` of the element is used as fallback text.
<i18n-msg msgid="unknownmsgid">fallback text</i18n-msg>
### Placeholders
It's possible to insert text within the message which requires no translation (e.g: names, dates, numbers).
To make available the use of placeholders the message must contains $n (being n a numeric value) whenever a parameter
should be used, and to use these add the attribute "placeholders" and separate each parameter with ";;". Example:
JSON
"textwithplaceholders" {
"description" : "...",
"message" : "I am $0 and I live in $1"
}
HTML
<i18-msg msgid="textwithplaceholders" paremeters="John Doe;;Seattle"></i18n-msg>
It's also possible to use {{}} and [[]] within the placeholders.
### Full example
<html lang="es">
...
<body>
<p>"Days" in Spanish is <i18n-msg msgid="days">days</i18n-msg>!</p>
<script>
I18nMsg.lang = document.documentElement.lang || 'en';
</script>
</body>
</html>
### Getting a message:
// No argument returns the instance's message:
document.querySelector('i18n-msg').getMsg();
// Get a message by an id:
document.querySelector('i18n-msg').getMsg('days');
@demo
-->
<dom-module id="i18n-msg"></dom-module>
<script>
(function () {
window.I18nMsg = window.I18nMsg || {
lang: null,
url: 'locales',
locales: {}
};
var _instances = []; // Holds all i18n-msg elements to have them easily updated with translation messages.
var _fetching = false; // True if there's an outstanding XHR fetching a locale file.
var _numInstancesUpdated = 0;
Polymer({
is: 'i18n-msg',
/**
* The `i18n-language-ready` is fired after the locale was fetched and all `<i18n-msg>` elements were updated.
*
* @event i18n-language-ready
* @detail {{language: String}}
*/
properties: {
/**
* The message id (key) for this message.
*/
msgid: {
type: String,
value: null,
observer: '_msgidChanged'
},
/**
* Placeholders used to insert within the message if it contains replacement
* patterns to switch with. To use this feature you must include the "placeholders"
* attribute and use '' for the array and "" for each element.
* Example: placeholders = '["John Doe","Seattle"]'
*/
placeholders: {
type: Array,
value: [],
observer: '_placeholdersChanged'
},
/**
* The language being used.
*/
language: {
type: String,
value: null,
observer: '_languageChanged',
readOnly: true
},
/**
* The folder name where the localized `<lang>.json` files are located.
* Overrides `window.I18nMsg.url` if not `null`.
*/
messagesUrl: {
type: String,
value: 'locales'
},
/**
* The message in the current locale
*/
msg: {
type: String,
value: null,
notify: true
}
},
/**
* An object containing the set of known language locales that have been loaded.
*/
locales: {
type: Object,
value: I18nMsg.locales // static
},
ready: function() {
this.messagesUrl = I18nMsg.url;
this._setLanguage(I18nMsg.lang);
// Have instances observe window.I18nMsg.lang changes
// and go fetch the localized messages.json file.
var observerLang = new PathObserver(window.I18nMsg, 'lang');
observerLang.open(function(newValue, oldValue) {
_numInstancesUpdated = 0;
this._setLanguage(newValue);
}.bind(this));
// Have instances observe window.I18nMsg.url changes
// and go fetch the localized messages.json file.
var observerUrl = new PathObserver(window.I18nMsg, 'url');
observerUrl.open(function(newValue, oldValue) {
_numInstancesUpdated = 0;
this.messagesUrl = newValue;
// TODO: this will xhr the json file for each instance.
// if (!this.language || _fetching) {
// return;
// }
this._fetchLanguage();
}.bind(this));
_instances.push(this);
},
attached: function() {
var msg = this.getMsg(this.msgid)
if (msg) {
this.msg = msg;
this.innerHTML = msg;
}
},
/**
* Returns a message in the current locale (set by `window.I18nMsg.lang`).
* @method getMsg
* @param {string=} opt_msgId Optional message id to lookup. If left off,
* the instance's `msgid` property is used.
* @return {string|null} Translated message or `null` if not found.
*/
getMsg: function(opt_msgId) {
var msgId = opt_msgId || this.msgid;
var lang = this.locales[this.language];
if (lang && lang[msgId]) {
return lang[msgId].message;
}
return null;
},
_msgidChanged: function() {
if (this.language && this.locales[this.language] && !_fetching && this.msgid) {
this._updateElementMessage();
}
},
_placeholdersChanged: function() {
if (this.language && this.locales[this.language] && this.placeholders) {
this._updateElementMessage(this);
}
},
_languageChanged: function() {
// Don't fetch .json file if it has already been
// fetched or another instance is already trying to.
if (this.language && this.locales[this.language] && !_fetching) {
// Send one signal that language changed to outside.
if (_numInstancesUpdated == _instances.length - 1) {
this.fire('i18n-language-ready', {language: this.language});
}
this._updateElementMessage();
_numInstancesUpdated++;
return;
} else if (!this.language || this.locales[this.language] || _fetching) {
return;
}
this._fetchLanguage();
},
_fetchLanguage: function() {
// if (_fetching) {
// return;
// }
_fetching = true;
var url = /*this.baseURI + */this.messagesUrl + '/' + this.language + '.json';
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function(e) {
_fetching = false;
if (e.target.status !== 200 && e.target.status !== 0) {
return;
}
var resp = JSON.parse(e.target.response);
if (!this.msgid in resp) {
console.warn(this.localName + ': "' + this.msgid + '" message id was not found in ' + url);
return;
}
this.locales[this.language] = resp; // cache this locale.
this._notifyInstances();
this.fire('i18n-language-ready', {language: this.language});
}.bind(this);
xhr.onerror = function(e) {
_fetching = false;
};
xhr.send();
},
_updateElementMessage: function(opt_instance) {
var instance = opt_instance || this;
var msg = instance.locales[instance.language][instance.msgid];
if (msg && msg.message) {
var message = msg.message;
var placeholders = msg.placeholders;
var phData = instance.placeholders;
if ((placeholders) && (phData)) {
var content, pos;
for (var p in placeholders) {
content = placeholders[p].content;
if (content[0] == '$') {
pos = content.substring(1, content.length);
if (!isNaN(pos)) {
content = (phData.length < pos) ? '' : phData[pos - 1];
}
}
message = message.split('$' + p + '$').join(content);
}
}
instance.msg = msg.message;
instance.innerHTML = message;
}
},
_notifyInstances: function() {
for (var i = 0, instance; instance = _instances[i]; ++i) {
instance._setLanguage(I18nMsg.lang);
if (!instance.locales[instance.language][instance.msgid]) {
console.warn(this.localName + ': "' + instance.msgid + '" message id was not found');
continue;
}
this._updateElementMessage(instance);
}
}
});
})();
</script>