graph.ts 22 KB

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