graph.ts 21 KB

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