Upgrade to ExtJS 3.3.0 - Released 10/06/2010
[extjs.git] / src / util / Format.js
1 /*!
2  * Ext JS Library 3.3.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
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  */
12 Ext.util.Format = function() {
13     var trimRe         = /^\s+|\s+$/g,
14         stripTagsRE    = /<\/?[^>]+>/gi,
15         stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
16         nl2brRe        = /\r?\n/g;
17
18     return {
19         /**
20          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
21          * @param {String} value The string to truncate
22          * @param {Number} length The maximum length to allow before truncating
23          * @param {Boolean} word True to try to find a common work break
24          * @return {String} The converted text
25          */
26         ellipsis : function(value, len, word) {
27             if (value && value.length > len) {
28                 if (word) {
29                     var vs    = value.substr(0, len - 2),
30                         index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
31                     if (index == -1 || index < (len - 15)) {
32                         return value.substr(0, len - 3) + "...";
33                     } else {
34                         return vs.substr(0, index) + "...";
35                     }
36                 } else {
37                     return value.substr(0, len - 3) + "...";
38                 }
39             }
40             return value;
41         },
42
43         /**
44          * Checks a reference and converts it to empty string if it is undefined
45          * @param {Mixed} value Reference to check
46          * @return {Mixed} Empty string if converted, otherwise the original value
47          */
48         undef : function(value) {
49             return value !== undefined ? value : "";
50         },
51
52         /**
53          * Checks a reference and converts it to the default value if it's empty
54          * @param {Mixed} value Reference to check
55          * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
56          * @return {String}
57          */
58         defaultValue : function(value, defaultValue) {
59             return value !== undefined && value !== '' ? value : defaultValue;
60         },
61
62         /**
63          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
64          * @param {String} value The string to encode
65          * @return {String} The encoded text
66          */
67         htmlEncode : function(value) {
68             return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
69         },
70
71         /**
72          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
73          * @param {String} value The string to decode
74          * @return {String} The decoded text
75          */
76         htmlDecode : function(value) {
77             return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
78         },
79
80         /**
81          * Trims any whitespace from either side of a string
82          * @param {String} value The text to trim
83          * @return {String} The trimmed text
84          */
85         trim : function(value) {
86             return String(value).replace(trimRe, "");
87         },
88
89         /**
90          * Returns a substring from within an original string
91          * @param {String} value The original text
92          * @param {Number} start The start index of the substring
93          * @param {Number} length The length of the substring
94          * @return {String} The substring
95          */
96         substr : function(value, start, length) {
97             return String(value).substr(start, length);
98         },
99
100         /**
101          * Converts a string to all lower case letters
102          * @param {String} value The text to convert
103          * @return {String} The converted text
104          */
105         lowercase : function(value) {
106             return String(value).toLowerCase();
107         },
108
109         /**
110          * Converts a string to all upper case letters
111          * @param {String} value The text to convert
112          * @return {String} The converted text
113          */
114         uppercase : function(value) {
115             return String(value).toUpperCase();
116         },
117
118         /**
119          * Converts the first character only of a string to upper case
120          * @param {String} value The text to convert
121          * @return {String} The converted text
122          */
123         capitalize : function(value) {
124             return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
125         },
126
127         // private
128         call : function(value, fn) {
129             if (arguments.length > 2) {
130                 var args = Array.prototype.slice.call(arguments, 2);
131                 args.unshift(value);
132                 return eval(fn).apply(window, args);
133             } else {
134                 return eval(fn).call(window, value);
135             }
136         },
137
138         /**
139          * Format a number as US currency
140          * @param {Number/String} value The numeric value to format
141          * @return {String} The formatted currency string
142          */
143         usMoney : function(v) {
144             v = (Math.round((v-0)*100))/100;
145             v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
146             v = String(v);
147             var ps = v.split('.'),
148                 whole = ps[0],
149                 sub = ps[1] ? '.'+ ps[1] : '.00',
150                 r = /(\d+)(\d{3})/;
151             while (r.test(whole)) {
152                 whole = whole.replace(r, '$1' + ',' + '$2');
153             }
154             v = whole + sub;
155             if (v.charAt(0) == '-') {
156                 return '-$' + v.substr(1);
157             }
158             return "$" +  v;
159         },
160
161         /**
162          * Parse a value into a formatted date using the specified format pattern.
163          * @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)
164          * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
165          * @return {String} The formatted date string
166          */
167         date : function(v, format) {
168             if (!v) {
169                 return "";
170             }
171             if (!Ext.isDate(v)) {
172                 v = new Date(Date.parse(v));
173             }
174             return v.dateFormat(format || "m/d/Y");
175         },
176
177         /**
178          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
179          * @param {String} format Any valid date format string
180          * @return {Function} The date formatting function
181          */
182         dateRenderer : function(format) {
183             return function(v) {
184                 return Ext.util.Format.date(v, format);
185             };
186         },
187
188         /**
189          * Strips all HTML tags
190          * @param {Mixed} value The text from which to strip tags
191          * @return {String} The stripped text
192          */
193         stripTags : function(v) {
194             return !v ? v : String(v).replace(stripTagsRE, "");
195         },
196
197         /**
198          * Strips all script tags
199          * @param {Mixed} value The text from which to strip script tags
200          * @return {String} The stripped text
201          */
202         stripScripts : function(v) {
203             return !v ? v : String(v).replace(stripScriptsRe, "");
204         },
205
206         /**
207          * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
208          * @param {Number/String} size The numeric value to format
209          * @return {String} The formatted file size
210          */
211         fileSize : function(size) {
212             if (size < 1024) {
213                 return size + " bytes";
214             } else if (size < 1048576) {
215                 return (Math.round(((size*10) / 1024))/10) + " KB";
216             } else {
217                 return (Math.round(((size*10) / 1048576))/10) + " MB";
218             }
219         },
220
221         /**
222          * It does simple math for use in a template, for example:<pre><code>
223          * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
224          * </code></pre>
225          * @return {Function} A function that operates on the passed value.
226          */
227         math : function(){
228             var fns = {};
229             
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
304             psplit = fnum.split('.');
305
306             if (hasComma) {
307                 var cnum = psplit[0], 
308                     parr = [], 
309                     j    = cnum.length, 
310                     m    = Math.floor(j / 3),
311                     n    = cnum.length % 3 || 3,
312                     i;
313
314                 for (i = 0; i < j; i += n) {
315                     if (i != 0) {
316                         n = 3;
317                     }
318                     
319                     parr[parr.length] = cnum.substr(i, n);
320                     m -= 1;
321                 }
322                 fnum = parr.join(comma);
323                 if (psplit[1]) {
324                     fnum += dec + psplit[1];
325                 }
326             } else {
327                 if (psplit[1]) {
328                     fnum = psplit[0] + dec + psplit[1];
329                 }
330             }
331
332             return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
333         },
334
335         /**
336          * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
337          * @param {String} format Any valid number format string for {@link #number}
338          * @return {Function} The number formatting function
339          */
340         numberRenderer : function(format) {
341             return function(v) {
342                 return Ext.util.Format.number(v, format);
343             };
344         },
345
346         /**
347          * Selectively do a plural form of a word based on a numeric value. For example, in a template,
348          * {commentCount:plural("Comment")}  would result in "1 Comment" if commentCount was 1 or would be "x Comments"
349          * if the value is 0 or greater than 1.
350          * @param {Number} value The value to compare against
351          * @param {String} singular The singular form of the word
352          * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
353          */
354         plural : function(v, s, p) {
355             return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
356         },
357
358         /**
359          * Converts newline characters to the HTML tag &lt;br/>
360          * @param {String} The string value to format.
361          * @return {String} The string with embedded &lt;br/> tags in place of newlines.
362          */
363         nl2br : function(v) {
364             return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
365         }
366     };
367 }();