PageRenderTime 26ms CodeModel.GetById 15ms app.highlight 6ms RepoModel.GetById 0ms app.codeStats 0ms

/ext-4.0.7/docs/source/Format.html

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