2 * Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
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 * Author: Zhaoxing Meng
17 * email: meng.zhaoxing1@zte.com.cn
19 /******************************************************************************
20 * jquery.i18n.properties
22 * Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
23 * MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
26 * @author Nuno Fernandes
27 * @url www.codingwithcoffee.com
28 * @inspiration Localisation assistance for jQuery (http://keith-wood.name/localisation.html)
29 * by Keith Wood (kbwood{at}iinet.com.au) June 2007
31 *****************************************************************************/
36 /** Map holding bundle keys (if mode: 'map') */
40 * Load and parse message bundle files (.properties),
41 * making bundles keys available as javascript variables.
43 * i18n files are named <name>.js, or <name>_<language>.js or <name>_<language>_<country>.js
45 * The <language> argument is a valid ISO Language Code. These codes are the lower-case,
46 * two-letter codes as defined by ISO-639. You can find a full list of these codes at a
47 * number of sites, such as: http://www.loc.gov/standards/iso639-2/englangn.html
48 * The <country> argument is a valid ISO Country Code. These codes are the upper-case,
49 * two-letter codes as defined by ISO-3166. You can find a full list of these codes at a
50 * number of sites, such as: http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
52 * Sample usage for a bundles/Messages.properties bundle:
58 * @param name (string/string[], optional) names of file to load (eg, 'Messages' or ['Msg1','Msg2']). Defaults to "Messages"
59 * @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.
60 * @param path (string, optional) path of directory that contains file to load
61 * @param mode (string, optional) whether bundles keys are available as JavaScript variables/functions or as a map (eg, 'vars' or 'map')
62 * @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)
63 * @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.
64 * @param callback (function, optional) callback function to be called after script is terminated
66 $.i18n.properties = function(settings) {
77 settings = $.extend(defaults, settings);
78 if(settings.language === null || settings.language == '') {
79 settings.language = $.i18n.browserLang();
81 if(settings.language === null) {settings.language='';}
83 // load and parse bundle files
84 var files = getFiles(settings.name);
85 for(i=0; i<files.length; i++) {
86 // 1. load base (eg, Messages.properties)
87 //loadAndParseFile(settings.path + files[i] + '.properties', settings);
88 // 2. with language code (eg, Messages_pt.properties)
89 //if(settings.language.length >= 2) {
90 // loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
92 // 3. with language code and country code (eg, Messages_pt_PT.properties)
94 if(settings.language.length >= 5) {
95 loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 5) +'.properties', settings);
96 } else if(settings.language.length >= 2) {
97 loadAndParseFile(settings.path + files[i] + '-' + settings.language.substring(0, 2) +'.properties', settings);
99 loadAndParseFile(settings.path + files[i] + '.properties', settings);
104 if(settings.callback){ settings.callback(); }
109 * When configured with mode: 'map', allows access to bundle values by specifying its key.
110 * Eg, jQuery.i18n.prop('com.company.bundles.menu_add')
112 $.i18n.prop = function(key /* Add parameters as function arguments as necessary */) {
113 var value = $.i18n.map[key];
115 return '[' + key + ']';
117 // if(arguments.length < 2) // No arguments.
118 // //if(key == 'spv.lbl.modified') {alert(value);}
121 // if (!$.isArray(placeHolderValues)) {
122 // // If placeHolderValues is not an array, make it into one.
123 // placeHolderValues = [placeHolderValues];
124 // for (var i=2; i<arguments.length; i++)
125 // placeHolderValues.push(arguments[i]);
128 // Place holder replacement
131 * test.t1=asdf ''{0}''
132 * test.t2=asdf '{0}' '{1}'{1}'zxcv
133 * test.t3=This is \"a quote" 'a''{0}''s'd{fgh{ij'
134 * test.t4="'''{'0}''" {0}{a}
135 * test.t5="'''{0}'''" {1}
136 * test.t6=a {1} b {0} c
137 * test.t7=a 'quoted \\ s\ttringy' \t\t x
140 * test.t1, p1 ==> asdf 'p1'
141 * test.t2, p1 ==> asdf {0} {1}{1}zxcv
142 * test.t3, p1 ==> This is "a quote" a'{0}'sd{fgh{ij
143 * test.t4, p1 ==> "'{0}'" p1{a}
144 * test.t5, p1 ==> "'{0}'" {1}
145 * test.t6, p1 ==> a {1} b p1 c
146 * test.t6, p1, p2 ==> a p2 b p1 c
147 * test.t6, p1, p2, p3 ==> a p2 b p1 c
148 * test.t7 ==> a quoted \ s tringy x
152 if (typeof(value) == 'string') {
153 // Handle escape characters. Done separately from the tokenizing loop below because escape characters are
154 // active in quoted strings.
156 while ((i = value.indexOf('\\', i)) != -1) {
157 if (value[i+1] == 't')
158 value = value.substring(0, i) + '\t' + value.substring((i++) + 2); // tab
159 else if (value[i+1] == 'r')
160 value = value.substring(0, i) + '\r' + value.substring((i++) + 2); // return
161 else if (value[i+1] == 'n')
162 value = value.substring(0, i) + '\n' + value.substring((i++) + 2); // line feed
163 else if (value[i+1] == 'f')
164 value = value.substring(0, i) + '\f' + value.substring((i++) + 2); // form feed
165 else if (value[i+1] == '\\')
166 value = value.substring(0, i) + '\\' + value.substring((i++) + 2); // \
168 value = value.substring(0, i) + value.substring(i+1); // Quietly drop the character
171 // Lazily convert the string to a list of tokens.
172 var arr = [], j, index;
174 while (i < value.length) {
175 if (value[i] == '\'') {
177 if (i == value.length-1)
178 value = value.substring(0, i); // Silently drop the trailing quote
179 else if (value[i+1] == '\'')
180 value = value.substring(0, i) + value.substring(++i); // Escaped quote
184 while ((j = value.indexOf('\'', j)) != -1) {
185 if (j == value.length-1 || value[j+1] != '\'') {
186 // Found start and end quotes. Remove them
187 value = value.substring(0,i) + value.substring(i+1, j) + value.substring(j+1);
192 // Found a double quote, reduce to a single quote.
193 value = value.substring(0,j) + value.substring(++j);
198 // There is no end quote. Drop the start quote
199 value = value.substring(0,i) + value.substring(i+1);
203 else if (value[i] == '{') {
204 // Beginning of an unquoted place holder.
205 j = value.indexOf('}', i+1);
207 i++; // No end. Process the rest of the line. Java would throw an exception
209 // Add 1 to the index so that it aligns with the function arguments.
210 index = parseInt(value.substring(i+1, j));
211 if (!isNaN(index) && index >= 0) {
212 // Put the line thus far (if it isn't empty) into the array
213 var s = value.substring(0, i);
216 // Put the parameter reference into the array
218 // Start the processing over again starting from the rest of the line.
220 value = value.substring(j+1);
223 i = j + 1; // Invalid parameter. Leave as is.
230 // Put the remainder of the no-empty line into the array.
235 // Make the array the value for the entry.
236 $.i18n.map[key] = arr;
239 if (value.length == 0)
241 if (value.lengh == 1 && typeof(value[0]) == "string")
245 for (i=0; i<value.length; i++) {
246 if (typeof(value[i]) == "string")
249 else if (value[i] + 1 < arguments.length)
250 s += arguments[value[i] + 1];
252 s += "{"+ value[i] +"}";
258 /** Language reported by browser, normalized code */
259 $.i18n.browserLang = function() {
260 return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
264 /** Load and parse .properties files */
265 function loadAndParseFile(filename, settings) {
269 cache: settings.cache,
270 contentType:'text/plain;charset='+ settings.encoding,
272 success: function(data, status) {
273 parseData(data, settings.mode);
278 /** Parse .properties files */
279 function parseData(data, mode) {
281 var parameters = data.split( /\n/ );
282 var regPlaceHolder = /(\{\d+\})/g;
283 var regRepPlaceHolder = /\{(\d+)\}/g;
284 var unicodeRE = /(\\u.{4})/ig;
285 for(var i=0; i<parameters.length; i++ ) {
286 parameters[i] = parameters[i].replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
287 if(parameters[i].length > 0 && parameters[i].match("^#")!="#") { // skip comments
288 var pair = parameters[i].split('=');
289 if(pair.length > 0) {
290 /** Process key & value */
291 var name = unescape(pair[0]).replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
292 var value = pair.length == 1 ? "" : pair[1];
293 // process multi-line values
294 while(value.match(/\\$/)=="\\") {
295 value = value.substring(0, value.length - 1);
296 value += parameters[++i].replace( /\s\s*$/, '' ); // right trim
298 // Put values with embedded '='s back together
299 for(var s=2;s<pair.length;s++){ value +='=' + pair[s]; }
300 value = value.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
302 /** Mode: bundle keys in a map */
303 if(mode == 'map' || mode == 'both') {
304 // handle unicode chars possibly left out
305 var unicodeMatches = value.match(unicodeRE);
307 for(var u=0; u<unicodeMatches.length; u++) {
308 value = value.replace( unicodeMatches[u], unescapeUnicode(unicodeMatches[u]));
312 $.i18n.map[name] = value;
315 /** Mode: bundle keys as vars/functions */
316 if(mode == 'vars' || mode == 'both') {
317 value = value.replace( /"/g, '\\"' ); // escape quotation mark (")
319 // make sure namespaced key exists (eg, 'some.key')
320 checkKeyNamespace(name);
322 // value with variable substitutions
323 if(regPlaceHolder.test(value)) {
324 var parts = value.split(regPlaceHolder);
325 // process function args
329 for(var p=0; p<parts.length; p++) {
330 if(regPlaceHolder.test(parts[p]) && (usedArgs.length == 0 || usedArgs.indexOf(parts[p]) == -1)) {
331 if(!first) {fnArgs += ',';}
332 fnArgs += parts[p].replace(regRepPlaceHolder, 'v$1');
333 usedArgs.push(parts[p]);
337 parsed += name + '=function(' + fnArgs + '){';
338 // process function body
339 var fnExpr = '"' + value.replace(regRepPlaceHolder, '"+v$1+"') + '"';
340 parsed += 'return ' + fnExpr + ';' + '};';
344 parsed += name+'="'+value+'";';
346 } // END: Mode: bundle keys as vars/functions
347 } // END: if(pair.length > 0)
348 } // END: skip comments
353 /** Make sure namespace exists (for keys with dots in name) */
354 // TODO key parts that start with numbers quietly fail. i.e. month.short.1=Jan
355 function checkKeyNamespace(key) {
357 if(regDot.test(key)) {
359 var names = key.split( /\./ );
360 for(var i=0; i<names.length; i++) {
361 if(i>0) {fullname += '.';}
362 fullname += names[i];
363 if(eval('typeof '+fullname+' == "undefined"')) {
364 eval(fullname + '={};');
370 /** Make sure filename is an array */
371 function getFiles(names) {
372 return (names && names.constructor == Array) ? names : [names];
375 /** Ensure language code is in the format aa_AA. */
376 function normaliseLanguageCode(lang) {
377 lang = lang.toLowerCase();
378 if(lang.length > 3) {
379 lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
384 /** Unescape unicode chars ('\u00e3') */
385 function unescapeUnicode(str) {
386 // unescape unicode codes
388 var code = parseInt(str.substr(2), 16);
389 if (code >= 0 && code < Math.pow(2, 16)) {
392 // convert codes to text
394 for (var i = 0; i < codes.length; ++i) {
395 unescaped += String.fromCharCode(codes[i]);
400 /* Cross-Browser Split 1.0.1
401 (c) Steven Levithan <stevenlevithan.com>; MIT License
402 An ECMA-compliant, uniform cross-browser split method */
404 // avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
406 cbSplit = function(str, separator, limit) {
407 // if `separator` is not a regex, use the native `split`
408 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
409 if(typeof cbSplit._nativeSplit == "undefined")
410 return str.split(separator, limit);
412 return cbSplit._nativeSplit.call(str, separator, limit);
417 flags = (separator.ignoreCase ? "i" : "") +
418 (separator.multiline ? "m" : "") +
419 (separator.sticky ? "y" : ""),
420 separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
421 separator2, match, lastIndex, lastLength;
423 str = str + ""; // type conversion
424 if (!cbSplit._compliantExecNpcg) {
425 separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
428 /* behavior for `limit`: if it's...
429 - `undefined`: no limit.
430 - `NaN` or zero: return an empty array.
431 - a positive number: use `Math.floor(limit)`.
432 - a negative number: no limit.
433 - other: type-convert, then use the above rules. */
434 if (limit === undefined || +limit < 0) {
437 limit = Math.floor(+limit);
443 while (match = separator.exec(str)) {
444 lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
446 if (lastIndex > lastLastIndex) {
447 output.push(str.slice(lastLastIndex, match.index));
449 // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
450 if (!cbSplit._compliantExecNpcg && match.length > 1) {
451 match[0].replace(separator2, function () {
452 for (var i = 1; i < arguments.length - 2; i++) {
453 if (arguments[i] === undefined) {
454 match[i] = undefined;
460 if (match.length > 1 && match.index < str.length) {
461 Array.prototype.push.apply(output, match.slice(1));
464 lastLength = match[0].length;
465 lastLastIndex = lastIndex;
467 if (output.length >= limit) {
472 if (separator.lastIndex === match.index) {
473 separator.lastIndex++; // avoid an infinite loop
477 if (lastLastIndex === str.length) {
478 if (lastLength || !separator.test("")) {
482 output.push(str.slice(lastLastIndex));
485 return output.length > limit ? output.slice(0, limit) : output;
488 cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
489 cbSplit._nativeSplit = String.prototype.split;
491 } // end `if (!cbSplit)`
492 String.prototype.split = function (separator, limit) {
493 return cbSplit(this, separator, limit);