graph.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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, DataLinkBuiltInVars } 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(
  174. link,
  175. {
  176. ...this.panel.scopedVars,
  177. [DataLinkBuiltInVars.seriesName]: { value: item.series.alias, text: item.series.alias },
  178. [DataLinkBuiltInVars.valueTime]: { value: item.datapoint[0], text: item.datapoint[0] },
  179. },
  180. item
  181. );
  182. return {
  183. label: linkUiModel.title,
  184. url: linkUiModel.href,
  185. target: linkUiModel.target,
  186. icon: `fa ${linkUiModel.target === '_self' ? 'fa-link' : 'fa-external-link'}`,
  187. };
  188. }),
  189. ],
  190. },
  191. ]
  192. : items;
  193. };
  194. onPlotClick(event: JQueryEventObject, pos: any, item: any) {
  195. const scrollContextElement = this.elem.closest('.view') ? this.elem.closest('.view').get()[0] : null;
  196. const contextMenuSourceItem = item;
  197. let contextMenuItems: ContextMenuItem[];
  198. if (this.panel.xaxis.mode !== 'time') {
  199. // Skip if panel in histogram or series mode
  200. return;
  201. }
  202. if ((pos.ctrlKey || pos.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
  203. // Skip if range selected (added in "plotselected" event handler)
  204. if (pos.x !== pos.x1) {
  205. return;
  206. }
  207. setTimeout(() => {
  208. this.eventManager.updateTime({ from: pos.x, to: null });
  209. }, 100);
  210. return;
  211. } else {
  212. this.tooltip.clear(this.plot);
  213. contextMenuItems = this.getContextMenuItems(pos, item) as ContextMenuItem[];
  214. this.scope.$apply(() => {
  215. // Setting nearest CustomScrollbar element as a scroll context for graph context menu
  216. this.contextMenu.setScrollContextElement(scrollContextElement);
  217. this.contextMenu.setSource(contextMenuSourceItem);
  218. this.contextMenu.setMenuItems(contextMenuItems);
  219. this.contextMenu.toggleMenu(pos);
  220. });
  221. }
  222. }
  223. shouldAbortRender() {
  224. if (!this.data) {
  225. return true;
  226. }
  227. if (this.panelWidth === 0) {
  228. return true;
  229. }
  230. return false;
  231. }
  232. drawHook(plot: any) {
  233. // add left axis labels
  234. if (this.panel.yaxes[0].label && this.panel.yaxes[0].show) {
  235. $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
  236. .text(this.panel.yaxes[0].label)
  237. .appendTo(this.elem);
  238. }
  239. // add right axis labels
  240. if (this.panel.yaxes[1].label && this.panel.yaxes[1].show) {
  241. $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
  242. .text(this.panel.yaxes[1].label)
  243. .appendTo(this.elem);
  244. }
  245. if (this.ctrl.dataWarning) {
  246. $(`<div class="datapoints-warning flot-temp-elem">${this.ctrl.dataWarning.title}</div>`).appendTo(this.elem);
  247. }
  248. this.thresholdManager.draw(plot);
  249. this.timeRegionManager.draw(plot);
  250. }
  251. processOffsetHook(plot: any, gridMargin: { left: number; right: number }) {
  252. const left = this.panel.yaxes[0];
  253. const right = this.panel.yaxes[1];
  254. if (left.show && left.label) {
  255. gridMargin.left = 20;
  256. }
  257. if (right.show && right.label) {
  258. gridMargin.right = 20;
  259. }
  260. // apply y-axis min/max options
  261. const yaxis = plot.getYAxes();
  262. for (let i = 0; i < yaxis.length; i++) {
  263. const axis: any = yaxis[i];
  264. const panelOptions = this.panel.yaxes[i];
  265. axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
  266. axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
  267. }
  268. }
  269. processRangeHook(plot: any) {
  270. const yAxes = plot.getYAxes();
  271. const align = this.panel.yaxis.align || false;
  272. if (yAxes.length > 1 && align === true) {
  273. const level = this.panel.yaxis.alignLevel || 0;
  274. alignYLevel(yAxes, parseFloat(level));
  275. }
  276. }
  277. // Series could have different timeSteps,
  278. // let's find the smallest one so that bars are correctly rendered.
  279. // In addition, only take series which are rendered as bars for this.
  280. getMinTimeStepOfSeries(data: any[]) {
  281. let min = Number.MAX_VALUE;
  282. for (let i = 0; i < data.length; i++) {
  283. if (!data[i].stats.timeStep) {
  284. continue;
  285. }
  286. if (this.panel.bars) {
  287. if (data[i].bars && data[i].bars.show === false) {
  288. continue;
  289. }
  290. } else {
  291. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  292. continue;
  293. }
  294. }
  295. if (data[i].stats.timeStep < min) {
  296. min = data[i].stats.timeStep;
  297. }
  298. }
  299. return min;
  300. }
  301. // Function for rendering panel
  302. renderPanel() {
  303. this.panelWidth = this.elem.width();
  304. if (this.shouldAbortRender()) {
  305. return;
  306. }
  307. // give space to alert editing
  308. this.thresholdManager.prepare(this.elem, this.data);
  309. // un-check dashes if lines are unchecked
  310. this.panel.dashes = this.panel.lines ? this.panel.dashes : false;
  311. // Populate element
  312. const options: any = this.buildFlotOptions(this.panel);
  313. this.prepareXAxis(options, this.panel);
  314. this.configureYAxisOptions(this.data, options);
  315. this.thresholdManager.addFlotOptions(options, this.panel);
  316. this.timeRegionManager.addFlotOptions(options, this.panel);
  317. this.eventManager.addFlotEvents(this.annotations, options);
  318. this.sortedSeries = this.sortSeries(this.data, this.panel);
  319. this.callPlot(options, true);
  320. }
  321. buildFlotPairs(data: any) {
  322. for (let i = 0; i < data.length; i++) {
  323. const series = data[i];
  324. series.data = series.getFlotPairs(series.nullPointMode || this.panel.nullPointMode);
  325. // if hidden remove points and disable stack
  326. if (this.ctrl.hiddenSeries[series.alias]) {
  327. series.data = [];
  328. series.stack = false;
  329. }
  330. }
  331. }
  332. prepareXAxis(options: any, panel: any) {
  333. switch (panel.xaxis.mode) {
  334. case 'series': {
  335. options.series.bars.barWidth = 0.7;
  336. options.series.bars.align = 'center';
  337. for (let i = 0; i < this.data.length; i++) {
  338. const series = this.data[i];
  339. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  340. }
  341. this.addXSeriesAxis(options);
  342. break;
  343. }
  344. case 'histogram': {
  345. let bucketSize: number;
  346. if (this.data.length) {
  347. let histMin = _.min(_.map(this.data, s => s.stats.min));
  348. let histMax = _.max(_.map(this.data, s => s.stats.max));
  349. const ticks = panel.xaxis.buckets || this.panelWidth / 50;
  350. if (panel.xaxis.min != null) {
  351. const isInvalidXaxisMin = tickStep(panel.xaxis.min, histMax, ticks) <= 0;
  352. histMin = isInvalidXaxisMin ? histMin : panel.xaxis.min;
  353. }
  354. if (panel.xaxis.max != null) {
  355. const isInvalidXaxisMax = tickStep(histMin, panel.xaxis.max, ticks) <= 0;
  356. histMax = isInvalidXaxisMax ? histMax : panel.xaxis.max;
  357. }
  358. bucketSize = tickStep(histMin, histMax, ticks);
  359. options.series.bars.barWidth = bucketSize * 0.8;
  360. this.data = convertToHistogramData(this.data, bucketSize, this.ctrl.hiddenSeries, histMin, histMax);
  361. } else {
  362. bucketSize = 0;
  363. }
  364. this.addXHistogramAxis(options, bucketSize);
  365. break;
  366. }
  367. case 'table': {
  368. options.series.bars.barWidth = 0.7;
  369. options.series.bars.align = 'center';
  370. this.addXTableAxis(options);
  371. break;
  372. }
  373. default: {
  374. options.series.bars.barWidth = this.getMinTimeStepOfSeries(this.data) / 1.5;
  375. this.addTimeAxis(options);
  376. break;
  377. }
  378. }
  379. }
  380. callPlot(options: any, incrementRenderCounter: boolean) {
  381. try {
  382. this.plot = $.plot(this.elem, this.sortedSeries, options);
  383. if (this.ctrl.renderError) {
  384. delete this.ctrl.error;
  385. delete this.ctrl.inspector;
  386. }
  387. } catch (e) {
  388. console.log('flotcharts error', e);
  389. this.ctrl.error = e.message || 'Render Error';
  390. this.ctrl.renderError = true;
  391. this.ctrl.inspector = { error: e };
  392. }
  393. if (incrementRenderCounter) {
  394. this.ctrl.renderingCompleted();
  395. }
  396. }
  397. buildFlotOptions(panel: any) {
  398. let gridColor = '#c8c8c8';
  399. if (config.bootData.user.lightTheme === true) {
  400. gridColor = '#a1a1a1';
  401. }
  402. const stack = panel.stack ? true : null;
  403. const options: any = {
  404. hooks: {
  405. draw: [this.drawHook.bind(this)],
  406. processOffset: [this.processOffsetHook.bind(this)],
  407. processRange: [this.processRangeHook.bind(this)],
  408. },
  409. legend: { show: false },
  410. series: {
  411. stackpercent: panel.stack ? panel.percentage : false,
  412. stack: panel.percentage ? null : stack,
  413. lines: {
  414. show: panel.lines,
  415. zero: false,
  416. fill: this.translateFillOption(panel.fill),
  417. fillColor: this.getFillGradient(panel.fillGradient),
  418. lineWidth: panel.dashes ? 0 : panel.linewidth,
  419. steps: panel.steppedLine,
  420. },
  421. dashes: {
  422. show: panel.dashes,
  423. lineWidth: panel.linewidth,
  424. dashLength: [panel.dashLength, panel.spaceLength],
  425. },
  426. bars: {
  427. show: panel.bars,
  428. fill: 1,
  429. barWidth: 1,
  430. zero: false,
  431. lineWidth: 0,
  432. },
  433. points: {
  434. show: panel.points,
  435. fill: 1,
  436. fillColor: false,
  437. radius: panel.points ? panel.pointradius : 2,
  438. },
  439. shadowSize: 0,
  440. },
  441. yaxes: [],
  442. xaxis: {},
  443. grid: {
  444. minBorderMargin: 0,
  445. markings: [],
  446. backgroundColor: null,
  447. borderWidth: 0,
  448. hoverable: true,
  449. clickable: true,
  450. color: gridColor,
  451. margin: { left: 0, right: 0 },
  452. labelMarginX: 0,
  453. mouseActiveRadius: 30,
  454. },
  455. selection: {
  456. mode: 'x',
  457. color: '#666',
  458. },
  459. crosshair: {
  460. mode: 'x',
  461. },
  462. };
  463. return options;
  464. }
  465. sortSeries(series: any, panel: any) {
  466. const sortBy = panel.legend.sort;
  467. const sortOrder = panel.legend.sortDesc;
  468. const haveSortBy = sortBy !== null && sortBy !== undefined && panel.legend[sortBy];
  469. const haveSortOrder = sortOrder !== null && sortOrder !== undefined;
  470. const shouldSortBy = panel.stack && haveSortBy && haveSortOrder && panel.legend.alignAsTable;
  471. const sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  472. if (shouldSortBy) {
  473. return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
  474. } else {
  475. return _.sortBy(series, s => s.zindex);
  476. }
  477. }
  478. getFillGradient(amount: number) {
  479. if (!amount) {
  480. return null;
  481. }
  482. return {
  483. colors: [{ opacity: 0.0 }, { opacity: amount / 10 }],
  484. };
  485. }
  486. translateFillOption(fill: number) {
  487. if (this.panel.percentage && this.panel.stack) {
  488. return fill === 0 ? 0.001 : fill / 10;
  489. } else {
  490. return fill / 10;
  491. }
  492. }
  493. addTimeAxis(options: any) {
  494. const ticks = this.panelWidth / 100;
  495. const min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
  496. const max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
  497. options.xaxis = {
  498. timezone: this.dashboard.getTimezone(),
  499. show: this.panel.xaxis.show,
  500. mode: 'time',
  501. min: min,
  502. max: max,
  503. label: 'Datetime',
  504. ticks: ticks,
  505. timeformat: this.time_format(ticks, min, max),
  506. };
  507. }
  508. addXSeriesAxis(options: any) {
  509. const ticks = _.map(this.data, (series, index) => {
  510. return [index + 1, series.alias];
  511. });
  512. options.xaxis = {
  513. timezone: this.dashboard.getTimezone(),
  514. show: this.panel.xaxis.show,
  515. mode: null,
  516. min: 0,
  517. max: ticks.length + 1,
  518. label: 'Datetime',
  519. ticks: ticks,
  520. };
  521. }
  522. addXHistogramAxis(options: any, bucketSize: number) {
  523. let ticks: number | number[];
  524. let min: number | undefined;
  525. let max: number | undefined;
  526. const defaultTicks = this.panelWidth / 50;
  527. if (this.data.length && bucketSize) {
  528. const tickValues = [];
  529. for (const d of this.data) {
  530. for (const point of d.data) {
  531. tickValues[point[0]] = true;
  532. }
  533. }
  534. ticks = Object.keys(tickValues).map(v => Number(v));
  535. min = _.min(ticks)!;
  536. max = _.max(ticks)!;
  537. // Adjust tick step
  538. let tickStep = bucketSize;
  539. let ticksNum = Math.floor((max - min) / tickStep);
  540. while (ticksNum > defaultTicks) {
  541. tickStep = tickStep * 2;
  542. ticksNum = Math.ceil((max - min) / tickStep);
  543. }
  544. // Expand ticks for pretty view
  545. min = Math.floor(min / tickStep) * tickStep;
  546. // 1.01 is 101% - ensure we have enough space for last bar
  547. max = Math.ceil((max * 1.01) / tickStep) * tickStep;
  548. ticks = [];
  549. for (let i = min; i <= max; i += tickStep) {
  550. ticks.push(i);
  551. }
  552. } else {
  553. // Set defaults if no data
  554. ticks = defaultTicks / 2;
  555. min = 0;
  556. max = 1;
  557. }
  558. options.xaxis = {
  559. timezone: this.dashboard.getTimezone(),
  560. show: this.panel.xaxis.show,
  561. mode: null,
  562. min: min,
  563. max: max,
  564. label: 'Histogram',
  565. ticks: ticks,
  566. };
  567. // Use 'short' format for histogram values
  568. this.configureAxisMode(options.xaxis, 'short');
  569. }
  570. addXTableAxis(options: any) {
  571. let ticks = _.map(this.data, (series, seriesIndex) => {
  572. return _.map(series.datapoints, (point, pointIndex) => {
  573. const tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  574. return [tickIndex + 1, point[1]];
  575. });
  576. });
  577. // @ts-ignore, potential bug? is this _.flattenDeep?
  578. ticks = _.flatten(ticks, true);
  579. options.xaxis = {
  580. timezone: this.dashboard.getTimezone(),
  581. show: this.panel.xaxis.show,
  582. mode: null,
  583. min: 0,
  584. max: ticks.length + 1,
  585. label: 'Datetime',
  586. ticks: ticks,
  587. };
  588. }
  589. configureYAxisOptions(data: any, options: any) {
  590. const defaults = {
  591. position: 'left',
  592. show: this.panel.yaxes[0].show,
  593. index: 1,
  594. logBase: this.panel.yaxes[0].logBase || 1,
  595. min: this.parseNumber(this.panel.yaxes[0].min),
  596. max: this.parseNumber(this.panel.yaxes[0].max),
  597. tickDecimals: this.panel.yaxes[0].decimals,
  598. };
  599. options.yaxes.push(defaults);
  600. if (_.find(data, { yaxis: 2 })) {
  601. const secondY = _.clone(defaults);
  602. secondY.index = 2;
  603. secondY.show = this.panel.yaxes[1].show;
  604. secondY.logBase = this.panel.yaxes[1].logBase || 1;
  605. secondY.position = 'right';
  606. secondY.min = this.parseNumber(this.panel.yaxes[1].min);
  607. secondY.max = this.parseNumber(this.panel.yaxes[1].max);
  608. secondY.tickDecimals = this.panel.yaxes[1].decimals;
  609. options.yaxes.push(secondY);
  610. this.applyLogScale(options.yaxes[1], data);
  611. this.configureAxisMode(
  612. options.yaxes[1],
  613. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[1].format
  614. );
  615. }
  616. this.applyLogScale(options.yaxes[0], data);
  617. this.configureAxisMode(
  618. options.yaxes[0],
  619. this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[0].format
  620. );
  621. }
  622. parseNumber(value: any) {
  623. if (value === null || typeof value === 'undefined') {
  624. return null;
  625. }
  626. return _.toNumber(value);
  627. }
  628. applyLogScale(axis: any, data: any) {
  629. if (axis.logBase === 1) {
  630. return;
  631. }
  632. const minSetToZero = axis.min === 0;
  633. if (axis.min < Number.MIN_VALUE) {
  634. axis.min = null;
  635. }
  636. if (axis.max < Number.MIN_VALUE) {
  637. axis.max = null;
  638. }
  639. let series, i;
  640. let max = axis.max,
  641. min = axis.min;
  642. for (i = 0; i < data.length; i++) {
  643. series = data[i];
  644. if (series.yaxis === axis.index) {
  645. if (!max || max < series.stats.max) {
  646. max = series.stats.max;
  647. }
  648. if (!min || min > series.stats.logmin) {
  649. min = series.stats.logmin;
  650. }
  651. }
  652. }
  653. axis.transform = (v: number) => {
  654. return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
  655. };
  656. axis.inverseTransform = (v: any) => {
  657. return Math.pow(axis.logBase, v);
  658. };
  659. if (!max && !min) {
  660. max = axis.inverseTransform(+2);
  661. min = axis.inverseTransform(-2);
  662. } else if (!max) {
  663. max = min * axis.inverseTransform(+4);
  664. } else if (!min) {
  665. min = max * axis.inverseTransform(-4);
  666. }
  667. if (axis.min) {
  668. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  669. } else {
  670. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  671. }
  672. if (axis.max) {
  673. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  674. } else {
  675. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  676. }
  677. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  678. return;
  679. }
  680. if (Number.isFinite(min) && Number.isFinite(max)) {
  681. if (minSetToZero) {
  682. axis.min = 0.1;
  683. min = 1;
  684. }
  685. axis.ticks = this.generateTicksForLogScaleYAxis(min, max, axis.logBase);
  686. if (minSetToZero) {
  687. axis.ticks.unshift(0.1);
  688. }
  689. if (axis.ticks[axis.ticks.length - 1] > axis.max) {
  690. axis.max = axis.ticks[axis.ticks.length - 1];
  691. }
  692. } else {
  693. axis.ticks = [1, 2];
  694. delete axis.min;
  695. delete axis.max;
  696. }
  697. }
  698. generateTicksForLogScaleYAxis(min: any, max: number, logBase: number) {
  699. let ticks = [];
  700. let nextTick;
  701. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  702. ticks.push(nextTick);
  703. }
  704. const maxNumTicks = Math.ceil(this.ctrl.height / 25);
  705. const numTicks = ticks.length;
  706. if (numTicks > maxNumTicks) {
  707. const factor = Math.ceil(numTicks / maxNumTicks) * logBase;
  708. ticks = [];
  709. for (nextTick = min; nextTick <= max * factor; nextTick *= factor) {
  710. ticks.push(nextTick);
  711. }
  712. }
  713. return ticks;
  714. }
  715. configureAxisMode(axis: { tickFormatter: (val: any, axis: any) => string }, format: string) {
  716. axis.tickFormatter = (val, axis) => {
  717. const formatter = getValueFormat(format);
  718. if (!formatter) {
  719. throw new Error(`Unit '${format}' is not supported`);
  720. }
  721. return formatter(val, axis.tickDecimals, axis.scaledDecimals);
  722. };
  723. }
  724. time_format(ticks: number, min: number | null, max: number | null) {
  725. if (min && max && ticks) {
  726. const range = max - min;
  727. const secPerTick = range / ticks / 1000;
  728. // Need have 10 millisecond margin on the day range
  729. // As sometimes last 24 hour dashboard evaluates to more than 86400000
  730. const oneDay = 86400010;
  731. const oneYear = 31536000000;
  732. if (secPerTick <= 45) {
  733. return '%H:%M:%S';
  734. }
  735. if (secPerTick <= 7200 || range <= oneDay) {
  736. return '%H:%M';
  737. }
  738. if (secPerTick <= 80000) {
  739. return '%m/%d %H:%M';
  740. }
  741. if (secPerTick <= 2419200 || range <= oneYear) {
  742. return '%m/%d';
  743. }
  744. return '%Y-%m';
  745. }
  746. return '%H:%M';
  747. }
  748. }
  749. /** @ngInject */
  750. function graphDirective(timeSrv: TimeSrv, popoverSrv: any, contextSrv: ContextSrv, linkSrv: LinkSrv) {
  751. return {
  752. restrict: 'A',
  753. template: '',
  754. link: (scope: any, elem: JQuery) => {
  755. return new GraphElement(scope, elem, timeSrv, linkSrv);
  756. },
  757. };
  758. }
  759. coreModule.directive('grafanaGraph', graphDirective);
  760. export { GraphElement, graphDirective };