graph.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. import 'vendor/flot/jquery.flot';
  2. import 'vendor/flot/jquery.flot.selection';
  3. import 'vendor/flot/jquery.flot.time';
  4. import 'vendor/flot/jquery.flot.stack';
  5. import 'vendor/flot/jquery.flot.stackpercent';
  6. import 'vendor/flot/jquery.flot.fillbelow';
  7. import 'vendor/flot/jquery.flot.crosshair';
  8. import 'vendor/flot/jquery.flot.dashes';
  9. import './jquery.flot.events';
  10. import $ from 'jquery';
  11. import _ from 'lodash';
  12. import moment from 'moment';
  13. import kbn from 'app/core/utils/kbn';
  14. import { tickStep } from 'app/core/utils/ticks';
  15. import { appEvents, coreModule, updateLegendValues } from 'app/core/core';
  16. import GraphTooltip from './graph_tooltip';
  17. import { ThresholdManager } from './threshold_manager';
  18. import { EventManager } from 'app/features/annotations/all';
  19. import { convertToHistogramData } from './histogram';
  20. import { alignYLevel } from './align_yaxes';
  21. import config from 'app/core/config';
  22. import React from 'react';
  23. import ReactDOM from 'react-dom';
  24. import { Legend, GraphLegendProps } from './Legend/Legend';
  25. import { GraphCtrl } from './module';
  26. class GraphElement {
  27. ctrl: GraphCtrl;
  28. tooltip: any;
  29. dashboard: any;
  30. annotations: object[];
  31. panel: any;
  32. plot: any;
  33. sortedSeries: any[];
  34. data: any[];
  35. panelWidth: number;
  36. eventManager: EventManager;
  37. thresholdManager: ThresholdManager;
  38. legendElem: HTMLElement;
  39. constructor(private scope, private elem, private timeSrv) {
  40. this.ctrl = scope.ctrl;
  41. this.dashboard = this.ctrl.dashboard;
  42. this.panel = this.ctrl.panel;
  43. this.annotations = [];
  44. this.panelWidth = 0;
  45. this.eventManager = new EventManager(this.ctrl);
  46. this.thresholdManager = new ThresholdManager(this.ctrl);
  47. this.tooltip = new GraphTooltip(this.elem, this.ctrl.dashboard, this.scope, () => {
  48. return this.sortedSeries;
  49. });
  50. // panel events
  51. this.ctrl.events.on('panel-teardown', this.onPanelTeardown.bind(this));
  52. /**
  53. * Split graph rendering into two parts.
  54. * First, calculate series stats in buildFlotPairs() function. Then legend rendering started
  55. * (see ctrl.events.on('render') in legend.ts).
  56. * When legend is rendered it emits 'legend-rendering-complete' and graph rendered.
  57. */
  58. this.ctrl.events.on('render', this.onRender.bind(this));
  59. this.ctrl.events.on('legend-rendering-complete', this.onLegendRenderingComplete.bind(this));
  60. // global events
  61. appEvents.on('graph-hover', this.onGraphHover.bind(this), scope);
  62. appEvents.on('graph-hover-clear', this.onGraphHoverClear.bind(this), scope);
  63. this.elem.bind('plotselected', this.onPlotSelected.bind(this));
  64. this.elem.bind('plotclick', this.onPlotClick.bind(this));
  65. // get graph legend element
  66. if (this.elem && this.elem.parent) {
  67. this.legendElem = this.elem.parent().find('.graph-legend')[0];
  68. }
  69. }
  70. onRender(renderData) {
  71. this.data = renderData || this.data;
  72. if (!this.data) {
  73. return;
  74. }
  75. this.annotations = this.ctrl.annotations || [];
  76. this.buildFlotPairs(this.data);
  77. const graphHeight = this.elem.height();
  78. updateLegendValues(this.data, this.panel, graphHeight);
  79. const { values, min, max, avg, current, total } = this.panel.legend;
  80. const { alignAsTable, rightSide, sideWidth, sort, sortDesc, hideEmpty, hideZero } = this.panel.legend;
  81. const legendOptions = { alignAsTable, rightSide, sideWidth, sort, sortDesc, hideEmpty, hideZero };
  82. const valueOptions = { values, min, max, avg, current, total };
  83. const legendProps: GraphLegendProps = {
  84. seriesList: this.data,
  85. hiddenSeries: this.ctrl.hiddenSeries,
  86. ...legendOptions,
  87. ...valueOptions,
  88. onToggleSeries: this.ctrl.onToggleSeries,
  89. onToggleSort: this.ctrl.onToggleSort,
  90. onColorChange: this.ctrl.onColorChange,
  91. onToggleAxis: this.ctrl.onToggleAxis,
  92. };
  93. const legendReactElem = React.createElement(Legend, legendProps);
  94. ReactDOM.render(legendReactElem, this.legendElem, () => this.onLegendRenderingComplete());
  95. }
  96. onLegendRenderingComplete() {
  97. this.render_panel();
  98. }
  99. onGraphHover(evt) {
  100. // ignore other graph hover events if shared tooltip is disabled
  101. if (!this.dashboard.sharedTooltipModeEnabled()) {
  102. return;
  103. }
  104. // ignore if we are the emitter
  105. if (!this.plot || evt.panel.id === this.panel.id || this.ctrl.otherPanelInFullscreenMode()) {
  106. return;
  107. }
  108. this.tooltip.show(evt.pos);
  109. }
  110. onPanelTeardown() {
  111. this.thresholdManager = null;
  112. if (this.plot) {
  113. this.plot.destroy();
  114. this.plot = null;
  115. }
  116. this.tooltip.destroy();
  117. this.elem.off();
  118. this.elem.remove();
  119. console.log('react unmount');
  120. ReactDOM.unmountComponentAtNode(this.legendElem);
  121. }
  122. onGraphHoverClear(event, info) {
  123. if (this.plot) {
  124. this.tooltip.clear(this.plot);
  125. }
  126. }
  127. onPlotSelected(event, ranges) {
  128. if (this.panel.xaxis.mode !== 'time') {
  129. // Skip if panel in histogram or series mode
  130. this.plot.clearSelection();
  131. return;
  132. }
  133. if ((ranges.ctrlKey || ranges.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  134. // Add annotation
  135. setTimeout(() => {
  136. this.eventManager.updateTime(ranges.xaxis);
  137. }, 100);
  138. } else {
  139. this.scope.$apply(() => {
  140. this.timeSrv.setTime({
  141. from: moment.utc(ranges.xaxis.from),
  142. to: moment.utc(ranges.xaxis.to),
  143. });
  144. });
  145. }
  146. }
  147. onPlotClick(event, pos, item) {
  148. if (this.panel.xaxis.mode !== 'time') {
  149. // Skip if panel in histogram or series mode
  150. return;
  151. }
  152. if ((pos.ctrlKey || pos.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  153. // Skip if range selected (added in "plotselected" event handler)
  154. const isRangeSelection = pos.x !== pos.x1;
  155. if (!isRangeSelection) {
  156. setTimeout(() => {
  157. this.eventManager.updateTime({ from: pos.x, to: null });
  158. }, 100);
  159. }
  160. }
  161. }
  162. shouldAbortRender() {
  163. if (!this.data) {
  164. return true;
  165. }
  166. if (this.panelWidth === 0) {
  167. return true;
  168. }
  169. return false;
  170. }
  171. drawHook(plot) {
  172. // add left axis labels
  173. if (this.panel.yaxes[0].label && this.panel.yaxes[0].show) {
  174. $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
  175. .text(this.panel.yaxes[0].label)
  176. .appendTo(this.elem);
  177. }
  178. // add right axis labels
  179. if (this.panel.yaxes[1].label && this.panel.yaxes[1].show) {
  180. $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
  181. .text(this.panel.yaxes[1].label)
  182. .appendTo(this.elem);
  183. }
  184. if (this.ctrl.dataWarning) {
  185. $(`<div class="datapoints-warning flot-temp-elem">${this.ctrl.dataWarning.title}</div>`).appendTo(this.elem);
  186. }
  187. this.thresholdManager.draw(plot);
  188. }
  189. processOffsetHook(plot, gridMargin) {
  190. const left = this.panel.yaxes[0];
  191. const right = this.panel.yaxes[1];
  192. if (left.show && left.label) {
  193. gridMargin.left = 20;
  194. }
  195. if (right.show && right.label) {
  196. gridMargin.right = 20;
  197. }
  198. // apply y-axis min/max options
  199. const yaxis = plot.getYAxes();
  200. for (let i = 0; i < yaxis.length; i++) {
  201. const axis = yaxis[i];
  202. const panelOptions = this.panel.yaxes[i];
  203. axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
  204. axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
  205. }
  206. }
  207. processRangeHook(plot) {
  208. const yAxes = plot.getYAxes();
  209. const align = this.panel.yaxis.align || false;
  210. if (yAxes.length > 1 && align === true) {
  211. const level = this.panel.yaxis.alignLevel || 0;
  212. alignYLevel(yAxes, parseFloat(level));
  213. }
  214. }
  215. // Series could have different timeSteps,
  216. // let's find the smallest one so that bars are correctly rendered.
  217. // In addition, only take series which are rendered as bars for this.
  218. getMinTimeStepOfSeries(data) {
  219. let min = Number.MAX_VALUE;
  220. for (let i = 0; i < data.length; i++) {
  221. if (!data[i].stats.timeStep) {
  222. continue;
  223. }
  224. if (this.panel.bars) {
  225. if (data[i].bars && data[i].bars.show === false) {
  226. continue;
  227. }
  228. } else {
  229. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  230. continue;
  231. }
  232. }
  233. if (data[i].stats.timeStep < min) {
  234. min = data[i].stats.timeStep;
  235. }
  236. }
  237. return min;
  238. }
  239. // Function for rendering panel
  240. render_panel() {
  241. this.panelWidth = this.elem.width();
  242. if (this.shouldAbortRender()) {
  243. return;
  244. }
  245. // give space to alert editing
  246. this.thresholdManager.prepare(this.elem, this.data);
  247. // un-check dashes if lines are unchecked
  248. this.panel.dashes = this.panel.lines ? this.panel.dashes : false;
  249. // Populate element
  250. const options: any = this.buildFlotOptions(this.panel);
  251. this.prepareXAxis(options, this.panel);
  252. this.configureYAxisOptions(this.data, options);
  253. this.thresholdManager.addFlotOptions(options, this.panel);
  254. this.eventManager.addFlotEvents(this.annotations, options);
  255. this.sortedSeries = this.sortSeries(this.data, this.panel);
  256. this.callPlot(options, true);
  257. }
  258. buildFlotPairs(data) {
  259. for (let i = 0; i < data.length; i++) {
  260. const series = data[i];
  261. series.data = series.getFlotPairs(series.nullPointMode || this.panel.nullPointMode);
  262. // if hidden remove points and disable stack
  263. if (this.ctrl.hiddenSeries[series.alias]) {
  264. series.data = [];
  265. series.stack = false;
  266. }
  267. }
  268. }
  269. prepareXAxis(options, panel) {
  270. switch (panel.xaxis.mode) {
  271. case 'series': {
  272. options.series.bars.barWidth = 0.7;
  273. options.series.bars.align = 'center';
  274. for (let i = 0; i < this.data.length; i++) {
  275. const series = this.data[i];
  276. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  277. }
  278. this.addXSeriesAxis(options);
  279. break;
  280. }
  281. case 'histogram': {
  282. let bucketSize: number;
  283. if (this.data.length) {
  284. const histMin = _.min(_.map(this.data, s => s.stats.min));
  285. const histMax = _.max(_.map(this.data, s => s.stats.max));
  286. const ticks = panel.xaxis.buckets || this.panelWidth / 50;
  287. bucketSize = tickStep(histMin, histMax, ticks);
  288. options.series.bars.barWidth = bucketSize * 0.8;
  289. this.data = convertToHistogramData(this.data, bucketSize, this.ctrl.hiddenSeries, histMin, histMax);
  290. } else {
  291. bucketSize = 0;
  292. }
  293. this.addXHistogramAxis(options, bucketSize);
  294. break;
  295. }
  296. case 'table': {
  297. options.series.bars.barWidth = 0.7;
  298. options.series.bars.align = 'center';
  299. this.addXTableAxis(options);
  300. break;
  301. }
  302. default: {
  303. options.series.bars.barWidth = this.getMinTimeStepOfSeries(this.data) / 1.5;
  304. this.addTimeAxis(options);
  305. break;
  306. }
  307. }
  308. }
  309. callPlot(options, incrementRenderCounter) {
  310. try {
  311. this.plot = $.plot(this.elem, this.sortedSeries, options);
  312. if (this.ctrl.renderError) {
  313. delete this.ctrl.error;
  314. delete this.ctrl.inspector;
  315. }
  316. } catch (e) {
  317. console.log('flotcharts error', e);
  318. this.ctrl.error = e.message || 'Render Error';
  319. this.ctrl.renderError = true;
  320. this.ctrl.inspector = { error: e };
  321. }
  322. if (incrementRenderCounter) {
  323. this.ctrl.renderingCompleted();
  324. }
  325. }
  326. buildFlotOptions(panel) {
  327. let gridColor = '#c8c8c8';
  328. if (config.bootData.user.lightTheme === true) {
  329. gridColor = '#a1a1a1';
  330. }
  331. const stack = panel.stack ? true : null;
  332. const options = {
  333. hooks: {
  334. draw: [this.drawHook.bind(this)],
  335. processOffset: [this.processOffsetHook.bind(this)],
  336. processRange: [this.processRangeHook.bind(this)],
  337. },
  338. legend: { show: false },
  339. series: {
  340. stackpercent: panel.stack ? panel.percentage : false,
  341. stack: panel.percentage ? null : stack,
  342. lines: {
  343. show: panel.lines,
  344. zero: false,
  345. fill: this.translateFillOption(panel.fill),
  346. lineWidth: panel.dashes ? 0 : panel.linewidth,
  347. steps: panel.steppedLine,
  348. },
  349. dashes: {
  350. show: panel.dashes,
  351. lineWidth: panel.linewidth,
  352. dashLength: [panel.dashLength, panel.spaceLength],
  353. },
  354. bars: {
  355. show: panel.bars,
  356. fill: 1,
  357. barWidth: 1,
  358. zero: false,
  359. lineWidth: 0,
  360. },
  361. points: {
  362. show: panel.points,
  363. fill: 1,
  364. fillColor: false,
  365. radius: panel.points ? panel.pointradius : 2,
  366. },
  367. shadowSize: 0,
  368. },
  369. yaxes: [],
  370. xaxis: {},
  371. grid: {
  372. minBorderMargin: 0,
  373. markings: [],
  374. backgroundColor: null,
  375. borderWidth: 0,
  376. hoverable: true,
  377. clickable: true,
  378. color: gridColor,
  379. margin: { left: 0, right: 0 },
  380. labelMarginX: 0,
  381. },
  382. selection: {
  383. mode: 'x',
  384. color: '#666',
  385. },
  386. crosshair: {
  387. mode: 'x',
  388. },
  389. };
  390. return options;
  391. }
  392. sortSeries(series, panel) {
  393. const sortBy = panel.legend.sort;
  394. const sortOrder = panel.legend.sortDesc;
  395. const haveSortBy = sortBy !== null && sortBy !== undefined;
  396. const haveSortOrder = sortOrder !== null && sortOrder !== undefined;
  397. const shouldSortBy = panel.stack && haveSortBy && haveSortOrder;
  398. const sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  399. if (shouldSortBy) {
  400. return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
  401. } else {
  402. return _.sortBy(series, s => s.zindex);
  403. }
  404. }
  405. translateFillOption(fill) {
  406. if (this.panel.percentage && this.panel.stack) {
  407. return fill === 0 ? 0.001 : fill / 10;
  408. } else {
  409. return fill / 10;
  410. }
  411. }
  412. addTimeAxis(options) {
  413. const ticks = this.panelWidth / 100;
  414. const min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
  415. const max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
  416. options.xaxis = {
  417. timezone: this.dashboard.getTimezone(),
  418. show: this.panel.xaxis.show,
  419. mode: 'time',
  420. min: min,
  421. max: max,
  422. label: 'Datetime',
  423. ticks: ticks,
  424. timeformat: this.time_format(ticks, min, max),
  425. };
  426. }
  427. addXSeriesAxis(options) {
  428. const ticks = _.map(this.data, (series, index) => {
  429. return [index + 1, series.alias];
  430. });
  431. options.xaxis = {
  432. timezone: this.dashboard.getTimezone(),
  433. show: this.panel.xaxis.show,
  434. mode: null,
  435. min: 0,
  436. max: ticks.length + 1,
  437. label: 'Datetime',
  438. ticks: ticks,
  439. };
  440. }
  441. addXHistogramAxis(options, bucketSize) {
  442. let ticks, min, max;
  443. const defaultTicks = this.panelWidth / 50;
  444. if (this.data.length && bucketSize) {
  445. const tickValues = [];
  446. for (const d of this.data) {
  447. for (const point of d.data) {
  448. tickValues[point[0]] = true;
  449. }
  450. }
  451. ticks = Object.keys(tickValues).map(v => Number(v));
  452. min = _.min(ticks);
  453. max = _.max(ticks);
  454. // Adjust tick step
  455. let tickStep = bucketSize;
  456. let ticksNum = Math.floor((max - min) / tickStep);
  457. while (ticksNum > defaultTicks) {
  458. tickStep = tickStep * 2;
  459. ticksNum = Math.ceil((max - min) / tickStep);
  460. }
  461. // Expand ticks for pretty view
  462. min = Math.floor(min / tickStep) * tickStep;
  463. // 1.01 is 101% - ensure we have enough space for last bar
  464. max = Math.ceil(max * 1.01 / tickStep) * tickStep;
  465. ticks = [];
  466. for (let i = min; i <= max; i += tickStep) {
  467. ticks.push(i);
  468. }
  469. } else {
  470. // Set defaults if no data
  471. ticks = defaultTicks / 2;
  472. min = 0;
  473. max = 1;
  474. }
  475. options.xaxis = {
  476. timezone: this.dashboard.getTimezone(),
  477. show: this.panel.xaxis.show,
  478. mode: null,
  479. min: min,
  480. max: max,
  481. label: 'Histogram',
  482. ticks: ticks,
  483. };
  484. // Use 'short' format for histogram values
  485. this.configureAxisMode(options.xaxis, 'short');
  486. }
  487. addXTableAxis(options) {
  488. let ticks = _.map(this.data, (series, seriesIndex) => {
  489. return _.map(series.datapoints, (point, pointIndex) => {
  490. const tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  491. return [tickIndex + 1, point[1]];
  492. });
  493. });
  494. ticks = _.flatten(ticks, true);
  495. options.xaxis = {
  496. timezone: this.dashboard.getTimezone(),
  497. show: this.panel.xaxis.show,
  498. mode: null,
  499. min: 0,
  500. max: ticks.length + 1,
  501. label: 'Datetime',
  502. ticks: ticks,
  503. };
  504. }
  505. configureYAxisOptions(data, options) {
  506. const defaults = {
  507. position: 'left',
  508. show: this.panel.yaxes[0].show,
  509. index: 1,
  510. logBase: this.panel.yaxes[0].logBase || 1,
  511. min: this.parseNumber(this.panel.yaxes[0].min),
  512. max: this.parseNumber(this.panel.yaxes[0].max),
  513. tickDecimals: this.panel.yaxes[0].decimals,
  514. };
  515. options.yaxes.push(defaults);
  516. if (_.find(data, { yaxis: 2 })) {
  517. const secondY = _.clone(defaults);
  518. secondY.index = 2;
  519. secondY.show = this.panel.yaxes[1].show;
  520. secondY.logBase = this.panel.yaxes[1].logBase || 1;
  521. secondY.position = 'right';
  522. secondY.min = this.parseNumber(this.panel.yaxes[1].min);
  523. secondY.max = this.parseNumber(this.panel.yaxes[1].max);
  524. secondY.tickDecimals = this.panel.yaxes[1].decimals;
  525. options.yaxes.push(secondY);
  526. this.applyLogScale(options.yaxes[1], data);
  527. this.configureAxisMode(
  528. options.yaxes[1],
  529. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[1].format
  530. );
  531. }
  532. this.applyLogScale(options.yaxes[0], data);
  533. this.configureAxisMode(
  534. options.yaxes[0],
  535. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[0].format
  536. );
  537. }
  538. parseNumber(value: any) {
  539. if (value === null || typeof value === 'undefined') {
  540. return null;
  541. }
  542. return _.toNumber(value);
  543. }
  544. applyLogScale(axis, data) {
  545. if (axis.logBase === 1) {
  546. return;
  547. }
  548. const minSetToZero = axis.min === 0;
  549. if (axis.min < Number.MIN_VALUE) {
  550. axis.min = null;
  551. }
  552. if (axis.max < Number.MIN_VALUE) {
  553. axis.max = null;
  554. }
  555. let series, i;
  556. let max = axis.max,
  557. min = axis.min;
  558. for (i = 0; i < data.length; i++) {
  559. series = data[i];
  560. if (series.yaxis === axis.index) {
  561. if (!max || max < series.stats.max) {
  562. max = series.stats.max;
  563. }
  564. if (!min || min > series.stats.logmin) {
  565. min = series.stats.logmin;
  566. }
  567. }
  568. }
  569. axis.transform = v => {
  570. return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
  571. };
  572. axis.inverseTransform = v => {
  573. return Math.pow(axis.logBase, v);
  574. };
  575. if (!max && !min) {
  576. max = axis.inverseTransform(+2);
  577. min = axis.inverseTransform(-2);
  578. } else if (!max) {
  579. max = min * axis.inverseTransform(+4);
  580. } else if (!min) {
  581. min = max * axis.inverseTransform(-4);
  582. }
  583. if (axis.min) {
  584. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  585. } else {
  586. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  587. }
  588. if (axis.max) {
  589. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  590. } else {
  591. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  592. }
  593. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  594. return;
  595. }
  596. if (Number.isFinite(min) && Number.isFinite(max)) {
  597. if (minSetToZero) {
  598. axis.min = 0.1;
  599. min = 1;
  600. }
  601. axis.ticks = this.generateTicksForLogScaleYAxis(min, max, axis.logBase);
  602. if (minSetToZero) {
  603. axis.ticks.unshift(0.1);
  604. }
  605. if (axis.ticks[axis.ticks.length - 1] > axis.max) {
  606. axis.max = axis.ticks[axis.ticks.length - 1];
  607. }
  608. } else {
  609. axis.ticks = [1, 2];
  610. delete axis.min;
  611. delete axis.max;
  612. }
  613. }
  614. generateTicksForLogScaleYAxis(min, max, logBase) {
  615. let ticks = [];
  616. let nextTick;
  617. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  618. ticks.push(nextTick);
  619. }
  620. const maxNumTicks = Math.ceil(this.ctrl.height / 25);
  621. const numTicks = ticks.length;
  622. if (numTicks > maxNumTicks) {
  623. const factor = Math.ceil(numTicks / maxNumTicks) * logBase;
  624. ticks = [];
  625. for (nextTick = min; nextTick <= max * factor; nextTick *= factor) {
  626. ticks.push(nextTick);
  627. }
  628. }
  629. return ticks;
  630. }
  631. configureAxisMode(axis, format) {
  632. axis.tickFormatter = (val, axis) => {
  633. if (!kbn.valueFormats[format]) {
  634. throw new Error(`Unit '${format}' is not supported`);
  635. }
  636. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  637. };
  638. }
  639. time_format(ticks, min, max) {
  640. if (min && max && ticks) {
  641. const range = max - min;
  642. const secPerTick = range / ticks / 1000;
  643. // Need have 10 milisecond margin on the day range
  644. // As sometimes last 24 hour dashboard evaluates to more than 86400000
  645. const oneDay = 86400010;
  646. const oneYear = 31536000000;
  647. if (secPerTick <= 45) {
  648. return '%H:%M:%S';
  649. }
  650. if (secPerTick <= 7200 || range <= oneDay) {
  651. return '%H:%M';
  652. }
  653. if (secPerTick <= 80000) {
  654. return '%m/%d %H:%M';
  655. }
  656. if (secPerTick <= 2419200 || range <= oneYear) {
  657. return '%m/%d';
  658. }
  659. return '%Y-%m';
  660. }
  661. return '%H:%M';
  662. }
  663. }
  664. /** @ngInject */
  665. function graphDirective(timeSrv, popoverSrv, contextSrv) {
  666. return {
  667. restrict: 'A',
  668. template: '',
  669. link: (scope, elem) => {
  670. return new GraphElement(scope, elem, timeSrv);
  671. },
  672. };
  673. }
  674. coreModule.directive('grafanaGraph', graphDirective);
  675. export { GraphElement, graphDirective };