graph.ts 22 KB

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