graph.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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 { tickStep } from 'app/core/utils/ticks';
  14. import { appEvents, coreModule, updateLegendValues } from 'app/core/core';
  15. import GraphTooltip from './graph_tooltip';
  16. import { ThresholdManager } from './threshold_manager';
  17. import { TimeRegionManager } from './time_region_manager';
  18. import { EventManager } from 'app/features/annotations/all';
  19. import { convertToHistogramData } from './histogram';
  20. import { alignYLevel } from './align_yaxes';
  21. import config from 'app/core/config';
  22. import React from 'react';
  23. import ReactDOM from 'react-dom';
  24. import { Legend, GraphLegendProps } from './Legend/Legend';
  25. import { GraphCtrl } from './module';
  26. import { getValueFormat } from '@grafana/ui';
  27. import { provideTheme } from 'app/core/utils/ConfigProvider';
  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, 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: moment.utc(ranges.xaxis.from),
  144. to: moment.utc(ranges.xaxis.to),
  145. });
  146. });
  147. }
  148. }
  149. onPlotClick(event, 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. lineWidth: panel.dashes ? 0 : panel.linewidth,
  359. steps: panel.steppedLine,
  360. },
  361. dashes: {
  362. show: panel.dashes,
  363. lineWidth: panel.linewidth,
  364. dashLength: [panel.dashLength, panel.spaceLength],
  365. },
  366. bars: {
  367. show: panel.bars,
  368. fill: 1,
  369. barWidth: 1,
  370. zero: false,
  371. lineWidth: 0,
  372. },
  373. points: {
  374. show: panel.points,
  375. fill: 1,
  376. fillColor: false,
  377. radius: panel.points ? panel.pointradius : 2,
  378. },
  379. shadowSize: 0,
  380. },
  381. yaxes: [],
  382. xaxis: {},
  383. grid: {
  384. minBorderMargin: 0,
  385. markings: [],
  386. backgroundColor: null,
  387. borderWidth: 0,
  388. hoverable: true,
  389. clickable: true,
  390. color: gridColor,
  391. margin: { left: 0, right: 0 },
  392. labelMarginX: 0,
  393. },
  394. selection: {
  395. mode: 'x',
  396. color: '#666',
  397. },
  398. crosshair: {
  399. mode: 'x',
  400. },
  401. };
  402. return options;
  403. }
  404. sortSeries(series, panel) {
  405. const sortBy = panel.legend.sort;
  406. const sortOrder = panel.legend.sortDesc;
  407. const haveSortBy = sortBy !== null && sortBy !== undefined;
  408. const haveSortOrder = sortOrder !== null && sortOrder !== undefined;
  409. const shouldSortBy = panel.stack && haveSortBy && haveSortOrder;
  410. const sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  411. if (shouldSortBy) {
  412. return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
  413. } else {
  414. return _.sortBy(series, s => s.zindex);
  415. }
  416. }
  417. translateFillOption(fill) {
  418. if (this.panel.percentage && this.panel.stack) {
  419. return fill === 0 ? 0.001 : fill / 10;
  420. } else {
  421. return fill / 10;
  422. }
  423. }
  424. addTimeAxis(options) {
  425. const ticks = this.panelWidth / 100;
  426. const min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
  427. const max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
  428. options.xaxis = {
  429. timezone: this.dashboard.getTimezone(),
  430. show: this.panel.xaxis.show,
  431. mode: 'time',
  432. min: min,
  433. max: max,
  434. label: 'Datetime',
  435. ticks: ticks,
  436. timeformat: this.time_format(ticks, min, max),
  437. };
  438. }
  439. addXSeriesAxis(options) {
  440. const ticks = _.map(this.data, (series, index) => {
  441. return [index + 1, series.alias];
  442. });
  443. options.xaxis = {
  444. timezone: this.dashboard.getTimezone(),
  445. show: this.panel.xaxis.show,
  446. mode: null,
  447. min: 0,
  448. max: ticks.length + 1,
  449. label: 'Datetime',
  450. ticks: ticks,
  451. };
  452. }
  453. addXHistogramAxis(options, bucketSize) {
  454. let ticks, min, max;
  455. const defaultTicks = this.panelWidth / 50;
  456. if (this.data.length && bucketSize) {
  457. const tickValues = [];
  458. for (const d of this.data) {
  459. for (const point of d.data) {
  460. tickValues[point[0]] = true;
  461. }
  462. }
  463. ticks = Object.keys(tickValues).map(v => Number(v));
  464. min = _.min(ticks);
  465. max = _.max(ticks);
  466. // Adjust tick step
  467. let tickStep = bucketSize;
  468. let ticksNum = Math.floor((max - min) / tickStep);
  469. while (ticksNum > defaultTicks) {
  470. tickStep = tickStep * 2;
  471. ticksNum = Math.ceil((max - min) / tickStep);
  472. }
  473. // Expand ticks for pretty view
  474. min = Math.floor(min / tickStep) * tickStep;
  475. // 1.01 is 101% - ensure we have enough space for last bar
  476. max = Math.ceil((max * 1.01) / tickStep) * tickStep;
  477. ticks = [];
  478. for (let i = min; i <= max; i += tickStep) {
  479. ticks.push(i);
  480. }
  481. } else {
  482. // Set defaults if no data
  483. ticks = defaultTicks / 2;
  484. min = 0;
  485. max = 1;
  486. }
  487. options.xaxis = {
  488. timezone: this.dashboard.getTimezone(),
  489. show: this.panel.xaxis.show,
  490. mode: null,
  491. min: min,
  492. max: max,
  493. label: 'Histogram',
  494. ticks: ticks,
  495. };
  496. // Use 'short' format for histogram values
  497. this.configureAxisMode(options.xaxis, 'short');
  498. }
  499. addXTableAxis(options) {
  500. let ticks = _.map(this.data, (series, seriesIndex) => {
  501. return _.map(series.datapoints, (point, pointIndex) => {
  502. const tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  503. return [tickIndex + 1, point[1]];
  504. });
  505. });
  506. // @ts-ignore, potential bug? is this _.flattenDeep?
  507. ticks = _.flatten(ticks, true);
  508. options.xaxis = {
  509. timezone: this.dashboard.getTimezone(),
  510. show: this.panel.xaxis.show,
  511. mode: null,
  512. min: 0,
  513. max: ticks.length + 1,
  514. label: 'Datetime',
  515. ticks: ticks,
  516. };
  517. }
  518. configureYAxisOptions(data, options) {
  519. const defaults = {
  520. position: 'left',
  521. show: this.panel.yaxes[0].show,
  522. index: 1,
  523. logBase: this.panel.yaxes[0].logBase || 1,
  524. min: this.parseNumber(this.panel.yaxes[0].min),
  525. max: this.parseNumber(this.panel.yaxes[0].max),
  526. tickDecimals: this.panel.yaxes[0].decimals,
  527. };
  528. options.yaxes.push(defaults);
  529. if (_.find(data, { yaxis: 2 })) {
  530. const secondY = _.clone(defaults);
  531. secondY.index = 2;
  532. secondY.show = this.panel.yaxes[1].show;
  533. secondY.logBase = this.panel.yaxes[1].logBase || 1;
  534. secondY.position = 'right';
  535. secondY.min = this.parseNumber(this.panel.yaxes[1].min);
  536. secondY.max = this.parseNumber(this.panel.yaxes[1].max);
  537. secondY.tickDecimals = this.panel.yaxes[1].decimals;
  538. options.yaxes.push(secondY);
  539. this.applyLogScale(options.yaxes[1], data);
  540. this.configureAxisMode(
  541. options.yaxes[1],
  542. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[1].format
  543. );
  544. }
  545. this.applyLogScale(options.yaxes[0], data);
  546. this.configureAxisMode(
  547. options.yaxes[0],
  548. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[0].format
  549. );
  550. }
  551. parseNumber(value: any) {
  552. if (value === null || typeof value === 'undefined') {
  553. return null;
  554. }
  555. return _.toNumber(value);
  556. }
  557. applyLogScale(axis, data) {
  558. if (axis.logBase === 1) {
  559. return;
  560. }
  561. const minSetToZero = axis.min === 0;
  562. if (axis.min < Number.MIN_VALUE) {
  563. axis.min = null;
  564. }
  565. if (axis.max < Number.MIN_VALUE) {
  566. axis.max = null;
  567. }
  568. let series, i;
  569. let max = axis.max,
  570. min = axis.min;
  571. for (i = 0; i < data.length; i++) {
  572. series = data[i];
  573. if (series.yaxis === axis.index) {
  574. if (!max || max < series.stats.max) {
  575. max = series.stats.max;
  576. }
  577. if (!min || min > series.stats.logmin) {
  578. min = series.stats.logmin;
  579. }
  580. }
  581. }
  582. axis.transform = v => {
  583. return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
  584. };
  585. axis.inverseTransform = v => {
  586. return Math.pow(axis.logBase, v);
  587. };
  588. if (!max && !min) {
  589. max = axis.inverseTransform(+2);
  590. min = axis.inverseTransform(-2);
  591. } else if (!max) {
  592. max = min * axis.inverseTransform(+4);
  593. } else if (!min) {
  594. min = max * axis.inverseTransform(-4);
  595. }
  596. if (axis.min) {
  597. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  598. } else {
  599. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  600. }
  601. if (axis.max) {
  602. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  603. } else {
  604. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  605. }
  606. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  607. return;
  608. }
  609. if (Number.isFinite(min) && Number.isFinite(max)) {
  610. if (minSetToZero) {
  611. axis.min = 0.1;
  612. min = 1;
  613. }
  614. axis.ticks = this.generateTicksForLogScaleYAxis(min, max, axis.logBase);
  615. if (minSetToZero) {
  616. axis.ticks.unshift(0.1);
  617. }
  618. if (axis.ticks[axis.ticks.length - 1] > axis.max) {
  619. axis.max = axis.ticks[axis.ticks.length - 1];
  620. }
  621. } else {
  622. axis.ticks = [1, 2];
  623. delete axis.min;
  624. delete axis.max;
  625. }
  626. }
  627. generateTicksForLogScaleYAxis(min, max, logBase) {
  628. let ticks = [];
  629. let nextTick;
  630. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  631. ticks.push(nextTick);
  632. }
  633. const maxNumTicks = Math.ceil(this.ctrl.height / 25);
  634. const numTicks = ticks.length;
  635. if (numTicks > maxNumTicks) {
  636. const factor = Math.ceil(numTicks / maxNumTicks) * logBase;
  637. ticks = [];
  638. for (nextTick = min; nextTick <= max * factor; nextTick *= factor) {
  639. ticks.push(nextTick);
  640. }
  641. }
  642. return ticks;
  643. }
  644. configureAxisMode(axis, format) {
  645. axis.tickFormatter = (val, axis) => {
  646. const formatter = getValueFormat(format);
  647. if (!formatter) {
  648. throw new Error(`Unit '${format}' is not supported`);
  649. }
  650. return formatter(val, axis.tickDecimals, axis.scaledDecimals);
  651. };
  652. }
  653. time_format(ticks, min, max) {
  654. if (min && max && ticks) {
  655. const range = max - min;
  656. const secPerTick = range / ticks / 1000;
  657. // Need have 10 millisecond margin on the day range
  658. // As sometimes last 24 hour dashboard evaluates to more than 86400000
  659. const oneDay = 86400010;
  660. const oneYear = 31536000000;
  661. if (secPerTick <= 45) {
  662. return '%H:%M:%S';
  663. }
  664. if (secPerTick <= 7200 || range <= oneDay) {
  665. return '%H:%M';
  666. }
  667. if (secPerTick <= 80000) {
  668. return '%m/%d %H:%M';
  669. }
  670. if (secPerTick <= 2419200 || range <= oneYear) {
  671. return '%m/%d';
  672. }
  673. return '%Y-%m';
  674. }
  675. return '%H:%M';
  676. }
  677. }
  678. /** @ngInject */
  679. function graphDirective(timeSrv, popoverSrv, contextSrv) {
  680. return {
  681. restrict: 'A',
  682. template: '',
  683. link: (scope, elem) => {
  684. return new GraphElement(scope, elem, timeSrv);
  685. },
  686. };
  687. }
  688. coreModule.directive('grafanaGraph', graphDirective);
  689. export { GraphElement, graphDirective };