Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / util / Format.js
1 /**
2  * @class Ext.util.Format
3
4 This class is a centralized place for formatting functions inside the library. It includes
5 functions to format various different types of data, such as text, dates and numeric values.
6
7 __Localization__
8 This class contains several options for localization. These can be set once the library has loaded,
9 all calls to the functions from that point will use the locale settings that were specified.
10 Options include:
11 - thousandSeparator
12 - decimalSeparator
13 - currenyPrecision
14 - currencySign
15 - currencyAtEnd
16 This class also uses the default date format defined here: {@link Ext.date#defaultFormat}.
17
18 __Using with renderers__
19 There are two helper functions that return a new function that can be used in conjunction with 
20 grid renderers:
21
22     columns: [{
23         dataIndex: 'date',
24         renderer: Ext.util.Format.dateRenderer('Y-m-d')
25     }, {
26         dataIndex: 'time',
27         renderer: Ext.util.Format.numberRenderer('0.000')
28     }]
29     
30 Functions that only take a single argument can also be passed directly:
31     columns: [{
32         dataIndex: 'cost',
33         renderer: Ext.util.Format.usMoney
34     }, {
35         dataIndex: 'productCode',
36         renderer: Ext.util.Format.uppercase
37     }]
38     
39 __Using with XTemplates__
40 XTemplates can also directly use Ext.util.Format functions:
41
42     new Ext.XTemplate([
43         'Date: {startDate:date("Y-m-d")}',
44         'Cost: {cost:usMoney}'
45     ]);
46
47  * @markdown
48  * @singleton
49  */
50 (function() {
51     Ext.ns('Ext.util');
52
53     Ext.util.Format = {};
54     var UtilFormat     = Ext.util.Format,
55         stripTagsRE    = /<\/?[^>]+>/gi,
56         stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
57         nl2brRe        = /\r?\n/g,
58
59         // A RegExp to remove from a number format string, all characters except digits and '.'
60         formatCleanRe  = /[^\d\.]/g,
61
62         // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
63         // Created on first use. The local decimal separator character must be initialized for this to be created.
64         I18NFormatCleanRe;
65
66     Ext.apply(UtilFormat, {
67         /**
68          * @type String
69          * @property thousandSeparator
70          * <p>The character that the {@link #number} function uses as a thousand separator.</p>
71          * <p>This defaults to <code>,</code>, but may be overridden in a locale file.</p>
72          */
73         thousandSeparator: ',',
74
75         /**
76          * @type String
77          * @property decimalSeparator
78          * <p>The character that the {@link #number} function uses as a decimal point.</p>
79          * <p>This defaults to <code>.</code>, but may be overridden in a locale file.</p>
80          */
81         decimalSeparator: '.',
82
83         /**
84          * @type Number
85          * @property currencyPrecision
86          * <p>The number of decimal places that the {@link #currency} function displays.</p>
87          * <p>This defaults to <code>2</code>, but may be overridden in a locale file.</p>
88          */
89         currencyPrecision: 2,
90
91         /**
92          * @type String
93          * @property currencySign
94          * <p>The currency sign that the {@link #currency} function displays.</p>
95          * <p>This defaults to <code>$</code>, but may be overridden in a locale file.</p>
96          */
97         currencySign: '$',
98
99         /**
100          * @type Boolean
101          * @property currencyAtEnd
102          * <p>This may be set to <code>true</code> to make the {@link #currency} function
103          * append the currency sign to the formatted value.</p>
104          * <p>This defaults to <code>false</code>, but may be overridden in a locale file.</p>
105          */
106         currencyAtEnd: false,
107
108         /**
109          * Checks a reference and converts it to empty string if it is undefined
110          * @param {Mixed} value Reference to check
111          * @return {Mixed} Empty string if converted, otherwise the original value
112          */
113         undef : function(value) {
114             return value !== undefined ? value : "";
115         },
116
117         /**
118          * Checks a reference and converts it to the default value if it's empty
119          * @param {Mixed} value Reference to check
120          * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
121          * @return {String}
122          */
123         defaultValue : function(value, defaultValue) {
124             return value !== undefined && value !== '' ? value : defaultValue;
125         },
126
127         /**
128          * Returns a substring from within an original string
129          * @param {String} value The original text
130          * @param {Number} start The start index of the substring
131          * @param {Number} length The length of the substring
132          * @return {String} The substring
133          */
134         substr : function(value, start, length) {
135             return String(value).substr(start, length);
136         },
137
138         /**
139          * Converts a string to all lower case letters
140          * @param {String} value The text to convert
141          * @return {String} The converted text
142          */
143         lowercase : function(value) {
144             return String(value).toLowerCase();
145         },
146
147         /**
148          * Converts a string to all upper case letters
149          * @param {String} value The text to convert
150          * @return {String} The converted text
151          */
152         uppercase : function(value) {
153             return String(value).toUpperCase();
154         },
155
156         /**
157          * Format a number as US currency
158          * @param {Number/String} value The numeric value to format
159          * @return {String} The formatted currency string
160          */
161         usMoney : function(v) {
162             return UtilFormat.currency(v, '$', 2);
163         },
164
165         /**
166          * Format a number as a currency
167          * @param {Number/String} value The numeric value to format
168          * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
169          * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
170          * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
171          * @return {String} The formatted currency string
172          */
173         currency: function(v, currencySign, decimals, end) {
174             var negativeSign = '',
175                 format = ",0",
176                 i = 0;
177             v = v - 0;
178             if (v < 0) {
179                 v = -v;
180                 negativeSign = '-';
181             }
182             decimals = decimals || UtilFormat.currencyPrecision;
183             format += format + (decimals > 0 ? '.' : '');
184             for (; i < decimals; i++) {
185                 format += '0';
186             }
187             v = UtilFormat.number(v, format); 
188             if ((end || UtilFormat.currencyAtEnd) === true) {
189                 return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
190             } else {
191                 return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
192             }
193         },
194
195         /**
196          * Formats the passed date using the specified format pattern.
197          * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
198          * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
199          * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
200          * @return {String} The formatted date string.
201          */
202         date: function(v, format) {
203             if (!v) {
204                 return "";
205             }
206             if (!Ext.isDate(v)) {
207                 v = new Date(Date.parse(v));
208             }
209             return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
210         },
211
212         /**
213          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
214          * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
215          * @return {Function} The date formatting function
216          */
217         dateRenderer : function(format) {
218             return function(v) {
219                 return UtilFormat.date(v, format);
220             };
221         },
222
223         /**
224          * Strips all HTML tags
225          * @param {Mixed} value The text from which to strip tags
226          * @return {String} The stripped text
227          */
228         stripTags : function(v) {
229             return !v ? v : String(v).replace(stripTagsRE, "");
230         },
231
232         /**
233          * Strips all script tags
234          * @param {Mixed} value The text from which to strip script tags
235          * @return {String} The stripped text
236          */
237         stripScripts : function(v) {
238             return !v ? v : String(v).replace(stripScriptsRe, "");
239         },
240
241         /**
242          * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
243          * @param {Number/String} size The numeric value to format
244          * @return {String} The formatted file size
245          */
246         fileSize : function(size) {
247             if (size < 1024) {
248                 return size + " bytes";
249             } else if (size < 1048576) {
250                 return (Math.round(((size*10) / 1024))/10) + " KB";
251             } else {
252                 return (Math.round(((size*10) / 1048576))/10) + " MB";
253             }
254         },
255
256         /**
257          * It does simple math for use in a template, for example:<pre><code>
258          * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
259          * </code></pre>
260          * @return {Function} A function that operates on the passed value.
261          */
262         math : function(){
263             var fns = {};
264
265             return function(v, a){
266                 if (!fns[a]) {
267                     fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
268                 }
269                 return fns[a](v);
270             };
271         }(),
272
273         /**
274          * Rounds the passed number to the required decimal precision.
275          * @param {Number/String} value The numeric value to round.
276          * @param {Number} precision The number of decimal places to which to round the first parameter's value.
277          * @return {Number} The rounded value.
278          */
279         round : function(value, precision) {
280             var result = Number(value);
281             if (typeof precision == 'number') {
282                 precision = Math.pow(10, precision);
283                 result = Math.round(value * precision) / precision;
284             }
285             return result;
286         },
287
288         /**
289          * <p>Formats the passed number according to the passed format string.</p>
290          * <p>The number of digits after the decimal separator character specifies the number of
291          * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
292          * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
293          * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
294          * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
295          * <p><b>New to Ext4</b></p>
296          * <p>Locale-specific characters are always used in the formatted output when inserting
297          * thousand and decimal separators.</p>
298          * <p>The format string must specify separator characters according to US/UK conventions ("," as the
299          * thousand separator, and "." as the decimal separator)</p>
300          * <p>To allow specification of format strings according to local conventions for separator characters, add
301          * the string <code>/i</code> to the end of the format string.</p>
302          * <div style="margin-left:40px">examples (123456.789):
303          * <div style="margin-left:10px">
304          * 0 - (123456) show only digits, no precision<br>
305          * 0.00 - (123456.78) show only digits, 2 precision<br>
306          * 0.0000 - (123456.7890) show only digits, 4 precision<br>
307          * 0,000 - (123,456) show comma and digits, no precision<br>
308          * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
309          * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
310          * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
311          * For example: 0.000,00/i
312          * </div></div>
313          * @param {Number} v The number to format.
314          * @param {String} format The way you would like to format this text.
315          * @return {String} The formatted number.
316          */
317         number:
318             function(v, formatString) {
319             if (!formatString) {
320                 return v;
321             }
322             v = Ext.Number.from(v, NaN);
323             if (isNaN(v)) {
324                 return '';
325             }
326             var comma = UtilFormat.thousandSeparator,
327                 dec   = UtilFormat.decimalSeparator,
328                 i18n  = false,
329                 neg   = v < 0,
330                 hasComma,
331                 psplit;
332
333             v = Math.abs(v);
334
335             // The "/i" suffix allows caller to use a locale-specific formatting string.
336             // Clean the format string by removing all but numerals and the decimal separator.
337             // Then split the format string into pre and post decimal segments according to *what* the
338             // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
339             if (formatString.substr(formatString.length - 2) == '/i') {
340                 if (!I18NFormatCleanRe) {
341                     I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
342                 }
343                 formatString = formatString.substr(0, formatString.length - 2);
344                 i18n   = true;
345                 hasComma = formatString.indexOf(comma) != -1;
346                 psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
347             } else {
348                 hasComma = formatString.indexOf(',') != -1;
349                 psplit = formatString.replace(formatCleanRe, '').split('.');
350             }
351
352             if (1 < psplit.length) {
353                 v = v.toFixed(psplit[1].length);
354             } else if(2 < psplit.length) {
355                 //<debug>
356                 Ext.Error.raise({
357                     sourceClass: "Ext.util.Format",
358                     sourceMethod: "number",
359                     value: v,
360                     formatString: formatString,
361                     msg: "Invalid number format, should have no more than 1 decimal"
362                 });
363                 //</debug>
364             } else {
365                 v = v.toFixed(0);
366             }
367
368             var fnum = v.toString();
369
370             psplit = fnum.split('.');
371
372             if (hasComma) {
373                 var cnum = psplit[0],
374                     parr = [],
375                     j    = cnum.length,
376                     m    = Math.floor(j / 3),
377                     n    = cnum.length % 3 || 3,
378                     i;
379
380                 for (i = 0; i < j; i += n) {
381                     if (i !== 0) {
382                         n = 3;
383                     }
384
385                     parr[parr.length] = cnum.substr(i, n);
386                     m -= 1;
387                 }
388                 fnum = parr.join(comma);
389                 if (psplit[1]) {
390                     fnum += dec + psplit[1];
391                 }
392             } else {
393                 if (psplit[1]) {
394                     fnum = psplit[0] + dec + psplit[1];
395                 }
396             }
397
398             return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
399         },
400
401         /**
402          * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
403          * @param {String} format Any valid number format string for {@link #number}
404          * @return {Function} The number formatting function
405          */
406         numberRenderer : function(format) {
407             return function(v) {
408                 return UtilFormat.number(v, format);
409             };
410         },
411
412         /**
413          * Selectively do a plural form of a word based on a numeric value. For example, in a template,
414          * {commentCount:plural("Comment")}  would result in "1 Comment" if commentCount was 1 or would be "x Comments"
415          * if the value is 0 or greater than 1.
416          * @param {Number} value The value to compare against
417          * @param {String} singular The singular form of the word
418          * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
419          */
420         plural : function(v, s, p) {
421             return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
422         },
423
424         /**
425          * Converts newline characters to the HTML tag &lt;br/>
426          * @param {String} The string value to format.
427          * @return {String} The string with embedded &lt;br/> tags in place of newlines.
428          */
429         nl2br : function(v) {
430             return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
431         },
432
433         /**
434          * Capitalize the given string. See {@link Ext.String#capitalize}.
435          */
436         capitalize: Ext.String.capitalize,
437
438         /**
439          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length.
440          * See {@link Ext.String#ellipsis}.
441          */
442         ellipsis: Ext.String.ellipsis,
443
444         /**
445          * Formats to a string. See {@link Ext.String#format}
446          */
447         format: Ext.String.format,
448
449         /**
450          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
451          * See {@link Ext.string#htmlDecode}.
452          */
453         htmlDecode: Ext.String.htmlDecode,
454
455         /**
456          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
457          * See {@link Ext.String#htmlEncode}.
458          */
459         htmlEncode: Ext.String.htmlEncode,
460
461         /**
462          * Adds left padding to a string. See {@link Ext.String#leftPad}
463          */
464         leftPad: Ext.String.leftPad,
465
466         /**
467          * Trims any whitespace from either side of a string. See {@link Ext.String#trim}.
468          */
469         trim : Ext.String.trim,
470
471         /**
472          * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
473          * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
474          * @param {Number|String} v The encoded margins
475          * @return {Object} An object with margin sizes for top, right, bottom and left
476          */
477         parseBox : function(box) {
478             if (Ext.isNumber(box)) {
479                 box = box.toString();
480             }
481             var parts  = box.split(' '),
482                 ln = parts.length;
483
484             if (ln == 1) {
485                 parts[1] = parts[2] = parts[3] = parts[0];
486             }
487             else if (ln == 2) {
488                 parts[2] = parts[0];
489                 parts[3] = parts[1];
490             }
491             else if (ln == 3) {
492                 parts[3] = parts[1];
493             }
494
495             return {
496                 top   :parseInt(parts[0], 10) || 0,
497                 right :parseInt(parts[1], 10) || 0,
498                 bottom:parseInt(parts[2], 10) || 0,
499                 left  :parseInt(parts[3], 10) || 0
500             };
501         },
502
503         /**
504          * Escapes the passed string for use in a regular expression
505          * @param {String} str
506          * @return {String}
507          */
508         escapeRegex : function(s) {
509             return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
510         }
511     });
512 })();