graph.ts 23 KB

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