linear_time.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with this
  4. * work for additional information regarding copyright ownership. The ASF
  5. * licenses this file to you under the Apache License, Version 2.0 (the
  6. * "License"); you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. var App = require('app');
  18. var string_utils = require('utils/string_utils');
  19. /**
  20. * @class
  21. *
  22. * This is a view which GETs data from a URL and shows it as a time based line
  23. * graph. Time is shown on the X axis with data series shown on Y axis. It
  24. * optionally also has the ability to auto refresh itself over a given time
  25. * interval.
  26. *
  27. * This is an abstract class which is meant to be extended.
  28. *
  29. * Extending classes should override the following:
  30. * <ul>
  31. * <li>url - from where the data can be retrieved
  32. * <li>title - Title to be displayed when showing the chart
  33. * <li>id - which uniquely identifies this chart in any page
  34. * <li>#transformToSeries(jsonData) - function to map server data into graph
  35. * series
  36. * </ul>
  37. *
  38. * Extending classes could optionally override the following:
  39. * <ul>
  40. * <li>#colorForSeries(series) - function to get custom colors per series
  41. * </ul>
  42. *
  43. * @extends Ember.Object
  44. * @extends Ember.View
  45. */
  46. App.ChartLinearTimeView = Ember.View.extend({
  47. templateName: require('templates/main/charts/linear_time'),
  48. /**
  49. * The URL from which data can be retrieved.
  50. *
  51. * This property must be provided for the graph to show properly.
  52. *
  53. * @type String
  54. * @default null
  55. */
  56. url: null,
  57. /**
  58. * A unique ID for this chart.
  59. *
  60. * @type String
  61. * @default null
  62. */
  63. id: null,
  64. /**
  65. * Title to be shown under the chart.
  66. *
  67. * @type String
  68. * @default null
  69. */
  70. title: null,
  71. /**
  72. * @private
  73. *
  74. * @type Rickshaw.Graph
  75. * @default null
  76. */
  77. _graph: null,
  78. _popupGraph: null,
  79. popupSuffix: '-popup',
  80. isPopup: false,
  81. /**
  82. * Color palette used for this chart
  83. *
  84. * @private
  85. * @type String[]
  86. */
  87. _paletteScheme: [ 'rgba(181,182,169,0.4)', 'rgba(133,135,114,0.4)',
  88. 'rgba(120,95,67,0.4)', 'rgba(150,85,126,0.4)',
  89. 'rgba(70,130,180,0.4)', 'rgba(0,255,204,0.4)',
  90. 'rgba(255,105,180,0.4)', 'rgba(101,185,172,0.4)',
  91. 'rgba(115,192,58,0.4)', 'rgba(203,81,58,0.4)' ].reverse(),
  92. init: function () {
  93. this._super();
  94. },
  95. selector: function () {
  96. return '#' + this.get('elementId');
  97. }.property('elementId'),
  98. didInsertElement: function () {
  99. this._super();
  100. this.loadData();
  101. this.registerGraph();
  102. },
  103. registerGraph: function(){
  104. var graph = {
  105. name: this.get('title'),
  106. id: this.get('elementId'),
  107. popupId: this.get('id')
  108. };
  109. App.router.get('updateController.graphs').push(graph);
  110. },
  111. loadData: function() {
  112. var validUrl = this.get('url');
  113. if (validUrl) {
  114. var hash = {};
  115. hash.url = validUrl;
  116. hash.type = 'GET';
  117. hash.dataType = 'json';
  118. hash.contentType = 'application/json; charset=utf-8';
  119. hash.context = this;
  120. hash.success = this._refreshGraph;
  121. hash.error = function (xhr, textStatus, errorThrown) {
  122. this._showMessage('warn', 'Error', 'There was a problem getting data for the chart (' + textStatus + ': ' + errorThrown + ')');
  123. }
  124. jQuery.ajax(hash);
  125. }
  126. },
  127. /**
  128. * Shows a yellow warning message in place of the chart.
  129. *
  130. * @param type Can be any of 'warn', 'error', 'info', 'success'
  131. * @param title Bolded title for the message
  132. * @param message String representing the message
  133. * @type: Function
  134. */
  135. _showMessage: function(type, title, message){
  136. var chartOverlayId = '#' + this.id + '-chart';
  137. if (this.get('isPopup')) {
  138. chartOverlayId += this.get('popupSuffix');
  139. }
  140. var typeClass;
  141. switch (type) {
  142. case 'error':
  143. typeClass = 'alert-error';
  144. break;
  145. case 'success':
  146. typeClass = 'alert-success';
  147. break;
  148. case 'info':
  149. typeClass = 'alert-info';
  150. break;
  151. default:
  152. typeClass = '';
  153. break;
  154. }
  155. $(chartOverlayId).html('');
  156. $(chartOverlayId).append('<div class=\"alert '+typeClass+'\"><strong>'+title+'</strong> '+message+'</div>');
  157. },
  158. /**
  159. * Transforms the JSON data retrieved from the server into the series
  160. * format that Rickshaw.Graph understands.
  161. *
  162. * The series object is generally in the following format: [ { name :
  163. * "Series 1", data : [ { x : 0, y : 0 }, { x : 1, y : 1 } ] } ]
  164. *
  165. * Extending classes should override this method.
  166. *
  167. * @param jsonData
  168. * Data retrieved from the server
  169. * @type: Function
  170. *
  171. */
  172. transformToSeries: function (jsonData) {
  173. return [ {
  174. name: "Series 1",
  175. data: [ {
  176. x: 0,
  177. y: 0
  178. }, {
  179. x: 1,
  180. y: 1
  181. } ]
  182. } ]
  183. },
  184. /**
  185. * Provides the formatter to use in displaying Y axis.
  186. *
  187. * The default is Rickshaw.Fixtures.Number.formatKMBT which shows 10K,
  188. * 300M etc.
  189. *
  190. * @type Function
  191. */
  192. yAxisFormatter: function(y) {
  193. var value = Rickshaw.Fixtures.Number.formatKMBT(y);
  194. if (value == '') return '0';
  195. value = String(value);
  196. var c = value[value.length - 1];
  197. if (!isNaN(parseInt(c))) {
  198. // c is digit
  199. value = parseFloat(value).toFixed(3);
  200. }
  201. else {
  202. // c in not digit
  203. value = parseFloat(value.substr(0, value.length - 1)).toFixed(3) + c;
  204. }
  205. return value;
  206. },
  207. /**
  208. * Provides the color (in any HTML color format) to use for a particular
  209. * series.
  210. *
  211. * @param series
  212. * Series for which color is being requested
  213. * @return color String. Returning null allows this chart to pick a color
  214. * from palette.
  215. * @default null
  216. * @type Function
  217. */
  218. colorForSeries: function (series) {
  219. return null;
  220. },
  221. /**
  222. * @private
  223. *
  224. * Refreshes the graph with the latest JSON data.
  225. *
  226. * @type Function
  227. */
  228. _refreshGraph: function (jsonData) {
  229. var seriesData = this.transformToSeries(jsonData);
  230. if (seriesData instanceof Array && seriesData.length>0) {
  231. this.draw(seriesData);
  232. }
  233. else {
  234. this._showMessage('info', 'No Data', 'There was no data available.');
  235. }
  236. },
  237. /**
  238. * Returns a custom time unit for the graph's X axis. This is needed
  239. * as Rickshaw's default time X axis uses UTC time, which can be confusing
  240. * for users expecting locale specific time. This value defaults to
  241. * App.ChartLinearTimeView.FifteenMinuteTimeUnit.
  242. *
  243. * If <code>null</code> is returned, Rickshaw's default time unit is used.
  244. *
  245. * @type Function
  246. * @return Rickshaw.Fixtures.Time
  247. * @default App.ChartLinearTimeView.FifteenMinuteTimeUnit
  248. */
  249. localeTimeUnit: function(){
  250. return App.ChartLinearTimeView.FifteenMinuteTimeUnit;
  251. },
  252. /**
  253. * @private
  254. *
  255. * When a graph is given a particular width and height,the lines are drawn
  256. * in a slightly bigger area thereby chopping off some of the UI. Hence
  257. * after the rendering, we adjust the SVGs size in the DOM to compensate.
  258. *
  259. * Opened https://github.com/shutterstock/rickshaw/issues/141
  260. *
  261. * @type Function
  262. */
  263. _adjustSVGHeight: function () {
  264. if (this._graph && this._graph.element
  265. && this._graph.element.firstChild) {
  266. var svgElement = this._graph.element.firstChild;
  267. svgElement.setAttribute('height', $(this._graph.element).height()
  268. + "px");
  269. svgElement.setAttribute('width', $(this._graph.element).width()
  270. + "px");
  271. }
  272. },
  273. draw: function(seriesData) {
  274. var isPopup = this.get('isPopup');
  275. var p = '';
  276. if (isPopup) {
  277. p = this.get('popupSuffix');
  278. }
  279. var palette = new Rickshaw.Color.Palette({
  280. scheme: this._paletteScheme
  281. });
  282. seriesData.forEach(function (series) {
  283. series.color = /*this.colorForSeries(series) ||*/ palette.color();
  284. series.stroke = 'rgba(0,0,0,0.3)';
  285. if (isPopup) {
  286. // calculate statistic data for popup legend
  287. var avg = 0;
  288. var min = Number.MAX_VALUE;
  289. var max = Number.MIN_VALUE;
  290. for (var i = 0; i < series.data.length; i++) {
  291. avg += series.data[i]['y'];
  292. if (series.data[i]['y'] < min) {
  293. min = series.data[i]['y'];
  294. }
  295. else {
  296. if (series.data[i]['y'] > max) {
  297. max = series.data[i]['y'];
  298. }
  299. }
  300. }
  301. series.name = string_utils.pad(series.name, 30, '&nbsp;', 2) + string_utils.pad('min', 5, '&nbsp;', 3) + string_utils.pad(this.get('yAxisFormatter')(min), 12, '&nbsp;', 3) + string_utils.pad('avg', 5, '&nbsp;', 3) + string_utils.pad(this.get('yAxisFormatter')(avg/series.data.length), 12, '&nbsp;', 3) + string_utils.pad('max', 12, '&nbsp;', 3) + string_utils.pad(this.get('yAxisFormatter')(max), 5, '&nbsp;', 3);
  302. }
  303. }.bind(this));
  304. var chartId = "#" + this.id + "-chart" + p;
  305. var chartOverlayId = "#" + this.id + "-container" + p;
  306. var xaxisElementId = "#" + this.id + "-xaxis" + p;
  307. var yaxisElementId = "#" + this.id + "-yaxis" + p;
  308. var legendElementId = "#" + this.id + "-legend" + p;
  309. var timelineElementId = "#" + this.id + "-timeline" + p;
  310. var chartElement = document.querySelector(chartId);
  311. var overlayElement = document.querySelector(chartOverlayId);
  312. var xaxisElement = document.querySelector(xaxisElementId);
  313. var yaxisElement = document.querySelector(yaxisElementId);
  314. var legendElement = document.querySelector(legendElementId);
  315. var timelineElement = document.querySelector(timelineElementId);
  316. var _graph = new Rickshaw.Graph({
  317. height: 150,
  318. element: chartElement,
  319. series: seriesData,
  320. interpolation: 'step-after',
  321. stroke: true,
  322. renderer: 'area',
  323. strokeWidth: 1
  324. });
  325. _graph.renderer.unstack = false;
  326. xAxis = new Rickshaw.Graph.Axis.Time({
  327. graph: _graph,
  328. timeUnit: this.localeTimeUnit()
  329. });
  330. yAxis = new Rickshaw.Graph.Axis.Y({
  331. tickFormat: this.yAxisFormatter,
  332. element: yaxisElement,
  333. graph: _graph
  334. });
  335. var legend = new Rickshaw.Graph.Legend({
  336. graph: _graph,
  337. element: legendElement
  338. });
  339. if (!isPopup) {
  340. overlayElement.addEventListener('mousemove', function () {
  341. $(xaxisElement).removeClass('hide');
  342. $(legendElement).removeClass('hide');
  343. $(chartElement).children("div").removeClass('hide');
  344. });
  345. overlayElement.addEventListener('mouseout', function () {
  346. $(legendElement).addClass('hide');
  347. });
  348. _graph.onUpdate(function () {
  349. $(legendElement).addClass('hide');
  350. });
  351. }
  352. var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
  353. graph: _graph,
  354. legend: legend
  355. });
  356. var order = new Rickshaw.Graph.Behavior.Series.Order({
  357. graph: _graph,
  358. legend: legend
  359. });
  360. var annotator = new Rickshaw.Graph.Annotate({
  361. graph: _graph,
  362. element: timelineElement
  363. });
  364. _graph.render();
  365. if (isPopup) {
  366. var self = this;
  367. var hoverDetail = new Rickshaw.Graph.HoverDetail({
  368. graph: _graph,
  369. yFormatter:function (y) {
  370. return self.yAxisFormatter(y);
  371. },
  372. xFormatter:function (x) {
  373. return (new Date(x)).toLocaleTimeString();
  374. },
  375. formatter:function (series, x, y, formattedX, formattedY, d) {
  376. return formattedY + '<br />' + formattedX;
  377. }
  378. });
  379. }
  380. if (isPopup) {
  381. this.set('_popupGraph', _graph);
  382. }
  383. else {
  384. this.set('_graph', _graph);
  385. }
  386. this.set('isPopup', false);
  387. },
  388. showGraphInPopup: function() {
  389. this.set('isPopup', true);
  390. var self = this;
  391. App.ModalPopup.show({
  392. template: Ember.Handlebars.compile([
  393. '<div class="modal-backdrop"></div><div class="modal modal-graph-line" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal-label" aria-hidden="true">',
  394. '<div class="modal-header">',
  395. '<a class="close" {{action onClose target="view"}}>x</a>',
  396. '<h3 id="modal-label">',
  397. '{{#if headerClass}}{{view headerClass}}',
  398. '{{else}}{{header}}{{/if}}',
  399. '</h3>',
  400. '</div>',
  401. '<div class="modal-body">',
  402. '{{#if bodyClass}}{{view bodyClass}}',
  403. '{{else}}'+
  404. '<div id="'+this.get('id')+'-container'+this.get('popupSuffix')+'" class="chart-container">'+
  405. '<div id="'+this.get('id')+'-yaxis'+this.get('popupSuffix')+'" class="'+this.get('id')+'-yaxis chart-y-axis"></div>'+
  406. '<div id="'+this.get('id')+'-xaxis'+this.get('popupSuffix')+'" class="'+this.get('id')+'-xaxis chart-x-axis"></div>'+
  407. '<div id="'+this.get('id')+'-legend'+this.get('popupSuffix')+'" class="'+this.get('id')+'-legend chart-legend"></div>'+
  408. '<div id="'+this.get('id')+'-chart'+this.get('popupSuffix')+'" class="'+this.get('id')+'-chart chart"></div>'+
  409. '<div id="'+this.get('id')+'-title'+this.get('popupSuffix')+'" class="'+this.get('id')+'-title chart-title">{{view.title}}</div>'+
  410. '<div id="'+this.get('id')+'-timeline'+this.get('popupSuffix')+'" class="'+this.get('id')+'-timeline timeline"></div>'+
  411. '</div>'+
  412. '{{/if}}',
  413. '</div>',
  414. '<div class="modal-footer">',
  415. '{{#if view.primary}}<a class="btn btn-success" {{action onPrimary target="view"}}>{{view.primary}}</a>{{/if}}',
  416. '</div>',
  417. '</div>'
  418. ].join('\n')),
  419. header: this.get('title'),
  420. primary: 'OK',
  421. onPrimary: function() {
  422. this.hide();
  423. self.set('isPopup', false);
  424. }
  425. });
  426. Ember.run.next(function() {
  427. self.loadData();
  428. });
  429. }
  430. });
  431. /**
  432. * A formatter which will turn a number into computer storage sizes of the
  433. * format '23 GB' etc.
  434. *
  435. * @type Function
  436. */
  437. App.ChartLinearTimeView.BytesFormatter = function (y) {
  438. if (y == 0) return '0 B';
  439. var value = Rickshaw.Fixtures.Number.formatBase1024KMGTP(y);
  440. if (!y || y.length < 1) {
  441. value = '0 B';
  442. }
  443. else {
  444. if ("number" == typeof value) {
  445. value = String(value);
  446. }
  447. if ("string" == typeof value) {
  448. value = value.replace(/\.\d+/, ''); // Remove decimal part
  449. // Either it ends with digit or ends with character
  450. value = value.replace(/(\d$)/, '$1 '); // Ends with digit like '120'
  451. value = value.replace(/([a-zA-Z]$)/, ' $1'); // Ends with character like
  452. // '120M'
  453. value = value + 'B'; // Append B to make B, MB, GB etc.
  454. }
  455. }
  456. return value;
  457. };
  458. /**
  459. * A formatter which will turn a number into percentage display like '42%'
  460. *
  461. * @type Function
  462. */
  463. App.ChartLinearTimeView.PercentageFormatter = function (percentage) {
  464. var value = percentage;
  465. if (!value || value.length < 1) {
  466. value = '0 %';
  467. } else {
  468. value = value.toFixed(3) + '%';
  469. }
  470. return value;
  471. };
  472. /**
  473. * A formatter which will turn elapsed time into display time like '50 ms',
  474. * '5s', '10 m', '3 hr' etc. Time is expected to be provided in milliseconds.
  475. *
  476. * @type Function
  477. */
  478. App.ChartLinearTimeView.TimeElapsedFormatter = function (millis) {
  479. var value = millis;
  480. if (!value || value.length < 1) {
  481. value = '0 ms';
  482. } else if ("number" == typeof millis) {
  483. var seconds = millis > 1000 ? Math.round(millis / 1000) : 0;
  484. var minutes = seconds > 60 ? Math.round(seconds / 60) : 0;
  485. var hours = minutes > 60 ? Math.round(minutes / 60) : 0;
  486. var days = hours > 24 ? Math.round(hours / 24) : 0;
  487. if (days > 0) {
  488. value = days + ' d';
  489. } else if (hours > 0) {
  490. value = hours + ' hr';
  491. } else if (minutes > 0) {
  492. value = minutes + ' m';
  493. } else if (seconds > 0) {
  494. value = seconds + ' s';
  495. } else if (millis > 0) {
  496. value = millis.toFixed(3) + ' ms';
  497. } else {
  498. value = millis.toFixed(3) + ' ms';
  499. }
  500. }
  501. return value;
  502. };
  503. /**
  504. * A time unit which can be used for showing 15 minute intervals on X axis.
  505. *
  506. * @type Rickshaw.Fixtures.Time
  507. */
  508. App.ChartLinearTimeView.FifteenMinuteTimeUnit = {
  509. name: '15 minute',
  510. seconds: 60 * 15,
  511. formatter: function (d) {
  512. return d.toLocaleString().match(/(\d+:\d+):/)[1];
  513. }
  514. };