2 * Copyright 2016-2017 ZTE, Inc. and others.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 /******************************************************************************
17 * jquery.i18n.properties
19 * Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
20 * MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
23 * @author Nuno Fernandes
24 * @url www.codingwithcoffee.com
25 * @inspiration Localisation assistance for jQuery (http://keith-wood.name/localisation.html)
26 * by Keith Wood (kbwood{at}iinet.com.au) June 2007
28 *****************************************************************************/
33 /** Map holding bundle keys (if mode: 'map') */
37 * Load and parse message bundle files (.properties),
38 * making bundles keys available as javascript variables.
40 * i18n files are named <name>.js, or <name>_<language>.js or <name>_<language>_<country>.js
42 * The <language> argument is a valid ISO Language Code. These codes are the lower-case,
43 * two-letter codes as defined by ISO-639. You can find a full list of these codes at a
44 * number of sites, such as: http://www.loc.gov/standards/iso639-2/englangn.html
45 * The <country> argument is a valid ISO Country Code. These codes are the upper-case,
46 * two-letter codes as defined by ISO-3166. You can find a full list of these codes at a
47 * number of sites, such as: http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
49 * Sample usage for a bundles/Messages.properties bundle:
55 * @param name (string/string[], optional) names of file to load (eg, 'Messages' or ['Msg1','Msg2']). Defaults to "Messages"
56 * @param language (string, optional) language/country code (eg, 'en', 'en_US', 'pt_PT'). if not specified, language reported by the browser will be used instead.
57 * @param path (string, optional) path of directory that contains file to load
58 * @param mode (string, optional) whether bundles keys are available as JavaScript variables/functions or as a map (eg, 'vars' or 'map')
59 * @param cache (boolean, optional) whether bundles should be cached by the browser, or forcibly reloaded on each page load. Defaults to false (i.e. forcibly reloaded)
60 * @param encoding (string, optional) the encoding to request for bundles. Property file resource bundles are specified to be in ISO-8859-1 format. Defaults to UTF-8 for backward compatibility.
61 * @param callback (function, optional) callback function to be called after script is terminated
63 $.i18n.properties = function(settings) {
74 settings = $.extend(defaults, settings);
75 if(settings.language === null || settings.language == '') {
76 settings.language = $.i18n.browserLang();
78 if(settings.language === null) {settings.language='';}
80 // load and parse bundle files
81 var files = getFiles(settings.name);
82 for(i=0; i<files.length; i++) {
83 // 1. load base (eg, Messages.properties)
84 //loadAndParseFile(settings.path + files[i] + '.properties', settings);
85 // 2. with language code (eg, Messages_pt.properties)
86 //if(settings.language.length >= 2) {
87 // loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
89 // 3. with language code and country code (eg, Messages_pt_PT.properties)
91 if(settings.language.length >= 5) {
92 loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 5) +'.properties', settings);
93 } else if(settings.language.length >= 2) {
94 loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
96 loadAndParseFile(settings.path + files[i] + '.properties', settings);
101 if(settings.callback){ settings.callback(); }
106 * When configured with mode: 'map', allows access to bundle values by specifying its key.
107 * Eg, jQuery.i18n.prop('com.company.bundles.menu_add')
109 $.i18n.prop = function(key /* Add parameters as function arguments as necessary */) {
110 var value = $.i18n.map[key];
112 return '[' + key + ']';
114 // if(arguments.length < 2) // No arguments.
115 // //if(key == 'spv.lbl.modified') {alert(value);}
118 // if (!$.isArray(placeHolderValues)) {
119 // // If placeHolderValues is not an array, make it into one.
120 // placeHolderValues = [placeHolderValues];
121 // for (var i=2; i<arguments.length; i++)
122 // placeHolderValues.push(arguments[i]);
125 // Place holder replacement
128 * test.t1=asdf ''{0}''
129 * test.t2=asdf '{0}' '{1}'{1}'zxcv
130 * test.t3=This is \"a quote" 'a''{0}''s'd{fgh{ij'
131 * test.t4="'''{'0}''" {0}{a}
132 * test.t5="'''{0}'''" {1}
133 * test.t6=a {1} b {0} c
134 * test.t7=a 'quoted \\ s\ttringy' \t\t x
137 * test.t1, p1 ==> asdf 'p1'
138 * test.t2, p1 ==> asdf {0} {1}{1}zxcv
139 * test.t3, p1 ==> This is "a quote" a'{0}'sd{fgh{ij
140 * test.t4, p1 ==> "'{0}'" p1{a}
141 * test.t5, p1 ==> "'{0}'" {1}
142 * test.t6, p1 ==> a {1} b p1 c
143 * test.t6, p1, p2 ==> a p2 b p1 c
144 * test.t6, p1, p2, p3 ==> a p2 b p1 c
145 * test.t7 ==> a quoted \ s tringy x
149 if (typeof(value) == 'string') {
150 // Handle escape characters. Done separately from the tokenizing loop below because escape characters are
151 // active in quoted strings.
153 while ((i = value.indexOf('\\', i)) != -1) {
154 if (value[i+1] == 't')
155 value = value.substring(0, i) + '\t' + value.substring((i++) + 2); // tab
156 else if (value[i+1] == 'r')
157 value = value.substring(0, i) + '\r' + value.substring((i++) + 2); // return
158 else if (value[i+1] == 'n')
159 value = value.substring(0, i) + '\n' + value.substring((i++) + 2); // line feed
160 else if (value[i+1] == 'f')
161 value = value.substring(0, i) + '\f' + value.substring((i++) + 2); // form feed
162 else if (value[i+1] == '\\')
163 value = value.substring(0, i) + '\\' + value.substring((i++) + 2); // \
165 value = value.substring(0, i) + value.substring(i+1); // Quietly drop the character
168 // Lazily convert the string to a list of tokens.
169 var arr = [], j, index;
171 while (i < value.length) {
172 if (value[i] == '\'') {
174 if (i == value.length-1)
175 value = value.substring(0, i); // Silently drop the trailing quote
176 else if (value[i+1] == '\'')
177 value = value.substring(0, i) + value.substring(++i); // Escaped quote
181 while ((j = value.indexOf('\'', j)) != -1) {
182 if (j == value.length-1 || value[j+1] != '\'') {
183 // Found start and end quotes. Remove them
184 value = value.substring(0,i) + value.substring(i+1, j) + value.substring(j+1);
189 // Found a double quote, reduce to a single quote.
190 value = value.substring(0,j) + value.substring(++j);
195 // There is no end quote. Drop the start quote
196 value = value.substring(0,i) + value.substring(i+1);
200 else if (value[i] == '{') {
201 // Beginning of an unquoted place holder.
202 j = value.indexOf('}', i+1);
204 i++; // No end. Process the rest of the line. Java would throw an exception
206 // Add 1 to the index so that it aligns with the function arguments.
207 index = parseInt(value.substring(i+1, j));
208 if (!isNaN(index) && index >= 0) {
209 // Put the line thus far (if it isn't empty) into the array
210 var s = value.substring(0, i);
213 // Put the parameter reference into the array
215 // Start the processing over again starting from the rest of the line.
217 value = value.substring(j+1);
220 i = j + 1; // Invalid parameter. Leave as is.
227 // Put the remainder of the no-empty line into the array.
232 // Make the array the value for the entry.
233 $.i18n.map[key] = arr;
236 if (value.length == 0)
238 if (value.lengh == 1 && typeof(value[0]) == "string")
242 for (i=0; i<value.length; i++) {
243 if (typeof(value[i]) == "string")
246 else if (value[i] + 1 < arguments.length)
247 s += arguments[value[i] + 1];
249 s += "{"+ value[i] +"}";
255 /** Language reported by browser, normalized code */
256 $.i18n.browserLang = function() {
257 return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
261 /** Load and parse .properties files */
262 function loadAndParseFile(filename, settings) {
266 cache: settings.cache,
267 contentType:'text/plain;charset='+ settings.encoding,
269 success: function(data, status) {
270 parseData(data, settings.mode);
275 /** Parse .properties files */
276 function parseData(data, mode) {
278 var parameters = data.split( /\n/ );
279 var regPlaceHolder = /(\{\d+\})/g;
280 var regRepPlaceHolder = /\{(\d+)\}/g;
281 var unicodeRE = /(\\u.{4})/ig;
282 for(var i=0; i<parameters.length; i++ ) {
283 parameters[i] = parameters[i].replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
284 if(parameters[i].length > 0 && parameters[i].match("^#")!="#") { // skip comments
285 var pair = parameters[i].split('=');
286 if(pair.length > 0) {
287 /** Process key & value */
288 var name = unescape(pair[0]).replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
289 var value = pair.length == 1 ? "" : pair[1];
290 // process multi-line values
291 while(value.match(/\\$/)=="\\") {
292 value = value.substring(0, value.length - 1);
293 value += parameters[++i].replace( /\s\s*$/, '' ); // right trim
295 // Put values with embedded '='s back together
296 for(var s=2;s<pair.length;s++){ value +='=' + pair[s]; }
297 value = value.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
299 /** Mode: bundle keys in a map */
300 if(mode == 'map' || mode == 'both') {
301 // handle unicode chars possibly left out
302 var unicodeMatches = value.match(unicodeRE);
304 for(var u=0; u<unicodeMatches.length; u++) {
305 value = value.replace( unicodeMatches[u], unescapeUnicode(unicodeMatches[u]));
309 $.i18n.map[name] = value;
312 /** Mode: bundle keys as vars/functions */
313 if(mode == 'vars' || mode == 'both') {
314 value = value.replace( /"/g, '\\"' ); // escape quotation mark (")
316 // make sure namespaced key exists (eg, 'some.key')
317 checkKeyNamespace(name);
319 // value with variable substitutions
320 if(regPlaceHolder.test(value)) {
321 var parts = value.split(regPlaceHolder);
322 // process function args
326 for(var p=0; p<parts.length; p++) {
327 if(regPlaceHolder.test(parts[p]) && (usedArgs.length == 0 || usedArgs.indexOf(parts[p]) == -1)) {
328 if(!first) {fnArgs += ',';}
329 fnArgs += parts[p].replace(regRepPlaceHolder, 'v$1');
330 usedArgs.push(parts[p]);
334 parsed += name + '=function(' + fnArgs + '){';
335 // process function body
336 var fnExpr = '"' + value.replace(regRepPlaceHolder, '"+v$1+"') + '"';
337 parsed += 'return ' + fnExpr + ';' + '};';
341 parsed += name+'="'+value+'";';
343 } // END: Mode: bundle keys as vars/functions
344 } // END: if(pair.length > 0)
345 } // END: skip comments
350 /** Make sure namespace exists (for keys with dots in name) */
351 // TODO key parts that start with numbers quietly fail. i.e. month.short.1=Jan
352 function checkKeyNamespace(key) {
354 if(regDot.test(key)) {
356 var names = key.split( /\./ );
357 for(var i=0; i<names.length; i++) {
358 if(i>0) {fullname += '.';}
359 fullname += names[i];
360 if(eval('typeof '+fullname+' == "undefined"')) {
361 eval(fullname + '={};');
367 /** Make sure filename is an array */
368 function getFiles(names) {
369 return (names && names.constructor == Array) ? names : [names];
372 /** Ensure language code is in the format aa_AA. */
373 function normaliseLanguageCode(lang) {
374 lang = lang.toLowerCase();
375 if(lang.length > 3) {
376 lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
381 /** Unescape unicode chars ('\u00e3') */
382 function unescapeUnicode(str) {
383 // unescape unicode codes
385 var code = parseInt(str.substr(2), 16);
386 if (code >= 0 && code < Math.pow(2, 16)) {
389 // convert codes to text
391 for (var i = 0; i < codes.length; ++i) {
392 unescaped += String.fromCharCode(codes[i]);
397 /* Cross-Browser Split 1.0.1
398 (c) Steven Levithan <stevenlevithan.com>; MIT License
399 An ECMA-compliant, uniform cross-browser split method */
401 // avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
403 cbSplit = function(str, separator, limit) {
404 // if `separator` is not a regex, use the native `split`
405 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
406 if(typeof cbSplit._nativeSplit == "undefined")
407 return str.split(separator, limit);
409 return cbSplit._nativeSplit.call(str, separator, limit);
414 flags = (separator.ignoreCase ? "i" : "") +
415 (separator.multiline ? "m" : "") +
416 (separator.sticky ? "y" : ""),
417 separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
418 separator2, match, lastIndex, lastLength;
420 str = str + ""; // type conversion
421 if (!cbSplit._compliantExecNpcg) {
422 separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
425 /* behavior for `limit`: if it's...
426 - `undefined`: no limit.
427 - `NaN` or zero: return an empty array.
428 - a positive number: use `Math.floor(limit)`.
429 - a negative number: no limit.
430 - other: type-convert, then use the above rules. */
431 if (limit === undefined || +limit < 0) {
434 limit = Math.floor(+limit);
440 while (match = separator.exec(str)) {
441 lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
443 if (lastIndex > lastLastIndex) {
444 output.push(str.slice(lastLastIndex, match.index));
446 // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
447 if (!cbSplit._compliantExecNpcg && match.length > 1) {
448 match[0].replace(separator2, function () {
449 for (var i = 1; i < arguments.length - 2; i++) {
450 if (arguments[i] === undefined) {
451 match[i] = undefined;
457 if (match.length > 1 && match.index < str.length) {
458 Array.prototype.push.apply(output, match.slice(1));
461 lastLength = match[0].length;
462 lastLastIndex = lastIndex;
464 if (output.length >= limit) {
469 if (separator.lastIndex === match.index) {
470 separator.lastIndex++; // avoid an infinite loop
474 if (lastLastIndex === str.length) {
475 if (lastLength || !separator.test("")) {
479 output.push(str.slice(lastLastIndex));
482 return output.length > limit ? output.slice(0, limit) : output;
485 cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
486 cbSplit._nativeSplit = String.prototype.split;
488 } // end `if (!cbSplit)`
489 String.prototype.split = function (separator, limit) {
490 return cbSplit(this, separator, limit);