graph.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. const histMin = _.min(_.map(this.data, s => s.stats.min));
  289. const histMax = _.max(_.map(this.data, s => s.stats.max));
  290. const ticks = panel.xaxis.buckets || this.panelWidth / 50;
  291. bucketSize = tickStep(histMin, histMax, ticks);
  292. options.series.bars.barWidth = bucketSize * 0.8;
  293. this.data = convertToHistogramData(this.data, bucketSize, this.ctrl.hiddenSeries, histMin, histMax);
  294. } else {
  295. bucketSize = 0;
  296. }
  297. this.addXHistogramAxis(options, bucketSize);
  298. break;
  299. }
  300. case 'table': {
  301. options.series.bars.barWidth = 0.7;
  302. options.series.bars.align = 'center';
  303. this.addXTableAxis(options);
  304. break;
  305. }
  306. default: {
  307. options.series.bars.barWidth = this.getMinTimeStepOfSeries(this.data) / 1.5;
  308. this.addTimeAxis(options);
  309. break;
  310. }
  311. }
  312. }
  313. callPlot(options, incrementRenderCounter) {
  314. try {
  315. this.plot = $.plot(this.elem, this.sortedSeries, options);
  316. if (this.ctrl.renderError) {
  317. delete this.ctrl.error;
  318. delete this.ctrl.inspector;
  319. }
  320. } catch (e) {
  321. console.log('flotcharts error', e);
  322. this.ctrl.error = e.message || 'Render Error';
  323. this.ctrl.renderError = true;
  324. this.ctrl.inspector = { error: e };
  325. }
  326. if (incrementRenderCounter) {
  327. this.ctrl.renderingCompleted();
  328. }
  329. }
  330. buildFlotOptions(panel) {
  331. let gridColor = '#c8c8c8';
  332. if (config.bootData.user.lightTheme === true) {
  333. gridColor = '#a1a1a1';
  334. }
  335. const stack = panel.stack ? true : null;
  336. const options = {
  337. hooks: {
  338. draw: [this.drawHook.bind(this)],
  339. processOffset: [this.processOffsetHook.bind(this)],
  340. processRange: [this.processRangeHook.bind(this)],
  341. },
  342. legend: { show: false },
  343. series: {
  344. stackpercent: panel.stack ? panel.percentage : false,
  345. stack: panel.percentage ? null : stack,
  346. lines: {
  347. show: panel.lines,
  348. zero: false,
  349. fill: this.translateFillOption(panel.fill),
  350. lineWidth: panel.dashes ? 0 : panel.linewidth,
  351. steps: panel.steppedLine,
  352. },
  353. dashes: {
  354. show: panel.dashes,
  355. lineWidth: panel.linewidth,
  356. dashLength: [panel.dashLength, panel.spaceLength],
  357. },
  358. bars: {
  359. show: panel.bars,
  360. fill: 1,
  361. barWidth: 1,
  362. zero: false,
  363. lineWidth: 0,
  364. },
  365. points: {
  366. show: panel.points,
  367. fill: 1,
  368. fillColor: false,
  369. radius: panel.points ? panel.pointradius : 2,
  370. },
  371. shadowSize: 0,
  372. },
  373. yaxes: [],
  374. xaxis: {},
  375. grid: {
  376. minBorderMargin: 0,
  377. markings: [],
  378. backgroundColor: null,
  379. borderWidth: 0,
  380. hoverable: true,
  381. clickable: true,
  382. color: gridColor,
  383. margin: { left: 0, right: 0 },
  384. labelMarginX: 0,
  385. },
  386. selection: {
  387. mode: 'x',
  388. color: '#666',
  389. },
  390. crosshair: {
  391. mode: 'x',
  392. },
  393. };
  394. return options;
  395. }
  396. sortSeries(series, panel) {
  397. const sortBy = panel.legend.sort;
  398. const sortOrder = panel.legend.sortDesc;
  399. const haveSortBy = sortBy !== null && sortBy !== undefined;
  400. const haveSortOrder = sortOrder !== null && sortOrder !== undefined;
  401. const shouldSortBy = panel.stack && haveSortBy && haveSortOrder;
  402. const sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  403. if (shouldSortBy) {
  404. return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
  405. } else {
  406. return _.sortBy(series, s => s.zindex);
  407. }
  408. }
  409. translateFillOption(fill) {
  410. if (this.panel.percentage && this.panel.stack) {
  411. return fill === 0 ? 0.001 : fill / 10;
  412. } else {
  413. return fill / 10;
  414. }
  415. }
  416. addTimeAxis(options) {
  417. const ticks = this.panelWidth / 100;
  418. const min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
  419. const max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
  420. options.xaxis = {
  421. timezone: this.dashboard.getTimezone(),
  422. show: this.panel.xaxis.show,
  423. mode: 'time',
  424. min: min,
  425. max: max,
  426. label: 'Datetime',
  427. ticks: ticks,
  428. timeformat: this.time_format(ticks, min, max),
  429. };
  430. }
  431. addXSeriesAxis(options) {
  432. const ticks = _.map(this.data, (series, index) => {
  433. return [index + 1, series.alias];
  434. });
  435. options.xaxis = {
  436. timezone: this.dashboard.getTimezone(),
  437. show: this.panel.xaxis.show,
  438. mode: null,
  439. min: 0,
  440. max: ticks.length + 1,
  441. label: 'Datetime',
  442. ticks: ticks,
  443. };
  444. }
  445. addXHistogramAxis(options, bucketSize) {
  446. let ticks, min, max;
  447. const defaultTicks = this.panelWidth / 50;
  448. if (this.data.length && bucketSize) {
  449. const tickValues = [];
  450. for (const d of this.data) {
  451. for (const point of d.data) {
  452. tickValues[point[0]] = true;
  453. }
  454. }
  455. ticks = Object.keys(tickValues).map(v => Number(v));
  456. min = _.min(ticks);
  457. max = _.max(ticks);
  458. // Adjust tick step
  459. let tickStep = bucketSize;
  460. let ticksNum = Math.floor((max - min) / tickStep);
  461. while (ticksNum > defaultTicks) {
  462. tickStep = tickStep * 2;
  463. ticksNum = Math.ceil((max - min) / tickStep);
  464. }
  465. // Expand ticks for pretty view
  466. min = Math.floor(min / tickStep) * tickStep;
  467. // 1.01 is 101% - ensure we have enough space for last bar
  468. max = Math.ceil(max * 1.01 / tickStep) * tickStep;
  469. ticks = [];
  470. for (let i = min; i <= max; i += tickStep) {
  471. ticks.push(i);
  472. }
  473. } else {
  474. // Set defaults if no data
  475. ticks = defaultTicks / 2;
  476. min = 0;
  477. max = 1;
  478. }
  479. options.xaxis = {
  480. timezone: this.dashboard.getTimezone(),
  481. show: this.panel.xaxis.show,
  482. mode: null,
  483. min: min,
  484. max: max,
  485. label: 'Histogram',
  486. ticks: ticks,
  487. };
  488. // Use 'short' format for histogram values
  489. this.configureAxisMode(options.xaxis, 'short');
  490. }
  491. addXTableAxis(options) {
  492. let ticks = _.map(this.data, (series, seriesIndex) => {
  493. return _.map(series.datapoints, (point, pointIndex) => {
  494. const tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  495. return [tickIndex + 1, point[1]];
  496. });
  497. });
  498. ticks = _.flatten(ticks, true);
  499. options.xaxis = {
  500. timezone: this.dashboard.getTimezone(),
  501. show: this.panel.xaxis.show,
  502. mode: null,
  503. min: 0,
  504. max: ticks.length + 1,
  505. label: 'Datetime',
  506. ticks: ticks,
  507. };
  508. }
  509. configureYAxisOptions(data, options) {
  510. const defaults = {
  511. position: 'left',
  512. show: this.panel.yaxes[0].show,
  513. index: 1,
  514. logBase: this.panel.yaxes[0].logBase || 1,
  515. min: this.parseNumber(this.panel.yaxes[0].min),
  516. max: this.parseNumber(this.panel.yaxes[0].max),
  517. tickDecimals: this.panel.yaxes[0].decimals,
  518. };
  519. options.yaxes.push(defaults);
  520. if (_.find(data, { yaxis: 2 })) {
  521. const secondY = _.clone(defaults);
  522. secondY.index = 2;
  523. secondY.show = this.panel.yaxes[1].show;
  524. secondY.logBase = this.panel.yaxes[1].logBase || 1;
  525. secondY.position = 'right';
  526. secondY.min = this.parseNumber(this.panel.yaxes[1].min);
  527. secondY.max = this.parseNumber(this.panel.yaxes[1].max);
  528. secondY.tickDecimals = this.panel.yaxes[1].decimals;
  529. options.yaxes.push(secondY);
  530. this.applyLogScale(options.yaxes[1], data);
  531. this.configureAxisMode(
  532. options.yaxes[1],
  533. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[1].format
  534. );
  535. }
  536. this.applyLogScale(options.yaxes[0], data);
  537. this.configureAxisMode(
  538. options.yaxes[0],
  539. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[0].format
  540. );
  541. }
  542. parseNumber(value: any) {
  543. if (value === null || typeof value === 'undefined') {
  544. return null;
  545. }
  546. return _.toNumber(value);
  547. }
  548. applyLogScale(axis, data) {
  549. if (axis.logBase === 1) {
  550. return;
  551. }
  552. const minSetToZero = axis.min === 0;
  553. if (axis.min < Number.MIN_VALUE) {
  554. axis.min = null;
  555. }
  556. if (axis.max < Number.MIN_VALUE) {
  557. axis.max = null;
  558. }
  559. let series, i;
  560. let max = axis.max,
  561. min = axis.min;
  562. for (i = 0; i < data.length; i++) {
  563. series = data[i];
  564. if (series.yaxis === axis.index) {
  565. if (!max || max < series.stats.max) {
  566. max = series.stats.max;
  567. }
  568. if (!min || min > series.stats.logmin) {
  569. min = series.stats.logmin;
  570. }
  571. }
  572. }
  573. axis.transform = v => {
  574. return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
  575. };
  576. axis.inverseTransform = v => {
  577. return Math.pow(axis.logBase, v);
  578. };
  579. if (!max && !min) {
  580. max = axis.inverseTransform(+2);
  581. min = axis.inverseTransform(-2);
  582. } else if (!max) {
  583. max = min * axis.inverseTransform(+4);
  584. } else if (!min) {
  585. min = max * axis.inverseTransform(-4);
  586. }
  587. if (axis.min) {
  588. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  589. } else {
  590. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  591. }
  592. if (axis.max) {
  593. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  594. } else {
  595. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  596. }
  597. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  598. return;
  599. }
  600. if (Number.isFinite(min) && Number.isFinite(max)) {
  601. if (minSetToZero) {
  602. axis.min = 0.1;
  603. min = 1;
  604. }
  605. axis.ticks = this.generateTicksForLogScaleYAxis(min, max, axis.logBase);
  606. if (minSetToZero) {
  607. axis.ticks.unshift(0.1);
  608. }
  609. if (axis.ticks[axis.ticks.length - 1] > axis.max) {
  610. axis.max = axis.ticks[axis.ticks.length - 1];
  611. }
  612. } else {
  613. axis.ticks = [1, 2];
  614. delete axis.min;
  615. delete axis.max;
  616. }
  617. }
  618. generateTicksForLogScaleYAxis(min, max, logBase) {
  619. let ticks = [];
  620. let nextTick;
  621. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  622. ticks.push(nextTick);
  623. }
  624. const maxNumTicks = Math.ceil(this.ctrl.height / 25);
  625. const numTicks = ticks.length;
  626. if (numTicks > maxNumTicks) {
  627. const factor = Math.ceil(numTicks / maxNumTicks) * logBase;
  628. ticks = [];
  629. for (nextTick = min; nextTick <= max * factor; nextTick *= factor) {
  630. ticks.push(nextTick);
  631. }
  632. }
  633. return ticks;
  634. }
  635. configureAxisMode(axis, format) {
  636. axis.tickFormatter = (val, axis) => {
  637. const formatter = getValueFormat(format);
  638. if (!formatter) {
  639. throw new Error(`Unit '${format}' is not supported`);
  640. }
  641. return formatter(val, axis.tickDecimals, axis.scaledDecimals);
  642. };
  643. }
  644. time_format(ticks, min, max) {
  645. if (min && max && ticks) {
  646. const range = max - min;
  647. const secPerTick = range / ticks / 1000;
  648. // Need have 10 millisecond margin on the day range
  649. // As sometimes last 24 hour dashboard evaluates to more than 86400000
  650. const oneDay = 86400010;
  651. const oneYear = 31536000000;
  652. if (secPerTick <= 45) {
  653. return '%H:%M:%S';
  654. }
  655. if (secPerTick <= 7200 || range <= oneDay) {
  656. return '%H:%M';
  657. }
  658. if (secPerTick <= 80000) {
  659. return '%m/%d %H:%M';
  660. }
  661. if (secPerTick <= 2419200 || range <= oneYear) {
  662. return '%m/%d';
  663. }
  664. return '%Y-%m';
  665. }
  666. return '%H:%M';
  667. }
  668. }
  669. /** @ngInject */
  670. function graphDirective(timeSrv, popoverSrv, contextSrv) {
  671. return {
  672. restrict: 'A',
  673. template: '',
  674. link: (scope, elem) => {
  675. return new GraphElement(scope, elem, timeSrv);
  676. },
  677. };
  678. }
  679. coreModule.directive('grafanaGraph', graphDirective);
  680. export { GraphElement, graphDirective };