graph.ts 20 KB

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