PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/tine20/library/ExtJS/src/util/Format.js

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