graph.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. if (this.plot) {
  121. this.plot.destroy();
  122. this.plot = null;
  123. }
  124. this.tooltip.destroy();
  125. this.elem.off();
  126. this.elem.remove();
  127. ReactDOM.unmountComponentAtNode(this.legendElem);
  128. }
  129. onGraphHoverClear(event: any, info: any) {
  130. if (this.plot) {
  131. this.tooltip.clear(this.plot);
  132. }
  133. }
  134. onPlotSelected(event: JQueryEventObject, ranges: any) {
  135. if (this.panel.xaxis.mode !== 'time') {
  136. // Skip if panel in histogram or series mode
  137. this.plot.clearSelection();
  138. return;
  139. }
  140. if ((ranges.ctrlKey || ranges.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  141. // Add annotation
  142. setTimeout(() => {
  143. this.eventManager.updateTime(ranges.xaxis);
  144. }, 100);
  145. } else {
  146. this.scope.$apply(() => {
  147. this.timeSrv.setTime({
  148. from: toUtc(ranges.xaxis.from),
  149. to: toUtc(ranges.xaxis.to),
  150. });
  151. });
  152. }
  153. }
  154. getContextMenuItems = (flotPosition: { x: number; y: number }, item?: FlotDataPoint): ContextMenuGroup[] => {
  155. const dataLinks: DataLink[] = this.panel.options.dataLinks || [];
  156. const items: ContextMenuGroup[] = [
  157. {
  158. items: [
  159. {
  160. label: 'Add annotation',
  161. icon: 'gicon gicon-annotation',
  162. onClick: () => this.eventManager.updateTime({ from: flotPosition.x, to: null }),
  163. },
  164. ],
  165. },
  166. ];
  167. return item
  168. ? [
  169. ...items,
  170. {
  171. items: [
  172. ...dataLinks.map<ContextMenuItem>(link => {
  173. const linkUiModel = this.linkSrv.getDataLinkUIModel(link, this.panel.scopedVars, {
  174. seriesName: item.series.alias,
  175. datapoint: item.datapoint,
  176. });
  177. return {
  178. label: linkUiModel.title,
  179. url: linkUiModel.href,
  180. target: linkUiModel.target,
  181. icon: `fa ${linkUiModel.target === '_self' ? 'fa-link' : 'fa-external-link'}`,
  182. };
  183. }),
  184. ],
  185. },
  186. ]
  187. : items;
  188. };
  189. onPlotClick(event: JQueryEventObject, pos: any, item: any) {
  190. const scrollContextElement = this.elem.closest('.view') ? this.elem.closest('.view').get()[0] : null;
  191. const contextMenuSourceItem = item;
  192. let contextMenuItems: ContextMenuItem[];
  193. if (this.panel.xaxis.mode !== 'time') {
  194. // Skip if panel in histogram or series mode
  195. return;
  196. }
  197. if ((pos.ctrlKey || pos.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  198. // Skip if range selected (added in "plotselected" event handler)
  199. if (pos.x !== pos.x1) {
  200. return;
  201. }
  202. setTimeout(() => {
  203. this.eventManager.updateTime({ from: pos.x, to: null });
  204. }, 100);
  205. return;
  206. } else {
  207. this.tooltip.clear(this.plot);
  208. contextMenuItems = this.getContextMenuItems(pos, item) as ContextMenuItem[];
  209. this.scope.$apply(() => {
  210. // Setting nearest CustomScrollbar element as a scroll context for graph context menu
  211. this.contextMenu.setScrollContextElement(scrollContextElement);
  212. this.contextMenu.setSource(contextMenuSourceItem);
  213. this.contextMenu.setMenuItems(contextMenuItems);
  214. this.contextMenu.toggleMenu(pos);
  215. });
  216. }
  217. }
  218. shouldAbortRender() {
  219. if (!this.data) {
  220. return true;
  221. }
  222. if (this.panelWidth === 0) {
  223. return true;
  224. }
  225. return false;
  226. }
  227. drawHook(plot: any) {
  228. // add left axis labels
  229. if (this.panel.yaxes[0].label && this.panel.yaxes[0].show) {
  230. $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
  231. .text(this.panel.yaxes[0].label)
  232. .appendTo(this.elem);
  233. }
  234. // add right axis labels
  235. if (this.panel.yaxes[1].label && this.panel.yaxes[1].show) {
  236. $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
  237. .text(this.panel.yaxes[1].label)
  238. .appendTo(this.elem);
  239. }
  240. if (this.ctrl.dataWarning) {
  241. $(`<div class="datapoints-warning flot-temp-elem">${this.ctrl.dataWarning.title}</div>`).appendTo(this.elem);
  242. }
  243. this.thresholdManager.draw(plot);
  244. this.timeRegionManager.draw(plot);
  245. }
  246. processOffsetHook(plot: any, gridMargin: { left: number; right: number }) {
  247. const left = this.panel.yaxes[0];
  248. const right = this.panel.yaxes[1];
  249. if (left.show && left.label) {
  250. gridMargin.left = 20;
  251. }
  252. if (right.show && right.label) {
  253. gridMargin.right = 20;
  254. }
  255. // apply y-axis min/max options
  256. const yaxis = plot.getYAxes();
  257. for (let i = 0; i < yaxis.length; i++) {
  258. const axis: any = yaxis[i];
  259. const panelOptions = this.panel.yaxes[i];
  260. axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
  261. axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
  262. }
  263. }
  264. processRangeHook(plot: any) {
  265. const yAxes = plot.getYAxes();
  266. const align = this.panel.yaxis.align || false;
  267. if (yAxes.length > 1 && align === true) {
  268. const level = this.panel.yaxis.alignLevel || 0;
  269. alignYLevel(yAxes, parseFloat(level));
  270. }
  271. }
  272. // Series could have different timeSteps,
  273. // let's find the smallest one so that bars are correctly rendered.
  274. // In addition, only take series which are rendered as bars for this.
  275. getMinTimeStepOfSeries(data: any[]) {
  276. let min = Number.MAX_VALUE;
  277. for (let i = 0; i < data.length; i++) {
  278. if (!data[i].stats.timeStep) {
  279. continue;
  280. }
  281. if (this.panel.bars) {
  282. if (data[i].bars && data[i].bars.show === false) {
  283. continue;
  284. }
  285. } else {
  286. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  287. continue;
  288. }
  289. }
  290. if (data[i].stats.timeStep < min) {
  291. min = data[i].stats.timeStep;
  292. }
  293. }
  294. return min;
  295. }
  296. // Function for rendering panel
  297. renderPanel() {
  298. this.panelWidth = this.elem.width();
  299. if (this.shouldAbortRender()) {
  300. return;
  301. }
  302. // give space to alert editing
  303. this.thresholdManager.prepare(this.elem, this.data);
  304. // un-check dashes if lines are unchecked
  305. this.panel.dashes = this.panel.lines ? this.panel.dashes : false;
  306. // Populate element
  307. const options: any = this.buildFlotOptions(this.panel);
  308. this.prepareXAxis(options, this.panel);
  309. this.configureYAxisOptions(this.data, options);
  310. this.thresholdManager.addFlotOptions(options, this.panel);
  311. this.timeRegionManager.addFlotOptions(options, this.panel);
  312. this.eventManager.addFlotEvents(this.annotations, options);
  313. this.sortedSeries = this.sortSeries(this.data, this.panel);
  314. this.callPlot(options, true);
  315. }
  316. buildFlotPairs(data: any) {
  317. for (let i = 0; i < data.length; i++) {
  318. const series = data[i];
  319. series.data = series.getFlotPairs(series.nullPointMode || this.panel.nullPointMode);
  320. // if hidden remove points and disable stack
  321. if (this.ctrl.hiddenSeries[series.alias]) {
  322. series.data = [];
  323. series.stack = false;
  324. }
  325. }
  326. }
  327. prepareXAxis(options: any, panel: any) {
  328. switch (panel.xaxis.mode) {
  329. case 'series': {
  330. options.series.bars.barWidth = 0.7;
  331. options.series.bars.align = 'center';
  332. for (let i = 0; i < this.data.length; i++) {
  333. const series = this.data[i];
  334. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  335. }
  336. this.addXSeriesAxis(options);
  337. break;
  338. }
  339. case 'histogram': {
  340. let bucketSize: number;
  341. if (this.data.length) {
  342. let histMin = _.min(_.map(this.data, s => s.stats.min));
  343. let histMax = _.max(_.map(this.data, s => s.stats.max));
  344. const ticks = panel.xaxis.buckets || this.panelWidth / 50;
  345. if (panel.xaxis.min != null) {
  346. const isInvalidXaxisMin = tickStep(panel.xaxis.min, histMax, ticks) <= 0;
  347. histMin = isInvalidXaxisMin ? histMin : panel.xaxis.min;
  348. }
  349. if (panel.xaxis.max != null) {
  350. const isInvalidXaxisMax = tickStep(histMin, panel.xaxis.max, ticks) <= 0;
  351. histMax = isInvalidXaxisMax ? histMax : panel.xaxis.max;
  352. }
  353. bucketSize = tickStep(histMin, histMax, ticks);
  354. options.series.bars.barWidth = bucketSize * 0.8;
  355. this.data = convertToHistogramData(this.data, bucketSize, this.ctrl.hiddenSeries, histMin, histMax);
  356. } else {
  357. bucketSize = 0;
  358. }
  359. this.addXHistogramAxis(options, bucketSize);
  360. break;
  361. }
  362. case 'table': {
  363. options.series.bars.barWidth = 0.7;
  364. options.series.bars.align = 'center';
  365. this.addXTableAxis(options);
  366. break;
  367. }
  368. default: {
  369. options.series.bars.barWidth = this.getMinTimeStepOfSeries(this.data) / 1.5;
  370. this.addTimeAxis(options);
  371. break;
  372. }
  373. }
  374. }
  375. callPlot(options: any, incrementRenderCounter: boolean) {
  376. try {
  377. this.plot = $.plot(this.elem, this.sortedSeries, options);
  378. if (this.ctrl.renderError) {
  379. delete this.ctrl.error;
  380. delete this.ctrl.inspector;
  381. }
  382. } catch (e) {
  383. console.log('flotcharts error', e);
  384. this.ctrl.error = e.message || 'Render Error';
  385. this.ctrl.renderError = true;
  386. this.ctrl.inspector = { error: e };
  387. }
  388. if (incrementRenderCounter) {
  389. this.ctrl.renderingCompleted();
  390. }
  391. }
  392. buildFlotOptions(panel: any) {
  393. let gridColor = '#c8c8c8';
  394. if (config.bootData.user.lightTheme === true) {
  395. gridColor = '#a1a1a1';
  396. }
  397. const stack = panel.stack ? true : null;
  398. const options: any = {
  399. hooks: {
  400. draw: [this.drawHook.bind(this)],
  401. processOffset: [this.processOffsetHook.bind(this)],
  402. processRange: [this.processRangeHook.bind(this)],
  403. },
  404. legend: { show: false },
  405. series: {
  406. stackpercent: panel.stack ? panel.percentage : false,
  407. stack: panel.percentage ? null : stack,
  408. lines: {
  409. show: panel.lines,
  410. zero: false,
  411. fill: this.translateFillOption(panel.fill),
  412. fillColor: this.getFillGradient(panel.fillGradient),
  413. lineWidth: panel.dashes ? 0 : panel.linewidth,
  414. steps: panel.steppedLine,
  415. },
  416. dashes: {
  417. show: panel.dashes,
  418. lineWidth: panel.linewidth,
  419. dashLength: [panel.dashLength, panel.spaceLength],
  420. },
  421. bars: {
  422. show: panel.bars,
  423. fill: 1,
  424. barWidth: 1,
  425. zero: false,
  426. lineWidth: 0,
  427. },
  428. points: {
  429. show: panel.points,
  430. fill: 1,
  431. fillColor: false,
  432. radius: panel.points ? panel.pointradius : 2,
  433. },
  434. shadowSize: 0,
  435. },
  436. yaxes: [],
  437. xaxis: {},
  438. grid: {
  439. minBorderMargin: 0,
  440. markings: [],
  441. backgroundColor: null,
  442. borderWidth: 0,
  443. hoverable: true,
  444. clickable: true,
  445. color: gridColor,
  446. margin: { left: 0, right: 0 },
  447. labelMarginX: 0,
  448. mouseActiveRadius: 30,
  449. },
  450. selection: {
  451. mode: 'x',
  452. color: '#666',
  453. },
  454. crosshair: {
  455. mode: 'x',
  456. },
  457. };
  458. return options;
  459. }
  460. sortSeries(series: any, panel: any) {
  461. const sortBy = panel.legend.sort;
  462. const sortOrder = panel.legend.sortDesc;
  463. const haveSortBy = sortBy !== null && sortBy !== undefined && panel.legend[sortBy];
  464. const haveSortOrder = sortOrder !== null && sortOrder !== undefined;
  465. const shouldSortBy = panel.stack && haveSortBy && haveSortOrder && panel.legend.alignAsTable;
  466. const sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  467. if (shouldSortBy) {
  468. return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
  469. } else {
  470. return _.sortBy(series, s => s.zindex);
  471. }
  472. }
  473. getFillGradient(amount: number) {
  474. if (!amount) {
  475. return null;
  476. }
  477. return {
  478. colors: [{ opacity: 0.0 }, { opacity: amount / 10 }],
  479. };
  480. }
  481. translateFillOption(fill: number) {
  482. if (this.panel.percentage && this.panel.stack) {
  483. return fill === 0 ? 0.001 : fill / 10;
  484. } else {
  485. return fill / 10;
  486. }
  487. }
  488. addTimeAxis(options: any) {
  489. const ticks = this.panelWidth / 100;
  490. const min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
  491. const max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
  492. options.xaxis = {
  493. timezone: this.dashboard.getTimezone(),
  494. show: this.panel.xaxis.show,
  495. mode: 'time',
  496. min: min,
  497. max: max,
  498. label: 'Datetime',
  499. ticks: ticks,
  500. timeformat: this.time_format(ticks, min, max),
  501. };
  502. }
  503. addXSeriesAxis(options: any) {
  504. const ticks = _.map(this.data, (series, index) => {
  505. return [index + 1, series.alias];
  506. });
  507. options.xaxis = {
  508. timezone: this.dashboard.getTimezone(),
  509. show: this.panel.xaxis.show,
  510. mode: null,
  511. min: 0,
  512. max: ticks.length + 1,
  513. label: 'Datetime',
  514. ticks: ticks,
  515. };
  516. }
  517. addXHistogramAxis(options: any, bucketSize: number) {
  518. let ticks: number | number[];
  519. let min: number | undefined;
  520. let max: number | undefined;
  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 | null, max: number | null) {
  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 };