kbn.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. define(['jquery','underscore','moment','chromath'],
  2. function($, _, moment) {
  3. 'use strict';
  4. var kbn = {};
  5. /**
  6. * Calculate a graph interval
  7. *
  8. * from:: Date object containing the start time
  9. * to:: Date object containing the finish time
  10. * size:: Calculate to approximately this many bars
  11. * user_interval:: User specified histogram interval
  12. *
  13. */
  14. kbn.calculate_interval = function(from,to,size,user_interval) {
  15. if(_.isObject(from)) {
  16. from = from.valueOf();
  17. }
  18. if(_.isObject(to)) {
  19. to = to.valueOf();
  20. }
  21. return user_interval === 0 ? kbn.round_interval((to - from)/size) : user_interval;
  22. };
  23. kbn.round_interval = function(interval) {
  24. switch (true) {
  25. // 0.5s
  26. case (interval <= 500):
  27. return 100; // 0.1s
  28. // 5s
  29. case (interval <= 5000):
  30. return 1000; // 1s
  31. // 7.5s
  32. case (interval <= 7500):
  33. return 5000; // 5s
  34. // 15s
  35. case (interval <= 15000):
  36. return 10000; // 10s
  37. // 45s
  38. case (interval <= 45000):
  39. return 30000; // 30s
  40. // 3m
  41. case (interval <= 180000):
  42. return 60000; // 1m
  43. // 9m
  44. case (interval <= 450000):
  45. return 300000; // 5m
  46. // 20m
  47. case (interval <= 1200000):
  48. return 600000; // 10m
  49. // 45m
  50. case (interval <= 2700000):
  51. return 1800000; // 30m
  52. // 2h
  53. case (interval <= 7200000):
  54. return 3600000; // 1h
  55. // 6h
  56. case (interval <= 21600000):
  57. return 10800000; // 3h
  58. // 24h
  59. case (interval <= 86400000):
  60. return 43200000; // 12h
  61. // 48h
  62. case (interval <= 172800000):
  63. return 86400000; // 24h
  64. // 1w
  65. case (interval <= 604800000):
  66. return 86400000; // 24h
  67. // 3w
  68. case (interval <= 1814400000):
  69. return 604800000; // 1w
  70. // 2y
  71. case (interval < 3628800000):
  72. return 2592000000; // 30d
  73. default:
  74. return 31536000000; // 1y
  75. }
  76. };
  77. kbn.secondsToHms = function(seconds){
  78. var numyears = Math.floor(seconds / 31536000);
  79. if(numyears){
  80. return numyears + 'y';
  81. }
  82. var numdays = Math.floor((seconds % 31536000) / 86400);
  83. if(numdays){
  84. return numdays + 'd';
  85. }
  86. var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
  87. if(numhours){
  88. return numhours + 'h';
  89. }
  90. var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
  91. if(numminutes){
  92. return numminutes + 'm';
  93. }
  94. var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
  95. if(numseconds){
  96. return numseconds + 's';
  97. }
  98. return 'less then a second'; //'just now' //or other string you like;
  99. };
  100. kbn.to_percent = function(number,outof) {
  101. return Math.floor((number/outof)*10000)/100 + "%";
  102. };
  103. kbn.addslashes = function(str) {
  104. str = str.replace(/\\/g, '\\\\');
  105. str = str.replace(/\'/g, '\\\'');
  106. str = str.replace(/\"/g, '\\"');
  107. str = str.replace(/\0/g, '\\0');
  108. return str;
  109. };
  110. kbn.interval_regex = /(\d+(?:\.\d+)?)([Mwdhmsy])/;
  111. // histogram & trends
  112. kbn.intervals_in_seconds = {
  113. y: 31536000,
  114. M: 2592000,
  115. w: 604800,
  116. d: 86400,
  117. h: 3600,
  118. m: 60,
  119. s: 1
  120. };
  121. kbn.describe_interval = function (string) {
  122. var matches = string.match(kbn.interval_regex);
  123. if (!matches || !_.has(kbn.intervals_in_seconds, matches[2])) {
  124. throw new Error('Invalid interval string, expexcting a number followed by one of "Mwdhmsy"');
  125. } else {
  126. return {
  127. sec: kbn.intervals_in_seconds[matches[2]],
  128. type: matches[2],
  129. count: parseInt(matches[1], 10)
  130. };
  131. }
  132. };
  133. kbn.interval_to_ms = function(string) {
  134. var info = kbn.describe_interval(string);
  135. return info.sec * 1000 * info.count;
  136. };
  137. kbn.interval_to_seconds = function (string) {
  138. var info = kbn.describe_interval(string);
  139. return info.sec * info.count;
  140. };
  141. // This should go away, moment.js can do this
  142. kbn.time_ago = function(string) {
  143. return new Date(new Date().getTime() - (kbn.interval_to_ms(string)));
  144. };
  145. /* This is a simplified version of elasticsearch's date parser */
  146. kbn.parseDate = function(text) {
  147. if(_.isDate(text)) {
  148. return text;
  149. }
  150. var time,
  151. mathString = "",
  152. index,
  153. parseString;
  154. if (text.substring(0,3) === "now") {
  155. time = new Date();
  156. mathString = text.substring("now".length);
  157. } else {
  158. index = text.indexOf("||");
  159. parseString;
  160. if (index === -1) {
  161. parseString = text;
  162. mathString = ""; // nothing else
  163. } else {
  164. parseString = text.substring(0, index);
  165. mathString = text.substring(index + 2);
  166. }
  167. // We're going to just require ISO8601 timestamps, k?
  168. time = new Date(parseString);
  169. }
  170. if (!mathString.length) {
  171. return time;
  172. }
  173. //return [time,parseString,mathString];
  174. return kbn.parseDateMath(mathString, time);
  175. };
  176. kbn.parseDateMath = function(mathString, time, roundUp) {
  177. var dateTime = moment(time);
  178. for (var i = 0; i < mathString.length; ) {
  179. var c = mathString.charAt(i++),
  180. type,
  181. num,
  182. unit;
  183. if (c === '/') {
  184. type = 0;
  185. } else if (c === '+') {
  186. type = 1;
  187. } else if (c === '-') {
  188. type = 2;
  189. } else {
  190. return false;
  191. }
  192. if (isNaN(mathString.charAt(i))) {
  193. num = 1;
  194. } else {
  195. var numFrom = i;
  196. while (!isNaN(mathString.charAt(i))) {
  197. i++;
  198. }
  199. num = parseInt(mathString.substring(numFrom, i),10);
  200. }
  201. if (type === 0) {
  202. // rounding is only allowed on whole numbers
  203. if (num !== 1) {
  204. return false;
  205. }
  206. }
  207. unit = mathString.charAt(i++);
  208. switch (unit) {
  209. case 'y':
  210. if (type === 0) {
  211. roundUp ? dateTime.endOf('year') : dateTime.startOf('year');
  212. } else if (type === 1) {
  213. dateTime.add('years',num);
  214. } else if (type === 2) {
  215. dateTime.subtract('years',num);
  216. }
  217. break;
  218. case 'M':
  219. if (type === 0) {
  220. roundUp ? dateTime.endOf('month') : dateTime.startOf('month');
  221. } else if (type === 1) {
  222. dateTime.add('months',num);
  223. } else if (type === 2) {
  224. dateTime.subtract('months',num);
  225. }
  226. break;
  227. case 'w':
  228. if (type === 0) {
  229. roundUp ? dateTime.endOf('week') : dateTime.startOf('week');
  230. } else if (type === 1) {
  231. dateTime.add('weeks',num);
  232. } else if (type === 2) {
  233. dateTime.subtract('weeks',num);
  234. }
  235. break;
  236. case 'd':
  237. if (type === 0) {
  238. roundUp ? dateTime.endOf('day') : dateTime.startOf('day');
  239. } else if (type === 1) {
  240. dateTime.add('days',num);
  241. } else if (type === 2) {
  242. dateTime.subtract('days',num);
  243. }
  244. break;
  245. case 'h':
  246. case 'H':
  247. if (type === 0) {
  248. roundUp ? dateTime.endOf('hour') : dateTime.startOf('hour');
  249. } else if (type === 1) {
  250. dateTime.add('hours',num);
  251. } else if (type === 2) {
  252. dateTime.subtract('hours',num);
  253. }
  254. break;
  255. case 'm':
  256. if (type === 0) {
  257. roundUp ? dateTime.endOf('minute') : dateTime.startOf('minute');
  258. } else if (type === 1) {
  259. dateTime.add('minutes',num);
  260. } else if (type === 2) {
  261. dateTime.subtract('minutes',num);
  262. }
  263. break;
  264. case 's':
  265. if (type === 0) {
  266. roundUp ? dateTime.endOf('second') : dateTime.startOf('second');
  267. } else if (type === 1) {
  268. dateTime.add('seconds',num);
  269. } else if (type === 2) {
  270. dateTime.subtract('seconds',num);
  271. }
  272. break;
  273. default:
  274. return false;
  275. }
  276. }
  277. return dateTime.toDate();
  278. };
  279. // LOL. hahahahaha. DIE.
  280. kbn.flatten_json = function(object,root,array) {
  281. if (typeof array === 'undefined') {
  282. array = {};
  283. }
  284. if (typeof root === 'undefined') {
  285. root = '';
  286. }
  287. for(var index in object) {
  288. var obj = object[index];
  289. var rootname = root.length === 0 ? index : root + '.' + index;
  290. if(typeof obj === 'object' ) {
  291. if(_.isArray(obj)) {
  292. if(obj.length > 0 && typeof obj[0] === 'object') {
  293. var strval = '';
  294. for (var objidx = 0, objlen = obj.length; objidx < objlen; objidx++) {
  295. if (objidx > 0) {
  296. strval = strval + ', ';
  297. }
  298. strval = strval + JSON.stringify(obj[objidx]);
  299. }
  300. array[rootname] = strval;
  301. } else if(obj.length === 1 && _.isNumber(obj[0])) {
  302. array[rootname] = parseFloat(obj[0]);
  303. } else {
  304. array[rootname] = typeof obj === 'undefined' ? null : obj;
  305. }
  306. } else {
  307. kbn.flatten_json(obj,rootname,array);
  308. }
  309. } else {
  310. array[rootname] = typeof obj === 'undefined' ? null : obj;
  311. }
  312. }
  313. return kbn.sortObj(array);
  314. };
  315. kbn.xmlEnt = function(value) {
  316. if(_.isString(value)) {
  317. var stg1 = value.replace(/</g, '&lt;')
  318. .replace(/>/g, '&gt;')
  319. .replace(/\r\n/g, '<br/>')
  320. .replace(/\r/g, '<br/>')
  321. .replace(/\n/g, '<br/>')
  322. .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
  323. .replace(/ /g, '&nbsp;&nbsp;')
  324. .replace(/&lt;del&gt;/g, '<del>')
  325. .replace(/&lt;\/del&gt;/g, '</del>');
  326. return stg1;
  327. } else {
  328. return value;
  329. }
  330. };
  331. kbn.sortObj = function(arr) {
  332. // Setup Arrays
  333. var sortedKeys = [];
  334. var sortedObj = {};
  335. var i;
  336. // Separate keys and sort them
  337. for (i in arr) {
  338. sortedKeys.push(i);
  339. }
  340. sortedKeys.sort();
  341. // Reconstruct sorted obj based on keys
  342. for (i in sortedKeys) {
  343. sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
  344. }
  345. return sortedObj;
  346. };
  347. kbn.query_color_dot = function (color, diameter) {
  348. return '<div class="icon-circle" style="' + [
  349. 'display:inline-block',
  350. 'color:' + color,
  351. 'font-size:' + diameter + 'px',
  352. ].join(';') + '"></div>';
  353. };
  354. kbn.colorSteps = function(col,steps) {
  355. var _d = steps > 5 ? 1.6/steps : 0.25, // distance between steps
  356. _p = []; // adjustment percentage
  357. // Create a range of numbers between -0.8 and 0.8
  358. for(var i = 1; i<steps+1; i+=1) {
  359. _p.push(i%2 ? ((i-1)*_d*-1)/2 : i*_d/2);
  360. }
  361. // Create the color range
  362. return _.map(_p.sort(function(a,b){return a-b;}),function(v) {
  363. return v<0 ? Chromath.darken(col,v*-1).toString() : Chromath.lighten(col,v).toString();
  364. });
  365. };
  366. // Find the smallest missing number in an array
  367. kbn.smallestMissing = function(arr,start,end) {
  368. start = start || 0;
  369. end = end || arr.length-1;
  370. if(start > end) {
  371. return end + 1;
  372. }
  373. if(start !== arr[start]) {
  374. return start;
  375. }
  376. var middle = Math.floor((start + end) / 2);
  377. if (arr[middle] > middle) {
  378. return kbn.smallestMissing(arr, start, middle);
  379. } else {
  380. return kbn.smallestMissing(arr, middle + 1, end);
  381. }
  382. };
  383. kbn.byteFormat = function(size, decimals) {
  384. var ext, steps = 0;
  385. if(_.isUndefined(decimals)) {
  386. decimals = 2;
  387. } else if (decimals === 0) {
  388. decimals = undefined;
  389. }
  390. while (Math.abs(size) >= 1024) {
  391. steps++;
  392. size /= 1024;
  393. }
  394. switch (steps) {
  395. case 0:
  396. ext = " B";
  397. break;
  398. case 1:
  399. ext = " KB";
  400. break;
  401. case 2:
  402. ext = " MB";
  403. break;
  404. case 3:
  405. ext = " GB";
  406. break;
  407. case 4:
  408. ext = " TB";
  409. break;
  410. case 5:
  411. ext = " PB";
  412. break;
  413. case 6:
  414. ext = " EB";
  415. break;
  416. case 7:
  417. ext = " ZB";
  418. break;
  419. case 8:
  420. ext = " YB";
  421. break;
  422. }
  423. return (size.toFixed(decimals) + ext);
  424. };
  425. kbn.bitFormat = function(size, decimals) {
  426. var ext, steps = 0;
  427. if(_.isUndefined(decimals)) {
  428. decimals = 2;
  429. } else if (decimals === 0) {
  430. decimals = undefined;
  431. }
  432. while (Math.abs(size) >= 1024) {
  433. steps++;
  434. size /= 1024;
  435. }
  436. switch (steps) {
  437. case 0:
  438. ext = " b";
  439. break;
  440. case 1:
  441. ext = " Kb";
  442. break;
  443. case 2:
  444. ext = " Mb";
  445. break;
  446. case 3:
  447. ext = " Gb";
  448. break;
  449. case 4:
  450. ext = " Tb";
  451. break;
  452. case 5:
  453. ext = " Pb";
  454. break;
  455. case 6:
  456. ext = " Eb";
  457. break;
  458. case 7:
  459. ext = " Zb";
  460. break;
  461. case 8:
  462. ext = " Yb";
  463. break;
  464. }
  465. return (size.toFixed(decimals) + ext);
  466. };
  467. kbn.shortFormat = function(size, decimals) {
  468. var ext, steps = 0;
  469. if(_.isUndefined(decimals)) {
  470. decimals = 2;
  471. } else if (decimals === 0) {
  472. decimals = undefined;
  473. }
  474. while (Math.abs(size) >= 1000) {
  475. steps++;
  476. size /= 1000;
  477. }
  478. switch (steps) {
  479. case 0:
  480. ext = "";
  481. break;
  482. case 1:
  483. ext = " K";
  484. break;
  485. case 2:
  486. ext = " Mil";
  487. break;
  488. case 3:
  489. ext = " Bil";
  490. break;
  491. case 4:
  492. ext = " Tri";
  493. break;
  494. case 5:
  495. ext = " Quadr";
  496. break;
  497. case 6:
  498. ext = " Quint";
  499. break;
  500. case 7:
  501. ext = " Sext";
  502. break;
  503. case 8:
  504. ext = " Sept";
  505. break;
  506. }
  507. return (size.toFixed(decimals) + ext);
  508. };
  509. kbn.getFormatFunction = function(formatName, decimals) {
  510. switch(formatName) {
  511. case 'short':
  512. return function(val) {
  513. return kbn.shortFormat(val, decimals);
  514. };
  515. case 'bytes':
  516. return function(val) {
  517. return kbn.byteFormat(val, decimals);
  518. };
  519. case 'bits':
  520. return function(val) {
  521. return kbn.bitFormat(val, decimals);
  522. };
  523. case 'ms':
  524. return function(val) {
  525. return kbn.msFormat(val, decimals);
  526. };
  527. case 'µs':
  528. return function(val) {
  529. return kbn.microsFormat(val, decimals);
  530. };
  531. default:
  532. return function(val) {
  533. return val % 1 === 0 ? val : val.toFixed(decimals);
  534. };
  535. }
  536. };
  537. kbn.msFormat = function(size, decimals) {
  538. if (size < 1000) {
  539. return size.toFixed(0) + " ms";
  540. }
  541. // Less than 1 min
  542. else if (size < 60000) {
  543. return (size / 1000).toFixed(decimals) + " s";
  544. }
  545. // Less than 1 hour, devide in minutes
  546. else if (size < 3600000) {
  547. return (size / 60000).toFixed(decimals) + " min";
  548. }
  549. // Less than one day, devide in hours
  550. else if (size < 86400000) {
  551. return (size / 3600000).toFixed(decimals) + " hour";
  552. }
  553. // Less than one week, devide in days
  554. else if (size < 604800000) {
  555. return (size / 86400000).toFixed(decimals) + " day";
  556. }
  557. // Less than one month, devide in weeks
  558. else if (size < 2.62974e9) {
  559. return (size / 604800000).toFixed(decimals) + " week";
  560. }
  561. // Less than one year, devide in weeks
  562. else if (size < 3.15569e10) {
  563. return (size / 2.62974e9).toFixed(decimals) + " year";
  564. }
  565. };
  566. kbn.microsFormat = function(size, decimals) {
  567. if (size < 1000) {
  568. return size.toFixed(0) + " µs";
  569. }
  570. else if (size < 1000000) {
  571. return (size / 1000).toFixed(decimals) + " ms";
  572. }
  573. else {
  574. return (size / 1000000).toFixed(decimals) + " s";
  575. }
  576. };
  577. return kbn;
  578. });