Format.html 23 KB

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