graph.ts 22 KB

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