graph.ts 26 KB

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