graph.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 { TimeRegionManager } from './time_region_manager';
  19. import { EventManager } from 'app/features/annotations/all';
  20. import { convertToHistogramData } from './histogram';
  21. import { alignYLevel } from './align_yaxes';
  22. import config from 'app/core/config';
  23. import React from 'react';
  24. import ReactDOM from 'react-dom';
  25. import { Legend, GraphLegendProps } from './Legend/Legend';
  26. import { GraphCtrl } from './module';
  27. class GraphElement {
  28. ctrl: GraphCtrl;
  29. tooltip: any;
  30. dashboard: any;
  31. annotations: object[];
  32. panel: any;
  33. plot: any;
  34. sortedSeries: any[];
  35. data: any[];
  36. panelWidth: number;
  37. eventManager: EventManager;
  38. thresholdManager: ThresholdManager;
  39. timeRegionManager: TimeRegionManager;
  40. legendElem: HTMLElement;
  41. constructor(private scope, private elem, private timeSrv) {
  42. this.ctrl = scope.ctrl;
  43. this.dashboard = this.ctrl.dashboard;
  44. this.panel = this.ctrl.panel;
  45. this.annotations = [];
  46. this.panelWidth = 0;
  47. this.eventManager = new EventManager(this.ctrl);
  48. this.thresholdManager = new ThresholdManager(this.ctrl);
  49. this.timeRegionManager = new TimeRegionManager(this.ctrl);
  50. this.tooltip = new GraphTooltip(this.elem, this.ctrl.dashboard, this.scope, () => {
  51. return this.sortedSeries;
  52. });
  53. // panel events
  54. this.ctrl.events.on('panel-teardown', this.onPanelTeardown.bind(this));
  55. this.ctrl.events.on('render', this.onRender.bind(this));
  56. // global events
  57. appEvents.on('graph-hover', this.onGraphHover.bind(this), scope);
  58. appEvents.on('graph-hover-clear', this.onGraphHoverClear.bind(this), scope);
  59. this.elem.bind('plotselected', this.onPlotSelected.bind(this));
  60. this.elem.bind('plotclick', this.onPlotClick.bind(this));
  61. // get graph legend element
  62. if (this.elem && this.elem.parent) {
  63. this.legendElem = this.elem.parent().find('.graph-legend')[0];
  64. }
  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. if (!this.panel.legend.show) {
  76. if (this.legendElem.hasChildNodes()) {
  77. ReactDOM.unmountComponentAtNode(this.legendElem);
  78. }
  79. this.renderPanel();
  80. return;
  81. }
  82. const { values, min, max, avg, current, total } = this.panel.legend;
  83. const { alignAsTable, rightSide, sideWidth, sort, sortDesc, hideEmpty, hideZero } = this.panel.legend;
  84. const legendOptions = { alignAsTable, rightSide, sideWidth, sort, sortDesc, hideEmpty, hideZero };
  85. const valueOptions = { values, min, max, avg, current, total };
  86. const legendProps: GraphLegendProps = {
  87. seriesList: this.data,
  88. hiddenSeries: this.ctrl.hiddenSeries,
  89. ...legendOptions,
  90. ...valueOptions,
  91. onToggleSeries: this.ctrl.onToggleSeries,
  92. onToggleSort: this.ctrl.onToggleSort,
  93. onColorChange: this.ctrl.onColorChange,
  94. onToggleAxis: this.ctrl.onToggleAxis,
  95. };
  96. const legendReactElem = React.createElement(Legend, legendProps);
  97. ReactDOM.render(legendReactElem, this.legendElem, () => this.renderPanel());
  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. this.timeRegionManager = null;
  113. if (this.plot) {
  114. this.plot.destroy();
  115. this.plot = null;
  116. }
  117. this.tooltip.destroy();
  118. this.elem.off();
  119. this.elem.remove();
  120. ReactDOM.unmountComponentAtNode(this.legendElem);
  121. }
  122. onGraphHoverClear(event, info) {
  123. if (this.plot) {
  124. this.tooltip.clear(this.plot);
  125. }
  126. }
  127. onPlotSelected(event, ranges) {
  128. if (this.panel.xaxis.mode !== 'time') {
  129. // Skip if panel in histogram or series mode
  130. this.plot.clearSelection();
  131. return;
  132. }
  133. if ((ranges.ctrlKey || ranges.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  134. // Add annotation
  135. setTimeout(() => {
  136. this.eventManager.updateTime(ranges.xaxis);
  137. }, 100);
  138. } else {
  139. this.scope.$apply(() => {
  140. this.timeSrv.setTime({
  141. from: moment.utc(ranges.xaxis.from),
  142. to: moment.utc(ranges.xaxis.to),
  143. });
  144. });
  145. }
  146. }
  147. onPlotClick(event, pos, item) {
  148. if (this.panel.xaxis.mode !== 'time') {
  149. // Skip if panel in histogram or series mode
  150. return;
  151. }
  152. if ((pos.ctrlKey || pos.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  153. // Skip if range selected (added in "plotselected" event handler)
  154. const isRangeSelection = pos.x !== pos.x1;
  155. if (!isRangeSelection) {
  156. setTimeout(() => {
  157. this.eventManager.updateTime({ from: pos.x, to: null });
  158. }, 100);
  159. }
  160. }
  161. }
  162. shouldAbortRender() {
  163. if (!this.data) {
  164. return true;
  165. }
  166. if (this.panelWidth === 0) {
  167. return true;
  168. }
  169. return false;
  170. }
  171. drawHook(plot) {
  172. // add left axis labels
  173. if (this.panel.yaxes[0].label && this.panel.yaxes[0].show) {
  174. $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
  175. .text(this.panel.yaxes[0].label)
  176. .appendTo(this.elem);
  177. }
  178. // add right axis labels
  179. if (this.panel.yaxes[1].label && this.panel.yaxes[1].show) {
  180. $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
  181. .text(this.panel.yaxes[1].label)
  182. .appendTo(this.elem);
  183. }
  184. if (this.ctrl.dataWarning) {
  185. $(`<div class="datapoints-warning flot-temp-elem">${this.ctrl.dataWarning.title}</div>`).appendTo(this.elem);
  186. }
  187. this.thresholdManager.draw(plot);
  188. this.timeRegionManager.draw(plot);
  189. }
  190. processOffsetHook(plot, gridMargin) {
  191. const left = this.panel.yaxes[0];
  192. const right = this.panel.yaxes[1];
  193. if (left.show && left.label) {
  194. gridMargin.left = 20;
  195. }
  196. if (right.show && right.label) {
  197. gridMargin.right = 20;
  198. }
  199. // apply y-axis min/max options
  200. const yaxis = plot.getYAxes();
  201. for (let i = 0; i < yaxis.length; i++) {
  202. const axis = yaxis[i];
  203. const panelOptions = this.panel.yaxes[i];
  204. axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
  205. axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
  206. }
  207. }
  208. processRangeHook(plot) {
  209. const yAxes = plot.getYAxes();
  210. const align = this.panel.yaxis.align || false;
  211. if (yAxes.length > 1 && align === true) {
  212. const level = this.panel.yaxis.alignLevel || 0;
  213. alignYLevel(yAxes, parseFloat(level));
  214. }
  215. }
  216. // Series could have different timeSteps,
  217. // let's find the smallest one so that bars are correctly rendered.
  218. // In addition, only take series which are rendered as bars for this.
  219. getMinTimeStepOfSeries(data) {
  220. let min = Number.MAX_VALUE;
  221. for (let i = 0; i < data.length; i++) {
  222. if (!data[i].stats.timeStep) {
  223. continue;
  224. }
  225. if (this.panel.bars) {
  226. if (data[i].bars && data[i].bars.show === false) {
  227. continue;
  228. }
  229. } else {
  230. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  231. continue;
  232. }
  233. }
  234. if (data[i].stats.timeStep < min) {
  235. min = data[i].stats.timeStep;
  236. }
  237. }
  238. return min;
  239. }
  240. // Function for rendering panel
  241. renderPanel() {
  242. this.panelWidth = this.elem.width();
  243. if (this.shouldAbortRender()) {
  244. return;
  245. }
  246. // give space to alert editing
  247. this.thresholdManager.prepare(this.elem, this.data);
  248. // un-check dashes if lines are unchecked
  249. this.panel.dashes = this.panel.lines ? this.panel.dashes : false;
  250. // Populate element
  251. const options: any = this.buildFlotOptions(this.panel);
  252. this.prepareXAxis(options, this.panel);
  253. this.configureYAxisOptions(this.data, options);
  254. this.thresholdManager.addFlotOptions(options, this.panel);
  255. this.timeRegionManager.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 millisecond 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 };