modify copyright year
[msb/discovery.git] / discovery-ui / src / main / resources / iui / microservices / js / jquery.i18n / jquery.i18n.properties-1.0.9.js
1 /*
2  * Copyright 2016-2017 ZTE, Inc. and others.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 /******************************************************************************
17  * jquery.i18n.properties
18  * 
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.
21  * 
22  * @version     1.0.x
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
27  * 
28  *****************************************************************************/
29
30 (function($) {
31 $.i18n = {};
32
33 /** Map holding bundle keys (if mode: 'map') */
34 $.i18n.map = {};
35     
36 /**
37  * Load and parse message bundle files (.properties),
38  * making bundles keys available as javascript variables.
39  * 
40  * i18n files are named <name>.js, or <name>_<language>.js or <name>_<language>_<country>.js
41  * Where:
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
48  * 
49  * Sample usage for a bundles/Messages.properties bundle:
50  * $.i18n.properties({
51  *      name:      'Messages', 
52  *      language:  'en_US',
53  *      path:      'bundles'
54  * });
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
62  */
63 $.i18n.properties = function(settings) {
64         // set up settings
65     var defaults = {
66         name:           'Messages',
67         language:       '',
68         path:           '',  
69         mode:           'vars',
70         cache:                  false,
71         encoding:       'UTF-8',
72         callback:       null
73     };
74     settings = $.extend(defaults, settings);    
75     if(settings.language === null || settings.language == '') {
76            settings.language = $.i18n.browserLang();
77         }
78         if(settings.language === null) {settings.language='';}
79         
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);
88                 //}
89                 // 3. with language code and country code (eg, Messages_pt_PT.properties)
90                 // 将寻找资源文件的顺序倒置
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);
95                 } else {
96                         loadAndParseFile(settings.path + files[i] + '.properties', settings);
97                 }
98         }
99         
100         // call callback
101         if(settings.callback){ settings.callback(); }
102 };
103
104
105 /**
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')
108  */
109 $.i18n.prop = function(key /* Add parameters as function arguments as necessary  */) {
110         var value = $.i18n.map[key];
111         if (value == null)
112                 return '[' + key + ']';
113         
114 //      if(arguments.length < 2) // No arguments.
115 //    //if(key == 'spv.lbl.modified') {alert(value);}
116 //              return value;
117         
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]);
123 //      }
124
125         // Place holder replacement
126         /**
127          * Tested with:
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
135          *
136          * Produces:
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
146          */
147         
148         var i;
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.
152         i = 0;
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); // \
164                    else
165                            value = value.substring(0, i) + value.substring(i+1); // Quietly drop the character
166         }
167                 
168                 // Lazily convert the string to a list of tokens.
169                 var arr = [], j, index;
170                 i = 0;
171                 while (i < value.length) {
172                         if (value[i] == '\'') {
173                                 // Handle quotes
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
178                                 else {
179                                         // Quoted string
180                                         j = i + 2;
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);
185                                                         i = j - 1;
186                                                         break;
187                                                 }
188                                                 else {
189                                                         // Found a double quote, reduce to a single quote.
190                                                         value = value.substring(0,j) + value.substring(++j);
191                                                 }
192                                         }
193                                         
194                                         if (j == -1) {
195                                                 // There is no end quote. Drop the start quote
196                                                 value = value.substring(0,i) + value.substring(i+1);
197                                         }
198                                 }
199                         }
200                         else if (value[i] == '{') {
201                                 // Beginning of an unquoted place holder.
202                                 j = value.indexOf('}', i+1);
203                                 if (j == -1)
204                                         i++; // No end. Process the rest of the line. Java would throw an exception
205                                 else {
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);
211                                                 if (s != "")
212                                                         arr.push(s);
213                                                 // Put the parameter reference into the array
214                                                 arr.push(index);
215                                                 // Start the processing over again starting from the rest of the line.
216                                                 i = 0;
217                                                 value = value.substring(j+1);
218                                         }
219                                         else
220                                                 i = j + 1; // Invalid parameter. Leave as is.
221                                 }
222                         }
223                         else
224                                 i++;
225                 }
226                 
227                 // Put the remainder of the no-empty line into the array.
228                 if (value != "")
229                         arr.push(value);
230                 value = arr;
231                 
232                 // Make the array the value for the entry.
233                 $.i18n.map[key] = arr;
234         }
235         
236         if (value.length == 0)
237                 return "";
238         if (value.lengh == 1 && typeof(value[0]) == "string")
239                 return value[0];
240         
241         var s = "";
242         for (i=0; i<value.length; i++) {
243                 if (typeof(value[i]) == "string")
244                         s += value[i];
245                 // Must be a number
246                 else if (value[i] + 1 < arguments.length)
247                         s += arguments[value[i] + 1];
248                 else
249                         s += "{"+ value[i] +"}";
250         }
251         
252         return s;
253 };
254
255 /** Language reported by browser, normalized code */
256 $.i18n.browserLang = function() {
257         return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
258 }
259
260
261 /** Load and parse .properties files */
262 function loadAndParseFile(filename, settings) {
263         $.ajax({
264         url:        filename,
265         async:      false,
266         cache:          settings.cache,
267         contentType:'text/plain;charset='+ settings.encoding,
268         dataType:   'text',
269         success:    function(data, status) {
270                                         parseData(data, settings.mode); 
271                                         }
272     });
273 }
274
275 /** Parse .properties files */
276 function parseData(data, mode) {
277    var parsed = '';
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
294                }               
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
298                
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);
303                    if(unicodeMatches) {
304                      for(var u=0; u<unicodeMatches.length; u++) {
305                         value = value.replace( unicodeMatches[u], unescapeUnicode(unicodeMatches[u]));
306                      }
307                    }
308                    // add to map
309                    $.i18n.map[name] = value;
310                }
311                
312                /** Mode: bundle keys as vars/functions */
313                if(mode == 'vars' || mode == 'both') {
314                    value = value.replace( /"/g, '\\"' ); // escape quotation mark (")
315                    
316                    // make sure namespaced key exists (eg, 'some.key') 
317                    checkKeyNamespace(name);
318                    
319                    // value with variable substitutions
320                    if(regPlaceHolder.test(value)) {
321                        var parts = value.split(regPlaceHolder);
322                        // process function args
323                        var first = true;
324                        var fnArgs = '';
325                        var usedArgs = [];
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]);
331                                first = false;
332                            }
333                        }
334                        parsed += name + '=function(' + fnArgs + '){';
335                        // process function body
336                        var fnExpr = '"' + value.replace(regRepPlaceHolder, '"+v$1+"') + '"';
337                        parsed += 'return ' + fnExpr + ';' + '};';
338                        
339                    // simple value
340                    }else{
341                        parsed += name+'="'+value+'";';
342                    }
343                } // END: Mode: bundle keys as vars/functions
344            } // END: if(pair.length > 0)
345        } // END: skip comments
346    }
347    eval(parsed);
348 }
349
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) {
353         var regDot = /\./;
354         if(regDot.test(key)) {
355                 var fullname = '';
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 + '={};');
362                         }
363                 }
364         }
365 }
366
367 /** Make sure filename is an array */
368 function getFiles(names) {
369         return (names && names.constructor == Array) ? names : [names];
370 }
371
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();
377     }
378     return lang;
379 }
380
381 /** Unescape unicode chars ('\u00e3') */
382 function unescapeUnicode(str) {
383   // unescape unicode codes
384   var codes = [];
385   var code = parseInt(str.substr(2), 16);
386   if (code >= 0 && code < Math.pow(2, 16)) {
387      codes.push(code);
388   }
389   // convert codes to text
390   var unescaped = '';
391   for (var i = 0; i < codes.length; ++i) {
392     unescaped += String.fromCharCode(codes[i]);
393   }
394   return unescaped;
395 }
396
397 /* Cross-Browser Split 1.0.1
398 (c) Steven Levithan <stevenlevithan.com>; MIT License
399 An ECMA-compliant, uniform cross-browser split method */
400 var cbSplit;
401 // avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
402 if (!cbSplit) {    
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);
408         else
409           return cbSplit._nativeSplit.call(str, separator, limit);
410       }
411   
412       var output = [],
413           lastLastIndex = 0,
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;
419   
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
423       }
424   
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) {
432           limit = Infinity;
433       } else {
434           limit = Math.floor(+limit);
435           if (!limit) {
436               return [];
437           }
438       }
439   
440       while (match = separator.exec(str)) {
441           lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
442   
443           if (lastIndex > lastLastIndex) {
444               output.push(str.slice(lastLastIndex, match.index));
445   
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;
452                           }
453                       }
454                   });
455               }
456   
457               if (match.length > 1 && match.index < str.length) {
458                   Array.prototype.push.apply(output, match.slice(1));
459               }
460   
461               lastLength = match[0].length;
462               lastLastIndex = lastIndex;
463   
464               if (output.length >= limit) {
465                   break;
466               }
467           }
468   
469           if (separator.lastIndex === match.index) {
470               separator.lastIndex++; // avoid an infinite loop
471           }
472       }
473   
474       if (lastLastIndex === str.length) {
475           if (lastLength || !separator.test("")) {
476               output.push("");
477           }
478       } else {
479           output.push(str.slice(lastLastIndex));
480       }
481   
482       return output.length > limit ? output.slice(0, limit) : output;
483   };
484   
485   cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
486   cbSplit._nativeSplit = String.prototype.split;
487
488 } // end `if (!cbSplit)`
489 String.prototype.split = function (separator, limit) {
490     return cbSplit(this, separator, limit);
491 };
492
493 })(jQuery);
494