graph.ts 23 KB

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