Debian Codegraph @

resources/lib/jquery.i18n/README.md

raw symbols SCIP
1 jQuery.i18n
2 ===========
3
4 [![npm][npm]][npm-url]
5
6 > NOTE: For jquery independent version of this library, see https://github.com/wikimedia/banana-i18n
7
8 jQuery.i18n is a jQuery based JavaScript internationalization library. It helps you to internationalize your web applications easily.
9
10 This is a project by Wikimedia foundation's [Language Engineering team](https://www.mediawiki.org/wiki/Wikimedia_Language_engineering) and used in some of the Wikimedia Foundation projects like Universal Language Selector.
11
12 The jquery.i18n library uses a json based localization file format, "banana", which is used as the localization file format for MediaWiki and other projects.
13
14
15 Features
16 ========
17 * Simple file format - JSON. Easily readable for humans and machines.
18 * Author and metadata information is not lost anywhere. There are other file formats using comments to store this.
19 * Uses MediaWiki convention for placeholders. Easily readable and proven convention. Example: ```There are $1 cars```
20 * Supports plural conversion without using extra messages for all plural forms. Plural rule handling is done using CLDR. Covers a wide range of languages
21 * Supports gender. By passing the gender value, you get correct sentences according to gender.
22 * Supports grammar forms. jquery.i18n has a basic but extensible grammar conversion support
23 * Fallback chains for all languages.
24 * Data api- the message key. Example: ```<li data-i18n="message-key"></li>```.
25 * Dynamic change of interface language without refreshing a webpage.
26 * Nestable grammar, plural, gender support. These constructs can be nested to any arbitrary level for supporting sophisticated message localization
27 * Message documentation through special language code ```qqq```
28 * Extensible message parser to add or customize magic words in the messages. Example: ```{sitename}``` or ```[[link]]```
29
30
31 Quick start
32 -----------
33
34 ```bash
35 git clone https://github.com/wikimedia/jquery.i18n.git
36 cd jquery.i18n
37 git submodule update --init
38 ```
39
40 Testing
41 -------
42
43 ```shell
44 npm install
45 ```
46
47 To run tests locally, run `npm test`, and this will run the tests.
48
49 Running demo
50 -------
51
52 ```bash
53 # If you're using python3, open demo as a local server using port 8000
54 python -m http.server
55 # If you're using python2, use this command instead
56 # python -m SimpleHTTPServer
57
58 ```
59 Open `localhost:8000/demo` in your browser, you can see the demo index page.
60
61
62 Message File Format
63 ===================
64
65 The message files are json formatted. As a convention, you can have a folder named i18n inside your source code. For each language or locale, have a file named like languagecode.json.
66
67 Example:
68 ```
69 App
70 |--src
71 |--doc
72 |--i18n
73 |--ar.json
74 |--de.json
75 |--en.json
76 |--he.json
77 |--hi.json
78 |--fr.json
79 |--qqq.json
80 ```
81
82 A simple en.json file example is given below
83
84 ```json
85 {
86 "@metadata": {
87 "authors": [
88 "Alice",
89 "David",
90 "Santhosh"
91 ],
92 "last-updated": "2012-09-21",
93 "locale": "en",
94 "message-documentation": "qqq",
95 "AnotherMetadata": "AnotherMedatadataValue"
96 },
97 "appname-title": "Example Application",
98 "appname-sub-title": "An example application with jquery.i18n",
99 "appname-header-introduction": "Introduction",
100 "appname-about": "About this application",
101 "appname-footer": "Footer text"
102 }
103 ```
104
105 The json file should be a valid json. The ```@metadata``` holds all kind of data that are not messages. You can store author information, copyright, updated date or anything there.
106
107 Messages are key-value pairs. It is a good convention to prefix your appname to message keys to make the messages unique. It acts as the namespace for the message keys. It is also a good convention to have the message keys with ```-``` separated words, all in lower case.
108
109 If you are curious to see some real jquery.i18n message file from other projects:
110
111 - message files of MediaWiki https://github.com/wikimedia/mediawiki/tree/master/languages/i18n
112 - message files from jquery.uls project https://github.com/wikimedia/jquery.uls/tree/master/i18n
113
114 Single message file for all languages
115 -------------------------------------
116 There are some alternate message file formats supported for different use cases. If your application is not big, and want all the translation in a single file, you can have it as shown in the below example:
117
118 ```json
119 {
120 "@metadata": {
121 "authors": [
122 "Alice",
123 "David",
124 "Santhosh"
125 ],
126 "last-updated": "2012-09-21",
127 "locale": "en",
128 "message-documentation": "qqq",
129 "AnotherMetadata": "AnotherMedatadataValue"
130 },
131 "en": {
132 "appname-title": "Example Application",
133 "appname-sub-title": "An example application with jquery.i18n",
134 "appname-header-introduction": "Introduction",
135 "appname-about": "About this application",
136 "appname-footer": "Footer text"
137 },
138 "ml": {
139 "appname-title": "അപ്ലിക്കേഷന്‍ ഉദാഹരണം",
140 "appname-sub-title": "jquery.i18n ഉപയോഗിച്ചുള്ള അപ്ലിക്കേഷന്‍ ഉദാഹരണം",
141 "appname-header-introduction": "ആമുഖം",
142 "appname-about": "ഈ അപ്ലിക്കേഷനെപ്പറ്റി",
143 "appname-footer": "അടിക്കുറിപ്പു്"
144 }
145 }
146 ```
147
148 Here the json file contains language code as key-value and messagekey-message pairs as the value for all language pairs. You can choose this format or per-language file formats depending on your use case. Per-language files are more convenient for collaboration, version controlling, scalability, etc.
149
150 In this approach, it is also possible to give a file name as the value of language code.
151
152 ```json
153 {
154 "@metadata": {
155 "authors": [
156 "Alice",
157 "David",
158 "Santhosh"
159 ],
160 "last-updated": "2012-09-21",
161 "locale": "en",
162 "message-documentation": "qqq",
163 "AnotherMetadata": "AnotherMedatadataValue"
164 },
165 "en": {
166 "appname-title": "Example Application",
167 "appname-sub-title": "An example application with jquery.i18n",
168 "appname-header-introduction": "Introduction",
169 "appname-about": "About this application",
170 "appname-footer": "Footer text"
171 },
172 "ml": "path/to/ml.json"
173 }
174 ```
175
176 Translation
177 ===========
178 To translate the jquery.i18n application, depending on the expertise of the translator, there are multiple ways.
179
180 * Editing the json files directly - Suitable for translators with technical background. Also suitable if your application is small and you want to work with only a small number of languages
181 * Providing a translation interface along with your application: Suitable for proprietary or private applications with significant amount of translators
182 * Using open source translation platforms like translatewiki.net. The MediaWiki and jquery.uls from previous examples use translatewiki.net for crowdsourced message translation. Translatewiki.net can update your code repo at regular intervals with updated translations. Highly recommended if your application is opensource and want it to be localized to as many as languages possible with maximum number of translators.
183
184 Usage
185 =====
186
187 ## Switching locale
188
189 While initializing the `jquery.i18n`, the locale for the page can be given using the `locale` option. For example
190
191 ```javascript
192 $.i18n( {
193 locale: 'he' // Locale is Hebrew
194 } );
195 ```
196
197 In case locale option is not given, `jquery.i18n` plugin will use the language attribute given for the html tag. For example
198
199 ```html
200 <html lang="he" dir="rtl">
201 ```
202
203 In this case, the locale will be he(Hebrew). If that `lang` attribute is also missing, it will try to use the locale specified by the browser.
204
205 It is possible to switch to another locale after plugin is initialized. See below example:
206
207 ```javascript
208 $.i18n({
209 locale: 'he' // Locale is Hebrew
210 });
211 $.i18n( 'message-hello' ); // This will give the Hebrew translation of message key `message-hello`.
212 $.i18n().locale = 'ml'; // Now onwards locale is 'Malayalam'
213 $.i18n( 'message-hello' ); // This will give the Malayalam translation of message key `message-hello`.
214 ```
215
216 ## Message Loading
217
218 JSON formatted messages can be loaded to the plugin using multiple ways.
219
220 ### Dynamic loading using `load` method.
221
222 Following example shows loading messages for two locales- localex, and localey. Here localex and localey are just examples. They should be valid IS0 639 language codes(eg: en, ml, hi, fr, ta etc)
223
224 ```javascript
225 $.i18n().load( {
226 'localex' : {
227 'message-key1' : 'message1' // Message for localex.
228 },
229 'localey' : {
230 'message-key1' : 'message1'
231 }
232 } );
233 ```
234
235 If we want to load the messages for a specific locale, it can be done like this:
236
237 ```javascript
238 $.i18n().load({
239 'message-hello': 'Hello World',
240 'message-welcome': 'Welcome'
241 }, 'en');
242 ```
243
244 Note the second argument for the `load` method. It should be a valid language code.
245
246 It is also possible to refer messages from an external URL. See below example
247
248 ```javascript
249 $.i18n().load( {
250 en: {
251 'message-hello': 'Hello World',
252 'message-welcome': 'Welcome'
253 },
254 hi: 'i18n/messages-hi.json', // Messages for Hindi
255 de: 'i18n/messages-de.json'
256 } );
257 ```
258
259 Messages for a locale can be also loaded in parts. Example
260
261 ```javascript
262 $.i18n().load( {
263 en: {
264 'message-hello': 'Hello World',
265 'message-welcome': 'Welcome'
266 }
267 } );
268
269 $.i18n().load( {
270 // This does not remove the previous messages.
271 en: {
272 'message-header' : 'Header',
273 'message-footer' : 'Footer',
274 // This will overwrite message-welcome message
275 'message-welcome' : 'Welcome back'
276 }
277 } );
278 ```
279
280 Since it is desirable to render interface messages instantly and not after a delay of loading the message files from a server, make sure that the messages are present at client side before using jQuery.i18n.
281
282 The library should expose an API to load an object containing key-value pair of messages. Example: ```$.i18n.load(data)```. This will return a ```jQuery.Promise```.
283
284 jquery.i18n plugin
285 =========================
286
287 The jQuery plugin defines ```$.i18n()``` and ```$.fn.i18n()```
288
289 ```javascript
290 $.i18n( 'message-key-sample1' );
291 $.i18n( 'message-key-sample1' );
292 $.i18n( 'Found $1 {{plural:$1|result|results}}', 10 ); // Message key itself is message text
293 $.i18n( 'Showing $1 out of $2 {{plural:$2|result|results}}', 5,100 );
294 $.i18n( 'User X updated {{gender|his|her}} profile', 'male' );
295
296 $( '#foo' ).i18n(); // to translate the element matching jquery selector based on data-i18n key
297 ```
298
299 Data API
300 --------
301
302 It is possible to display localized messages without any custom JavaScript. For the HTML tags, add an attribute data-i18n with value as the message key. Example:
303 ```html
304 <li data-i18n="message-key"></li>.
305 ```
306
307 It is also possible to have the above li node with fallback text already in place.
308 ```html
309 <li data-i18n="message-key">Fallback text</li>
310 ```
311
312 The framework will place the localized message corresponding to message-key as the text value of the node. Similar to $('selector').i18n( ... ).
313 This will not work for dynamically created elements.
314
315 Note that if data-i18n contains html markup, that html will not be used as the element content, instead, the text version will be used. But if the message key is prefixed with `[html]`, the element's html will be changed. For example ```<li data-i18n="[html]message-key">Fallback html</li>```, in this if the message-key has a value containing HTML markup, the `<li>` tags html will be replaced by that html.
316
317
318 If you want to change the html of the element, you can also use: ```$(selector).html($.i18n(messagekey))```
319
320 Examples
321 ========
322
323 See https://thottingal.in/projects/js/jquery.i18n/demo/
324
325 Message format
326 ==============
327
328 ## Placeholders
329
330 Messages take parameters. They are represented by $1, $2, $3, … in the message texts, and replaced at run time. Typical parameter values are numbers (Example: "Delete 3 versions?"), or user names (Example: "Page last edited by $1"), page names, links, and so on, or sometimes other messages.
331
332 ```javascript
333 var message = "Welcome, $1";
334 $.i18n(message, 'Alice'); // This gives "Welcome, Alice"
335 ```
336
337
338 ## Plurals
339
340 To make the syntax of sentence correct, plural forms are required. jquery.i18n support plural forms in the message using the syntax `{{PLURAL:$1|pluralform1|pluralform2|...}}`
341
342 For example:
343
344 ```javascript
345 var message = "Found $1 {{PLURAL:$1|result|results}}";
346 $.i18n(message, 1); // This gives "Found 1 result"
347 $.i18n(message, 4); // This gives "Found 4 results"
348 ```
349 Note that {{PLURAL:...}} is not case sensitive. It can be {{plural:...}} too.
350
351 In case of English, there are only 2 plural forms, but many languages use more than 2 plural forms. All the plural forms can be given in the above syntax, separated by pipe(|). The number of plural forms for each language is defined in [CLDR](https://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html). You need to provide all those plural forms for a language. Please note that many languages will require the inclusion of `CLDRPluralRuleParser.js` ([from here](https://github.com/santhoshtr/CLDRPluralRuleParser/tree/8baf9aedc428924fe6ee508b3d952cb5564efb3a/src)) as well as this project's own files to work properly.
352
353 For example, English has 2 plural forms and the message format will look like `{{PLURAL:$1|one|other}}`. for Arabic there are 6 plural forms and format will look like `{{PLURAL:$1|zero|one|two|few|many|other}}`.
354
355 You cannot skip a plural form from the middle or beginning. However, you can skip from end. For example, in Arabic, if the message is like
356 `{{PLURAL:$1|A|B}}`, for 0, A will be used, for numbers that fall under one, two, few, many, other categories B will be used.
357
358 If there is an explicit plural form to be given for a specific number, it is possible with the following syntax
359
360 ```
361 var message = 'Box has {{PLURAL:$1|one egg|$1 eggs|12=a dozen eggs}}.';
362 $.i18n(message, 4 ); // Gives "Box has 4 eggs."
363 $.i18n(message, 12 ); // Gives "Box has a dozen eggs."
364 ```
365
366 ## Gender
367 Similar to plural, depending on gender of placeholders, mostly user names, the syntax changes dynamically. An example in English is "Alice changed her profile picture" and "Bob changed his profile picture". To support this {{GENDER...}} syntax can be used as shown in example
368
369 ```javascript
370 var message = "$1 changed {{GENDER:$2|his|her}} profile picture";
371 $.i18n(message, 'Alice', 'female' ); // This gives "Alice changed her profile picture"
372 $.i18n(message, 'Bob', 'male' ); // This gives "Bob changed his profile picture"
373 ```
374
375 Note that {{GENDER:...}} is not case sensitive. It can be {{gender:...}} too.
376
377 ## Grammar
378
379
380 ```javascript
381 $.i18n( { locale: 'fi' } );
382
383 var message = "{{grammar:genitive|$1}}";
384
385 $.i18n(message, 'talo' ); // This gives "talon"
386
387 $.i18n().locale = 'hy'; // Switch to locale Armenian
388 $.i18n(message, 'Մաունա'); // This gives "Մաունայի"
389 ```
390
391 ## Directionality-safe isolation
392
393 To avoid BIDI corruption that looks like "(Foo_(Bar", which happens when a string is inserted into a context with the reverse directionality, you can use `{{bidi:…}}`. Directionality-neutral characters at the edge of the string can get wrongly interpreted by the BIDI algorithm. This would let you embed your substituted string into a new BIDI context, //e.g.//:
394
395 "`Shalom, {{bidi:$1}}, hi!`"
396
397 The embedded context's directionality is determined by looking at the argument for `$1`, and then explicitly inserted into the Unicode text, ensuring correct rendering (because then the bidi algorithm "knows" the argument text is a separate context).
398
399
400 Fallback
401 ========
402
403 The plugin takes an option 'fallback' with the default value 'en'. The library reuses the fallback data available in MediaWiki for calculating the language fallbacks. Fallbacks are used when a message key is not found in a locale. Example fallbacks: sa->hi->en or tt->tt-cyrl->ru.
404
405 See jquery.i18n.fallbacks.js in the source.
406
407 Magic word support
408 ===================
409 * For plural, gender and grammar support, MediaWiki template-like syntax - {{...}} will be used.
410 * There will be a default implementation for all these in $.i18n.language['default']
411 * The plural, gender and grammar methods in ```$.i18n.language[ 'default' ]``` can be overridden or extended in ```$.i18n.language['languageCode']```.
412 * Language-specific rules about Gender and Grammar can be written in languages/langXYZ.js files
413 * Plural forms will be dynamically calculated using the CLDR plural parser.
414
415 Extending the parser
416 --------------------
417 Following example illustrates extending the parser to support more magic words
418
419 ```javascript
420 $.extend( $.i18n.parser.emitter, {
421 // Handle SITENAME keywords
422 sitename: function () {
423 return 'Wikipedia';
424 },
425 // Handle LINK keywords
426 link: function ( nodes ) {
427 return '<a href="' + nodes[1] + '">' + nodes[0] + '</a>';
428 }
429 } );
430 ```
431
432 This will parse the message
433 ```javascript
434 $.i18n( '{{link:{{SITENAME}}|https://en.wikipedia.org}}' );
435 ```
436
437 to
438
439 ```html
440 <a href="https://en.wikipedia.org">Wikipedia</a>
441 ```
442
443 Message documentation
444 =====================
445
446 The message keys and messages won't give a enough context about the message being translated to the translator. Whenever a developer adds a new message, it is a usual practice to document the message to a file named qqq.json
447 with same message key.
448
449 Example qqq.json:
450 ```json
451 {
452 "@metadata": {
453 "authors": [
454 "Developer Name"
455 ]
456 },
457 "appname-title": "Application name. Transliteration is recommended",
458 "appname-sub-title": "Brief explanation of the application",
459 "appname-header-introduction": "Text for the introduction header",
460 "appname-about": "About this application text",
461 "appname-footer": "Footer text"
462 }
463
464 ```
465
466 In MediaWiki and its hundreds of extensions, message documentation is a strictly followed practice. There is a grunt task to check whether all messages are documented or not. See https://www.npmjs.org/package/grunt-banana-checker
467
468 [npm]: https://img.shields.io/npm/v/@wikimedia/jquery.i18n.svg
469 [npm-url]: https://npmjs.com/package/@wikimedia/jquery.i18n