graph.ts 21 KB

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