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