source: trunk/web/addons/job_monarch/lib/extjs-30/src/util/Format.js @ 625

Last change on this file since 625 was 625, checked in by ramonb, 15 years ago

lib/extjs-30:

  • new ExtJS 3.0
File size: 13.3 KB
Line 
1/*!
2 * Ext JS Library 3.0.0
3 * Copyright(c) 2006-2009 Ext JS, LLC
4 * licensing@extjs.com
5 * http://www.extjs.com/license
6 */
7/**
8 * @class Ext.util.Format
9 * Reusable data formatting functions
10 * @singleton
11 */
12Ext.util.Format = function(){
13    var trimRe = /^\s+|\s+$/g;
14    return {
15        /**
16         * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
17         * @param {String} value The string to truncate
18         * @param {Number} length The maximum length to allow before truncating
19         * @param {Boolean} word True to try to find a common work break
20         * @return {String} The converted text
21         */
22        ellipsis : function(value, len, word){
23            if(value && value.length > len){
24                if(word){
25                    var vs = value.substr(0, len - 2);
26                    var index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
27                    if(index == -1 || index < (len - 15)){
28                        return value.substr(0, len - 3) + "...";
29                    }else{
30                        return vs.substr(0, index) + "...";
31                    }
32                } else{
33                    return value.substr(0, len - 3) + "...";
34                }
35            }
36            return value;
37        },
38
39        /**
40         * Checks a reference and converts it to empty string if it is undefined
41         * @param {Mixed} value Reference to check
42         * @return {Mixed} Empty string if converted, otherwise the original value
43         */
44        undef : function(value){
45            return value !== undefined ? value : "";
46        },
47
48        /**
49         * Checks a reference and converts it to the default value if it's empty
50         * @param {Mixed} value Reference to check
51         * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
52         * @return {String}
53         */
54        defaultValue : function(value, defaultValue){
55            return value !== undefined && value !== '' ? value : defaultValue;
56        },
57
58        /**
59         * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
60         * @param {String} value The string to encode
61         * @return {String} The encoded text
62         */
63        htmlEncode : function(value){
64            return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
65        },
66
67        /**
68         * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
69         * @param {String} value The string to decode
70         * @return {String} The decoded text
71         */
72        htmlDecode : function(value){
73            return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
74        },
75
76        /**
77         * Trims any whitespace from either side of a string
78         * @param {String} value The text to trim
79         * @return {String} The trimmed text
80         */
81        trim : function(value){
82            return String(value).replace(trimRe, "");
83        },
84
85        /**
86         * Returns a substring from within an original string
87         * @param {String} value The original text
88         * @param {Number} start The start index of the substring
89         * @param {Number} length The length of the substring
90         * @return {String} The substring
91         */
92        substr : function(value, start, length){
93            return String(value).substr(start, length);
94        },
95
96        /**
97         * Converts a string to all lower case letters
98         * @param {String} value The text to convert
99         * @return {String} The converted text
100         */
101        lowercase : function(value){
102            return String(value).toLowerCase();
103        },
104
105        /**
106         * Converts a string to all upper case letters
107         * @param {String} value The text to convert
108         * @return {String} The converted text
109         */
110        uppercase : function(value){
111            return String(value).toUpperCase();
112        },
113
114        /**
115         * Converts the first character only of a string to upper case
116         * @param {String} value The text to convert
117         * @return {String} The converted text
118         */
119        capitalize : function(value){
120            return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
121        },
122
123        // private
124        call : function(value, fn){
125            if(arguments.length > 2){
126                var args = Array.prototype.slice.call(arguments, 2);
127                args.unshift(value);
128                return eval(fn).apply(window, args);
129            }else{
130                return eval(fn).call(window, value);
131            }
132        },
133
134        /**
135         * Format a number as US currency
136         * @param {Number/String} value The numeric value to format
137         * @return {String} The formatted currency string
138         */
139        usMoney : function(v){
140            v = (Math.round((v-0)*100))/100;
141            v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
142            v = String(v);
143            var ps = v.split('.');
144            var whole = ps[0];
145            var sub = ps[1] ? '.'+ ps[1] : '.00';
146            var r = /(\d+)(\d{3})/;
147            while (r.test(whole)) {
148                whole = whole.replace(r, '$1' + ',' + '$2');
149            }
150            v = whole + sub;
151            if(v.charAt(0) == '-'){
152                return '-$' + v.substr(1);
153            }
154            return "$" +  v;
155        },
156
157        /**
158         * Parse a value into a formatted date using the specified format pattern.
159         * @param {String/Date} value The value to format (Strings must conform to the format expected by the javascript Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method)
160         * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
161         * @return {String} The formatted date string
162         */
163        date : function(v, format){
164            if(!v){
165                return "";
166            }
167            if(!Ext.isDate(v)){
168                v = new Date(Date.parse(v));
169            }
170            return v.dateFormat(format || "m/d/Y");
171        },
172
173        /**
174         * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
175         * @param {String} format Any valid date format string
176         * @return {Function} The date formatting function
177         */
178        dateRenderer : function(format){
179            return function(v){
180                return Ext.util.Format.date(v, format);
181            };
182        },
183
184        // private
185        stripTagsRE : /<\/?[^>]+>/gi,
186       
187        /**
188         * Strips all HTML tags
189         * @param {Mixed} value The text from which to strip tags
190         * @return {String} The stripped text
191         */
192        stripTags : function(v){
193            return !v ? v : String(v).replace(this.stripTagsRE, "");
194        },
195
196        stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
197
198        /**
199         * Strips all script tags
200         * @param {Mixed} value The text from which to strip script tags
201         * @return {String} The stripped text
202         */
203        stripScripts : function(v){
204            return !v ? v : String(v).replace(this.stripScriptsRe, "");
205        },
206
207        /**
208         * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
209         * @param {Number/String} size The numeric value to format
210         * @return {String} The formatted file size
211         */
212        fileSize : function(size){
213            if(size < 1024) {
214                return size + " bytes";
215            } else if(size < 1048576) {
216                return (Math.round(((size*10) / 1024))/10) + " KB";
217            } else {
218                return (Math.round(((size*10) / 1048576))/10) + " MB";
219            }
220        },
221
222        /**
223         * It does simple math for use in a template, for example:<pre><code>
224         * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
225         * </code></pre>
226         * @return {Function} A function that operates on the passed value.
227         */
228        math : function(){
229            var fns = {};
230            return function(v, a){
231                if(!fns[a]){
232                    fns[a] = new Function('v', 'return v ' + a + ';');
233                }
234                return fns[a](v);
235            }
236        }(),
237
238        /**
239         * Rounds the passed number to the required decimal precision.
240         * @param {Number/String} value The numeric value to round.
241         * @param {Number} precision The number of decimal places to which to round the first parameter's value.
242         * @return {Number} The rounded value.
243         */
244        round : function(value, precision) {
245            var result = Number(value);
246            if (typeof precision == 'number') {
247                precision = Math.pow(10, precision);
248                result = Math.round(value * precision) / precision;
249            }
250            return result;
251        },
252
253        /**
254         * Formats the number according to the format string.
255         * <div style="margin-left:40px">examples (123456.789):
256         * <div style="margin-left:10px">
257         * 0 - (123456) show only digits, no precision<br>
258         * 0.00 - (123456.78) show only digits, 2 precision<br>
259         * 0.0000 - (123456.7890) show only digits, 4 precision<br>
260         * 0,000 - (123,456) show comma and digits, no precision<br>
261         * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
262         * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
263         * To reverse the grouping (,) and decimal (.) for international numbers, add /i to the end.
264         * For example: 0.000,00/i
265         * </div></div>
266         * @param {Number} v The number to format.
267         * @param {String} format The way you would like to format this text.
268         * @return {String} The formatted number.
269         */
270        number: function(v, format) {
271            if(!format){
272                        return v;
273                    }
274                    v = Ext.num(v, NaN);
275            if (isNaN(v)){
276                return '';
277            }
278                    var comma = ',',
279                        dec = '.',
280                        i18n = false,
281                        neg = v < 0;
282               
283                    v = Math.abs(v);
284                    if(format.substr(format.length - 2) == '/i'){
285                        format = format.substr(0, format.length - 2);
286                        i18n = true;
287                        comma = '.';
288                        dec = ',';
289                    }
290               
291                    var hasComma = format.indexOf(comma) != -1, 
292                        psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec);
293               
294                    if(1 < psplit.length){
295                        v = v.toFixed(psplit[1].length);
296                    }else if(2 < psplit.length){
297                        throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
298                    }else{
299                        v = v.toFixed(0);
300                    }
301               
302                    var fnum = v.toString();
303                    if(hasComma){
304                        psplit = fnum.split('.');
305               
306                        var cnum = psplit[0], parr = [], j = cnum.length, m = Math.floor(j / 3), n = cnum.length % 3 || 3;
307               
308                        for(var i = 0; i < j; i += n){
309                            if(i != 0){
310                                n = 3;
311                            }
312                            parr[parr.length] = cnum.substr(i, n);
313                            m -= 1;
314                        }
315                        fnum = parr.join(comma);
316                        if(psplit[1]){
317                            fnum += dec + psplit[1];
318                        }
319                    }
320               
321                    return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
322        },
323
324        /**
325         * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
326         * @param {String} format Any valid number format string for {@link #number}
327         * @return {Function} The number formatting function
328         */
329        numberRenderer : function(format){
330            return function(v){
331                return Ext.util.Format.number(v, format);
332            };
333        },
334
335        /**
336         * Selectively do a plural form of a word based on a numeric value. For example, in a template,
337         * {commentCount:plural("Comment")}  would result in "1 Comment" if commentCount was 1 or would be "x Comments"
338         * if the value is 0 or greater than 1.
339         * @param {Number} value The value to compare against
340         * @param {String} singular The singular form of the word
341         * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
342         */
343        plural : function(v, s, p){
344            return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
345        },
346       
347        /**
348         * Converts newline characters to the HTML tag &lt;br/>
349         * @param {String} The string value to format.
350         * @return {String} The string with embedded &lt;br/> tags in place of newlines.
351         */
352        nl2br : function(v){
353            return v === undefined || v === null ? '' : v.replace(/\n/g, '<br/>');
354        }
355    }
356}();
Note: See TracBrowser for help on using the repository browser.