graph.ts 21 KB

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