graph.ts 25 KB

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