graph.ts 26 KB

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