graph.ts 25 KB

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