graph.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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].shareZero) {
  140. shareYLevel(yaxis[0].min, yaxis[0].max, yaxis[1].min, yaxis[1].max, 0);
  141. }
  142. }
  143. function shareYLevel(minLeft, maxLeft, minRight, maxRight, shareLevel) {
  144. if (shareLevel !== 0) {
  145. minLeft -= shareLevel;
  146. maxLeft -= shareLevel;
  147. minRight -= shareLevel;
  148. maxRight -= shareLevel;
  149. }
  150. // wide Y min and max using increased wideFactor
  151. var deltaLeft = maxLeft - minLeft;
  152. var deltaRight = maxRight - minRight;
  153. var wideFactor = 0.25;
  154. if (deltaLeft === 0) {
  155. minLeft -= wideFactor;
  156. maxLeft += wideFactor;
  157. }
  158. if (deltaRight === 0) {
  159. minRight -= wideFactor;
  160. maxRight += wideFactor;
  161. }
  162. // on the opposite sides with respect to zero
  163. if ((minLeft >= 0 && maxRight <= 0) || (maxLeft <= 0 && minRight >= 0)) {
  164. if (minLeft >= 0) {
  165. minLeft = -maxLeft;
  166. maxRight = -minRight;
  167. } else {
  168. maxLeft = -minLeft;
  169. minRight = -maxRight;
  170. }
  171. } else {
  172. var limitTop = Infinity;
  173. var limitBottom = -Infinity;
  174. var absLeftMin = Math.abs(minLeft);
  175. var absLeftMax = Math.abs(maxLeft);
  176. var absRightMin = Math.abs(minRight);
  177. var absRightMax = Math.abs(maxRight);
  178. var upLeft = _.max([absLeftMin, absLeftMax]);
  179. var downLeft = _.min([absLeftMin, absLeftMax]);
  180. var upRight = _.max([absRightMin, absRightMax]);
  181. var downRight = _.min([absRightMin, absRightMax]);
  182. var oneSide = (minLeft >= 0 && minRight >= 0) || (maxLeft <= 0 && maxRight <= 0);
  183. var rateLeft, rateRight, rate;
  184. // on the one hand with respect to zero
  185. if (oneSide) {
  186. rateLeft = downLeft ? upLeft / downLeft : downLeft >= 0 ? limitTop : limitBottom;
  187. rateRight = downRight ? upRight / downRight : downRight >= 0 ? limitTop : limitBottom;
  188. rate = _.max([rateLeft, rateRight]);
  189. if (rate === limitTop) {
  190. if (maxLeft > 0) {
  191. minLeft = 0;
  192. minRight = 0;
  193. } else {
  194. maxLeft = 0;
  195. maxRight = 0;
  196. }
  197. } else {
  198. var coef = deltaLeft / deltaRight;
  199. if ((rate === rateLeft && minLeft > 0) || (rate === rateRight && maxRight < 0)) {
  200. maxLeft = maxRight * coef;
  201. minRight = minLeft / coef;
  202. } else {
  203. minLeft = minRight * coef;
  204. maxRight = maxLeft / coef;
  205. }
  206. }
  207. } else {
  208. rateLeft =
  209. minLeft && maxLeft
  210. ? minLeft < 0 ? maxLeft / minLeft : limitBottom
  211. : minLeft < 0 || maxRight >= 0 ? limitBottom : limitTop;
  212. rateRight =
  213. minRight && maxRight
  214. ? minRight < 0 ? maxRight / minRight : limitBottom
  215. : minRight < 0 || maxLeft >= 0 ? limitBottom : limitTop;
  216. rate = _.max([rateLeft, rateRight]);
  217. if (rate === rateLeft) {
  218. minRight =
  219. upRight === absRightMin && (absRightMin !== absRightMax || upLeft !== absLeftMin)
  220. ? -upRight
  221. : upRight / rate;
  222. maxRight = upRight === absRightMax ? upRight : -upRight * rate;
  223. } else {
  224. minLeft =
  225. upLeft === absLeftMin && (absLeftMin !== absLeftMax || upRight !== absRightMin)
  226. ? -upLeft
  227. : upLeft / rate;
  228. maxLeft = upLeft === absLeftMax ? upLeft : -upLeft * rate;
  229. }
  230. }
  231. }
  232. if (shareLevel !== 0) {
  233. minLeft += shareLevel;
  234. maxLeft += shareLevel;
  235. minRight += shareLevel;
  236. maxRight += shareLevel;
  237. }
  238. }
  239. // Series could have different timeSteps,
  240. // let's find the smallest one so that bars are correctly rendered.
  241. // In addition, only take series which are rendered as bars for this.
  242. function getMinTimeStepOfSeries(data) {
  243. var min = Number.MAX_VALUE;
  244. for (let i = 0; i < data.length; i++) {
  245. if (!data[i].stats.timeStep) {
  246. continue;
  247. }
  248. if (panel.bars) {
  249. if (data[i].bars && data[i].bars.show === false) {
  250. continue;
  251. }
  252. } else {
  253. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  254. continue;
  255. }
  256. }
  257. if (data[i].stats.timeStep < min) {
  258. min = data[i].stats.timeStep;
  259. }
  260. }
  261. return min;
  262. }
  263. // Function for rendering panel
  264. function render_panel() {
  265. panelWidth = elem.width();
  266. if (shouldAbortRender()) {
  267. return;
  268. }
  269. // give space to alert editing
  270. thresholdManager.prepare(elem, data);
  271. // un-check dashes if lines are unchecked
  272. panel.dashes = panel.lines ? panel.dashes : false;
  273. // Populate element
  274. let options: any = buildFlotOptions(panel);
  275. prepareXAxis(options, panel);
  276. configureYAxisOptions(data, options);
  277. thresholdManager.addFlotOptions(options, panel);
  278. eventManager.addFlotEvents(annotations, options);
  279. sortedSeries = sortSeries(data, panel);
  280. callPlot(options, true);
  281. }
  282. function buildFlotPairs(data) {
  283. for (let i = 0; i < data.length; i++) {
  284. let series = data[i];
  285. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  286. // if hidden remove points and disable stack
  287. if (ctrl.hiddenSeries[series.alias]) {
  288. series.data = [];
  289. series.stack = false;
  290. }
  291. }
  292. }
  293. function prepareXAxis(options, panel) {
  294. switch (panel.xaxis.mode) {
  295. case 'series': {
  296. options.series.bars.barWidth = 0.7;
  297. options.series.bars.align = 'center';
  298. for (let i = 0; i < data.length; i++) {
  299. let series = data[i];
  300. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  301. }
  302. addXSeriesAxis(options);
  303. break;
  304. }
  305. case 'histogram': {
  306. let bucketSize: number;
  307. let values = getSeriesValues(data);
  308. if (data.length && values.length) {
  309. let histMin = _.min(_.map(data, s => s.stats.min));
  310. let histMax = _.max(_.map(data, s => s.stats.max));
  311. let ticks = panel.xaxis.buckets || panelWidth / 50;
  312. bucketSize = tickStep(histMin, histMax, ticks);
  313. let histogram = convertValuesToHistogram(values, bucketSize);
  314. data[0].data = histogram;
  315. options.series.bars.barWidth = bucketSize * 0.8;
  316. } else {
  317. bucketSize = 0;
  318. }
  319. addXHistogramAxis(options, bucketSize);
  320. break;
  321. }
  322. case 'table': {
  323. options.series.bars.barWidth = 0.7;
  324. options.series.bars.align = 'center';
  325. addXTableAxis(options);
  326. break;
  327. }
  328. default: {
  329. options.series.bars.barWidth = getMinTimeStepOfSeries(data) / 1.5;
  330. addTimeAxis(options);
  331. break;
  332. }
  333. }
  334. }
  335. function callPlot(options, incrementRenderCounter) {
  336. try {
  337. plot = $.plot(elem, sortedSeries, options);
  338. if (ctrl.renderError) {
  339. delete ctrl.error;
  340. delete ctrl.inspector;
  341. }
  342. } catch (e) {
  343. console.log('flotcharts error', e);
  344. ctrl.error = e.message || 'Render Error';
  345. ctrl.renderError = true;
  346. ctrl.inspector = { error: e };
  347. }
  348. if (incrementRenderCounter) {
  349. ctrl.renderingCompleted();
  350. }
  351. }
  352. function buildFlotOptions(panel) {
  353. let gridColor = '#c8c8c8';
  354. if (config.bootData.user.lightTheme === true) {
  355. gridColor = '#a1a1a1';
  356. }
  357. const stack = panel.stack ? true : null;
  358. let options = {
  359. hooks: {
  360. draw: [drawHook],
  361. processOffset: [processOffsetHook],
  362. processRange: [processRangeHook],
  363. },
  364. legend: { show: false },
  365. series: {
  366. stackpercent: panel.stack ? panel.percentage : false,
  367. stack: panel.percentage ? null : stack,
  368. lines: {
  369. show: panel.lines,
  370. zero: false,
  371. fill: translateFillOption(panel.fill),
  372. lineWidth: panel.dashes ? 0 : panel.linewidth,
  373. steps: panel.steppedLine,
  374. },
  375. dashes: {
  376. show: panel.dashes,
  377. lineWidth: panel.linewidth,
  378. dashLength: [panel.dashLength, panel.spaceLength],
  379. },
  380. bars: {
  381. show: panel.bars,
  382. fill: 1,
  383. barWidth: 1,
  384. zero: false,
  385. lineWidth: 0,
  386. },
  387. points: {
  388. show: panel.points,
  389. fill: 1,
  390. fillColor: false,
  391. radius: panel.points ? panel.pointradius : 2,
  392. },
  393. shadowSize: 0,
  394. },
  395. yaxes: [],
  396. xaxis: {},
  397. grid: {
  398. minBorderMargin: 0,
  399. markings: [],
  400. backgroundColor: null,
  401. borderWidth: 0,
  402. hoverable: true,
  403. clickable: true,
  404. color: gridColor,
  405. margin: { left: 0, right: 0 },
  406. labelMarginX: 0,
  407. },
  408. selection: {
  409. mode: 'x',
  410. color: '#666',
  411. },
  412. crosshair: {
  413. mode: 'x',
  414. },
  415. };
  416. return options;
  417. }
  418. function sortSeries(series, panel) {
  419. var sortBy = panel.legend.sort;
  420. var sortOrder = panel.legend.sortDesc;
  421. var haveSortBy = sortBy !== null && sortBy !== undefined;
  422. var haveSortOrder = sortOrder !== null && sortOrder !== undefined;
  423. var shouldSortBy = panel.stack && haveSortBy && haveSortOrder;
  424. var sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  425. if (shouldSortBy) {
  426. return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
  427. } else {
  428. return _.sortBy(series, s => s.zindex);
  429. }
  430. }
  431. function translateFillOption(fill) {
  432. if (panel.percentage && panel.stack) {
  433. return fill === 0 ? 0.001 : fill / 10;
  434. } else {
  435. return fill / 10;
  436. }
  437. }
  438. function addTimeAxis(options) {
  439. var ticks = panelWidth / 100;
  440. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  441. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  442. options.xaxis = {
  443. timezone: dashboard.getTimezone(),
  444. show: panel.xaxis.show,
  445. mode: 'time',
  446. min: min,
  447. max: max,
  448. label: 'Datetime',
  449. ticks: ticks,
  450. timeformat: time_format(ticks, min, max),
  451. };
  452. }
  453. function addXSeriesAxis(options) {
  454. var ticks = _.map(data, function(series, index) {
  455. return [index + 1, series.alias];
  456. });
  457. options.xaxis = {
  458. timezone: dashboard.getTimezone(),
  459. show: panel.xaxis.show,
  460. mode: null,
  461. min: 0,
  462. max: ticks.length + 1,
  463. label: 'Datetime',
  464. ticks: ticks,
  465. };
  466. }
  467. function addXHistogramAxis(options, bucketSize) {
  468. let ticks, min, max;
  469. let defaultTicks = panelWidth / 50;
  470. if (data.length && bucketSize) {
  471. ticks = _.map(data[0].data, point => point[0]);
  472. min = _.min(ticks);
  473. max = _.max(ticks);
  474. // Adjust tick step
  475. let tickStep = bucketSize;
  476. let ticks_num = Math.floor((max - min) / tickStep);
  477. while (ticks_num > defaultTicks) {
  478. tickStep = tickStep * 2;
  479. ticks_num = Math.ceil((max - min) / tickStep);
  480. }
  481. // Expand ticks for pretty view
  482. min = Math.floor(min / tickStep) * tickStep;
  483. max = Math.ceil(max / tickStep) * tickStep;
  484. ticks = [];
  485. for (let i = min; i <= max; i += tickStep) {
  486. ticks.push(i);
  487. }
  488. } else {
  489. // Set defaults if no data
  490. ticks = defaultTicks / 2;
  491. min = 0;
  492. max = 1;
  493. }
  494. options.xaxis = {
  495. timezone: dashboard.getTimezone(),
  496. show: panel.xaxis.show,
  497. mode: null,
  498. min: min,
  499. max: max,
  500. label: 'Histogram',
  501. ticks: ticks,
  502. };
  503. // Use 'short' format for histogram values
  504. configureAxisMode(options.xaxis, 'short');
  505. }
  506. function addXTableAxis(options) {
  507. var ticks = _.map(data, function(series, seriesIndex) {
  508. return _.map(series.datapoints, function(point, pointIndex) {
  509. var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  510. return [tickIndex + 1, point[1]];
  511. });
  512. });
  513. ticks = _.flatten(ticks, true);
  514. options.xaxis = {
  515. timezone: dashboard.getTimezone(),
  516. show: panel.xaxis.show,
  517. mode: null,
  518. min: 0,
  519. max: ticks.length + 1,
  520. label: 'Datetime',
  521. ticks: ticks,
  522. };
  523. }
  524. function configureYAxisOptions(data, options) {
  525. var defaults = {
  526. position: 'left',
  527. show: panel.yaxes[0].show,
  528. index: 1,
  529. logBase: panel.yaxes[0].logBase || 1,
  530. min: parseNumber(panel.yaxes[0].min),
  531. max: parseNumber(panel.yaxes[0].max),
  532. tickDecimals: panel.yaxes[0].decimals,
  533. };
  534. options.yaxes.push(defaults);
  535. if (_.find(data, { yaxis: 2 })) {
  536. var secondY = _.clone(defaults);
  537. secondY.index = 2;
  538. secondY.show = panel.yaxes[1].show;
  539. secondY.logBase = panel.yaxes[1].logBase || 1;
  540. secondY.position = 'right';
  541. secondY.min = parseNumber(panel.yaxes[1].min);
  542. secondY.max = parseNumber(panel.yaxes[1].max);
  543. secondY.tickDecimals = panel.yaxes[1].decimals;
  544. options.yaxes.push(secondY);
  545. applyLogScale(options.yaxes[1], data);
  546. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? 'percent' : panel.yaxes[1].format);
  547. }
  548. applyLogScale(options.yaxes[0], data);
  549. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? 'percent' : panel.yaxes[0].format);
  550. }
  551. function parseNumber(value: any) {
  552. if (value === null || typeof value === 'undefined') {
  553. return null;
  554. }
  555. return _.toNumber(value);
  556. }
  557. function 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. var series, i;
  569. var 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 = function(v) {
  583. return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
  584. };
  585. axis.inverseTransform = function(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 = 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. function generateTicksForLogScaleYAxis(min, max, logBase) {
  628. let ticks = [];
  629. var nextTick;
  630. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  631. ticks.push(nextTick);
  632. }
  633. const maxNumTicks = Math.ceil(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. function configureAxisMode(axis, format) {
  645. axis.tickFormatter = function(val, axis) {
  646. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  647. };
  648. }
  649. function time_format(ticks, min, max) {
  650. if (min && max && ticks) {
  651. var range = max - min;
  652. var secPerTick = range / ticks / 1000;
  653. var oneDay = 86400000;
  654. var oneYear = 31536000000;
  655. if (secPerTick <= 45) {
  656. return '%H:%M:%S';
  657. }
  658. if (secPerTick <= 7200 || range <= oneDay) {
  659. return '%H:%M';
  660. }
  661. if (secPerTick <= 80000) {
  662. return '%m/%d %H:%M';
  663. }
  664. if (secPerTick <= 2419200 || range <= oneYear) {
  665. return '%m/%d';
  666. }
  667. return '%Y-%m';
  668. }
  669. return '%H:%M';
  670. }
  671. elem.bind('plotselected', function(event, ranges) {
  672. if (panel.xaxis.mode !== 'time') {
  673. // Skip if panel in histogram or series mode
  674. plot.clearSelection();
  675. return;
  676. }
  677. if ((ranges.ctrlKey || ranges.metaKey) && dashboard.meta.canEdit) {
  678. // Add annotation
  679. setTimeout(() => {
  680. eventManager.updateTime(ranges.xaxis);
  681. }, 100);
  682. } else {
  683. scope.$apply(function() {
  684. timeSrv.setTime({
  685. from: moment.utc(ranges.xaxis.from),
  686. to: moment.utc(ranges.xaxis.to),
  687. });
  688. });
  689. }
  690. });
  691. elem.bind('plotclick', function(event, pos, item) {
  692. if (panel.xaxis.mode !== 'time') {
  693. // Skip if panel in histogram or series mode
  694. return;
  695. }
  696. if ((pos.ctrlKey || pos.metaKey) && dashboard.meta.canEdit) {
  697. // Skip if range selected (added in "plotselected" event handler)
  698. let isRangeSelection = pos.x !== pos.x1;
  699. if (!isRangeSelection) {
  700. setTimeout(() => {
  701. eventManager.updateTime({ from: pos.x, to: null });
  702. }, 100);
  703. }
  704. }
  705. });
  706. scope.$on('$destroy', function() {
  707. tooltip.destroy();
  708. elem.off();
  709. elem.remove();
  710. });
  711. },
  712. };
  713. }
  714. coreModule.directive('grafanaGraph', graphDirective);