rendering.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. import _ from 'lodash';
  2. import $ from 'jquery';
  3. import moment from 'moment';
  4. import * as d3 from 'd3';
  5. import kbn from 'app/core/utils/kbn';
  6. import { appEvents, contextSrv } from 'app/core/core';
  7. import * as ticksUtils from 'app/core/utils/ticks';
  8. import { HeatmapTooltip } from './heatmap_tooltip';
  9. import { mergeZeroBuckets } from './heatmap_data_converter';
  10. import { getColorScale, getOpacityScale } from './color_scale';
  11. let MIN_CARD_SIZE = 1,
  12. CARD_PADDING = 1,
  13. CARD_ROUND = 0,
  14. DATA_RANGE_WIDING_FACTOR = 1.2,
  15. DEFAULT_X_TICK_SIZE_PX = 100,
  16. DEFAULT_Y_TICK_SIZE_PX = 50,
  17. X_AXIS_TICK_PADDING = 10,
  18. Y_AXIS_TICK_PADDING = 5,
  19. MIN_SELECTION_WIDTH = 2;
  20. export default function rendering(scope, elem, attrs, ctrl) {
  21. return new Link(scope, elem, attrs, ctrl);
  22. }
  23. export class Link {
  24. width: number;
  25. height: number;
  26. yScale: any;
  27. xScale: any;
  28. chartWidth: number;
  29. chartHeight: number;
  30. chartTop: number;
  31. chartBottom: number;
  32. yAxisWidth: number;
  33. xAxisHeight: number;
  34. cardPadding: number;
  35. cardRound: number;
  36. cardWidth: number;
  37. cardHeight: number;
  38. colorScale: any;
  39. opacityScale: any;
  40. mouseUpHandler: any;
  41. data: any;
  42. panel: any;
  43. $heatmap: any;
  44. tooltip: HeatmapTooltip;
  45. heatmap: any;
  46. timeRange: any;
  47. selection: any;
  48. padding: any;
  49. margin: any;
  50. dataRangeWidingFactor: number;
  51. constructor(private scope, private elem, attrs, private ctrl) {
  52. // $heatmap is JQuery object, but heatmap is D3
  53. this.$heatmap = this.elem.find('.heatmap-panel');
  54. this.tooltip = new HeatmapTooltip(this.$heatmap, this.scope);
  55. this.selection = {
  56. active: false,
  57. x1: -1,
  58. x2: -1,
  59. };
  60. this.padding = { left: 0, right: 0, top: 0, bottom: 0 };
  61. this.margin = { left: 25, right: 15, top: 10, bottom: 20 };
  62. this.dataRangeWidingFactor = DATA_RANGE_WIDING_FACTOR;
  63. this.ctrl.events.on('render', this.onRender.bind(this));
  64. this.ctrl.tickValueFormatter = this.tickValueFormatter.bind(this);
  65. /////////////////////////////
  66. // Selection and crosshair //
  67. /////////////////////////////
  68. // Shared crosshair and tooltip
  69. appEvents.on('graph-hover', this.onGraphHover.bind(this), this.scope);
  70. appEvents.on('graph-hover-clear', this.onGraphHoverClear.bind(this), this.scope);
  71. // Register selection listeners
  72. this.$heatmap.on('mousedown', this.onMouseDown.bind(this));
  73. this.$heatmap.on('mousemove', this.onMouseMove.bind(this));
  74. this.$heatmap.on('mouseleave', this.onMouseLeave.bind(this));
  75. }
  76. onGraphHoverClear() {
  77. this.clearCrosshair();
  78. }
  79. onGraphHover(event) {
  80. this.drawSharedCrosshair(event.pos);
  81. }
  82. onRender() {
  83. this.render();
  84. this.ctrl.renderingCompleted();
  85. }
  86. setElementHeight() {
  87. try {
  88. var height = this.ctrl.height || this.panel.height || this.ctrl.row.height;
  89. if (_.isString(height)) {
  90. height = parseInt(height.replace('px', ''), 10);
  91. }
  92. height -= this.panel.legend.show ? 28 : 11; // bottom padding and space for legend
  93. this.$heatmap.css('height', height + 'px');
  94. return true;
  95. } catch (e) {
  96. // IE throws errors sometimes
  97. return false;
  98. }
  99. }
  100. getYAxisWidth(elem) {
  101. let axis_text = elem.selectAll('.axis-y text').nodes();
  102. let max_text_width = _.max(
  103. _.map(axis_text, text => {
  104. // Use SVG getBBox method
  105. return text.getBBox().width;
  106. })
  107. );
  108. return max_text_width;
  109. }
  110. getXAxisHeight(elem) {
  111. let axis_line = elem.select('.axis-x line');
  112. if (!axis_line.empty()) {
  113. let axis_line_position = parseFloat(elem.select('.axis-x line').attr('y2'));
  114. let canvas_width = parseFloat(elem.attr('height'));
  115. return canvas_width - axis_line_position;
  116. } else {
  117. // Default height
  118. return 30;
  119. }
  120. }
  121. addXAxis() {
  122. this.scope.xScale = this.xScale = d3
  123. .scaleTime()
  124. .domain([this.timeRange.from, this.timeRange.to])
  125. .range([0, this.chartWidth]);
  126. let ticks = this.chartWidth / DEFAULT_X_TICK_SIZE_PX;
  127. let grafanaTimeFormatter = ticksUtils.grafanaTimeFormat(ticks, this.timeRange.from, this.timeRange.to);
  128. let timeFormat;
  129. let dashboardTimeZone = this.ctrl.dashboard.getTimezone();
  130. if (dashboardTimeZone === 'utc') {
  131. timeFormat = d3.utcFormat(grafanaTimeFormatter);
  132. } else {
  133. timeFormat = d3.timeFormat(grafanaTimeFormatter);
  134. }
  135. console.log(ticks);
  136. let xAxis = d3
  137. .axisBottom(this.xScale)
  138. .ticks(ticks)
  139. .tickFormat(timeFormat)
  140. .tickPadding(X_AXIS_TICK_PADDING)
  141. .tickSize(this.chartHeight);
  142. let posY = this.margin.top;
  143. let posX = this.yAxisWidth;
  144. this.heatmap
  145. .append('g')
  146. .attr('class', 'axis axis-x')
  147. .attr('transform', 'translate(' + posX + ',' + posY + ')')
  148. .call(xAxis);
  149. // Remove horizontal line in the top of axis labels (called domain in d3)
  150. this.heatmap
  151. .select('.axis-x')
  152. .select('.domain')
  153. .remove();
  154. }
  155. addYAxis() {
  156. let ticks = Math.ceil(this.chartHeight / DEFAULT_Y_TICK_SIZE_PX);
  157. let tick_interval = ticksUtils.tickStep(this.data.heatmapStats.min, this.data.heatmapStats.max, ticks);
  158. let { y_min, y_max } = this.wideYAxisRange(this.data.heatmapStats.min, this.data.heatmapStats.max, tick_interval);
  159. // Rewrite min and max if it have been set explicitly
  160. y_min = this.panel.yAxis.min !== null ? this.panel.yAxis.min : y_min;
  161. y_max = this.panel.yAxis.max !== null ? this.panel.yAxis.max : y_max;
  162. // Adjust ticks after Y range widening
  163. tick_interval = ticksUtils.tickStep(y_min, y_max, ticks);
  164. ticks = Math.ceil((y_max - y_min) / tick_interval);
  165. let decimalsAuto = ticksUtils.getPrecision(tick_interval);
  166. let decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals;
  167. // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
  168. let flot_tick_size = ticksUtils.getFlotTickSize(y_min, y_max, ticks, decimalsAuto);
  169. let scaledDecimals = ticksUtils.getScaledDecimals(decimals, flot_tick_size);
  170. this.ctrl.decimals = decimals;
  171. this.ctrl.scaledDecimals = scaledDecimals;
  172. // Set default Y min and max if no data
  173. if (_.isEmpty(this.data.buckets)) {
  174. y_max = 1;
  175. y_min = -1;
  176. ticks = 3;
  177. decimals = 1;
  178. }
  179. this.data.yAxis = {
  180. min: y_min,
  181. max: y_max,
  182. ticks: ticks,
  183. };
  184. this.scope.yScale = this.yScale = d3
  185. .scaleLinear()
  186. .domain([y_min, y_max])
  187. .range([this.chartHeight, 0]);
  188. let yAxis = d3
  189. .axisLeft(this.yScale)
  190. .ticks(ticks)
  191. .tickFormat(this.tickValueFormatter(decimals, scaledDecimals))
  192. .tickSizeInner(0 - this.width)
  193. .tickSizeOuter(0)
  194. .tickPadding(Y_AXIS_TICK_PADDING);
  195. this.heatmap
  196. .append('g')
  197. .attr('class', 'axis axis-y')
  198. .call(yAxis);
  199. // Calculate Y axis width first, then move axis into visible area
  200. let posY = this.margin.top;
  201. let posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  202. this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
  203. // Remove vertical line in the right of axis labels (called domain in d3)
  204. this.heatmap
  205. .select('.axis-y')
  206. .select('.domain')
  207. .remove();
  208. }
  209. // Wide Y values range and anjust to bucket size
  210. wideYAxisRange(min, max, tickInterval) {
  211. let y_widing = (max * (this.dataRangeWidingFactor - 1) - min * (this.dataRangeWidingFactor - 1)) / 2;
  212. let y_min, y_max;
  213. if (tickInterval === 0) {
  214. y_max = max * this.dataRangeWidingFactor;
  215. y_min = min - min * (this.dataRangeWidingFactor - 1);
  216. tickInterval = (y_max - y_min) / 2;
  217. } else {
  218. y_max = Math.ceil((max + y_widing) / tickInterval) * tickInterval;
  219. y_min = Math.floor((min - y_widing) / tickInterval) * tickInterval;
  220. }
  221. // Don't wide axis below 0 if all values are positive
  222. if (min >= 0 && y_min < 0) {
  223. y_min = 0;
  224. }
  225. return { y_min, y_max };
  226. }
  227. addLogYAxis() {
  228. let log_base = this.panel.yAxis.logBase;
  229. let { y_min, y_max } = this.adjustLogRange(this.data.heatmapStats.minLog, this.data.heatmapStats.max, log_base);
  230. y_min =
  231. this.panel.yAxis.min && this.panel.yAxis.min !== '0' ? this.adjustLogMin(this.panel.yAxis.min, log_base) : y_min;
  232. y_max = this.panel.yAxis.max !== null ? this.adjustLogMax(this.panel.yAxis.max, log_base) : y_max;
  233. // Set default Y min and max if no data
  234. if (_.isEmpty(this.data.buckets)) {
  235. y_max = Math.pow(log_base, 2);
  236. y_min = 1;
  237. }
  238. this.scope.yScale = this.yScale = d3
  239. .scaleLog()
  240. .base(this.panel.yAxis.logBase)
  241. .domain([y_min, y_max])
  242. .range([this.chartHeight, 0]);
  243. let domain = this.yScale.domain();
  244. let tick_values = this.logScaleTickValues(domain, log_base);
  245. let decimalsAuto = ticksUtils.getPrecision(y_min);
  246. let decimals = this.panel.yAxis.decimals || decimalsAuto;
  247. // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
  248. let flot_tick_size = ticksUtils.getFlotTickSize(y_min, y_max, tick_values.length, decimalsAuto);
  249. let scaledDecimals = ticksUtils.getScaledDecimals(decimals, flot_tick_size);
  250. this.ctrl.decimals = decimals;
  251. this.ctrl.scaledDecimals = scaledDecimals;
  252. this.data.yAxis = {
  253. min: y_min,
  254. max: y_max,
  255. ticks: tick_values.length,
  256. };
  257. let yAxis = d3
  258. .axisLeft(this.yScale)
  259. .tickValues(tick_values)
  260. .tickFormat(this.tickValueFormatter(decimals, scaledDecimals))
  261. .tickSizeInner(0 - this.width)
  262. .tickSizeOuter(0)
  263. .tickPadding(Y_AXIS_TICK_PADDING);
  264. this.heatmap
  265. .append('g')
  266. .attr('class', 'axis axis-y')
  267. .call(yAxis);
  268. // Calculate Y axis width first, then move axis into visible area
  269. let posY = this.margin.top;
  270. let posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  271. this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
  272. // Set first tick as pseudo 0
  273. if (y_min < 1) {
  274. this.heatmap
  275. .select('.axis-y')
  276. .select('.tick text')
  277. .text('0');
  278. }
  279. // Remove vertical line in the right of axis labels (called domain in d3)
  280. this.heatmap
  281. .select('.axis-y')
  282. .select('.domain')
  283. .remove();
  284. }
  285. addYAxisFromBuckets() {
  286. const tsBuckets = this.data.tsBuckets;
  287. this.scope.yScale = this.yScale = d3
  288. .scaleLinear()
  289. .domain([0, tsBuckets.length - 1])
  290. .range([this.chartHeight, 0]);
  291. const tick_values = _.map(tsBuckets, (b, i) => i);
  292. const decimalsAuto = _.max(_.map(tsBuckets, ticksUtils.getStringPrecision));
  293. const decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals;
  294. this.ctrl.decimals = decimals;
  295. let tickValueFormatter = this.tickValueFormatter.bind(this);
  296. function tickFormatter(valIndex) {
  297. let valueFormatted = tsBuckets[valIndex];
  298. if (!_.isNaN(_.toNumber(valueFormatted)) && valueFormatted !== '') {
  299. // Try to format numeric tick labels
  300. valueFormatted = tickValueFormatter(decimals)(_.toNumber(valueFormatted));
  301. }
  302. return valueFormatted;
  303. }
  304. const tsBucketsFormatted = _.map(tsBuckets, (v, i) => tickFormatter(i));
  305. this.data.tsBucketsFormatted = tsBucketsFormatted;
  306. let yAxis = d3
  307. .axisLeft(this.yScale)
  308. .tickValues(tick_values)
  309. .tickFormat(tickFormatter)
  310. .tickSizeInner(0 - this.width)
  311. .tickSizeOuter(0)
  312. .tickPadding(Y_AXIS_TICK_PADDING);
  313. this.heatmap
  314. .append('g')
  315. .attr('class', 'axis axis-y')
  316. .call(yAxis);
  317. // Calculate Y axis width first, then move axis into visible area
  318. const posY = this.margin.top;
  319. const posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  320. this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
  321. // Remove vertical line in the right of axis labels (called domain in d3)
  322. this.heatmap
  323. .select('.axis-y')
  324. .select('.domain')
  325. .remove();
  326. }
  327. // Adjust data range to log base
  328. adjustLogRange(min, max, logBase) {
  329. let y_min, y_max;
  330. y_min = this.data.heatmapStats.minLog;
  331. if (this.data.heatmapStats.minLog > 1 || !this.data.heatmapStats.minLog) {
  332. y_min = 1;
  333. } else {
  334. y_min = this.adjustLogMin(this.data.heatmapStats.minLog, logBase);
  335. }
  336. // Adjust max Y value to log base
  337. y_max = this.adjustLogMax(this.data.heatmapStats.max, logBase);
  338. return { y_min, y_max };
  339. }
  340. adjustLogMax(max, base) {
  341. return Math.pow(base, Math.ceil(ticksUtils.logp(max, base)));
  342. }
  343. adjustLogMin(min, base) {
  344. return Math.pow(base, Math.floor(ticksUtils.logp(min, base)));
  345. }
  346. logScaleTickValues(domain, base) {
  347. let domainMin = domain[0];
  348. let domainMax = domain[1];
  349. let tickValues = [];
  350. if (domainMin < 1) {
  351. let under_one_ticks = Math.floor(ticksUtils.logp(domainMin, base));
  352. for (let i = under_one_ticks; i < 0; i++) {
  353. let tick_value = Math.pow(base, i);
  354. tickValues.push(tick_value);
  355. }
  356. }
  357. let ticks = Math.ceil(ticksUtils.logp(domainMax, base));
  358. for (let i = 0; i <= ticks; i++) {
  359. let tick_value = Math.pow(base, i);
  360. tickValues.push(tick_value);
  361. }
  362. return tickValues;
  363. }
  364. tickValueFormatter(decimals, scaledDecimals = null) {
  365. let format = this.panel.yAxis.format;
  366. return function(value) {
  367. try {
  368. return format !== 'none' ? kbn.valueFormats[format](value, decimals, scaledDecimals) : value;
  369. } catch (err) {
  370. console.error(err.message || err);
  371. return value;
  372. }
  373. };
  374. }
  375. fixYAxisTickSize() {
  376. this.heatmap
  377. .select('.axis-y')
  378. .selectAll('.tick line')
  379. .attr('x2', this.chartWidth);
  380. }
  381. addAxes() {
  382. this.chartHeight = this.height - this.margin.top - this.margin.bottom;
  383. this.chartTop = this.margin.top;
  384. this.chartBottom = this.chartTop + this.chartHeight;
  385. if (this.panel.dataFormat === 'tsbuckets') {
  386. this.addYAxisFromBuckets();
  387. } else {
  388. if (this.panel.yAxis.logBase === 1) {
  389. this.addYAxis();
  390. } else {
  391. this.addLogYAxis();
  392. }
  393. }
  394. this.yAxisWidth = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  395. this.chartWidth = this.width - this.yAxisWidth - this.margin.right;
  396. this.fixYAxisTickSize();
  397. this.addXAxis();
  398. this.xAxisHeight = this.getXAxisHeight(this.heatmap);
  399. if (!this.panel.yAxis.show) {
  400. this.heatmap
  401. .select('.axis-y')
  402. .selectAll('line')
  403. .style('opacity', 0);
  404. }
  405. if (!this.panel.xAxis.show) {
  406. this.heatmap
  407. .select('.axis-x')
  408. .selectAll('line')
  409. .style('opacity', 0);
  410. }
  411. }
  412. addHeatmapCanvas() {
  413. let heatmap_elem = this.$heatmap[0];
  414. this.width = Math.floor(this.$heatmap.width()) - this.padding.right;
  415. this.height = Math.floor(this.$heatmap.height()) - this.padding.bottom;
  416. this.cardPadding = this.panel.cards.cardPadding !== null ? this.panel.cards.cardPadding : CARD_PADDING;
  417. this.cardRound = this.panel.cards.cardRound !== null ? this.panel.cards.cardRound : CARD_ROUND;
  418. if (this.heatmap) {
  419. this.heatmap.remove();
  420. }
  421. this.heatmap = d3
  422. .select(heatmap_elem)
  423. .append('svg')
  424. .attr('width', this.width)
  425. .attr('height', this.height);
  426. }
  427. addHeatmap() {
  428. this.addHeatmapCanvas();
  429. this.addAxes();
  430. if (this.panel.yAxis.logBase !== 1 && this.panel.dataFormat !== 'tsbuckets') {
  431. let log_base = this.panel.yAxis.logBase;
  432. let domain = this.yScale.domain();
  433. let tick_values = this.logScaleTickValues(domain, log_base);
  434. this.data.buckets = mergeZeroBuckets(this.data.buckets, _.min(tick_values));
  435. }
  436. let cardsData = this.data.cards;
  437. let maxValueAuto = this.data.cardStats.max;
  438. let maxValue = this.panel.color.max || maxValueAuto;
  439. let minValue = this.panel.color.min || 0;
  440. let colorScheme = _.find(this.ctrl.colorSchemes, {
  441. value: this.panel.color.colorScheme,
  442. });
  443. this.colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, maxValue, minValue);
  444. this.opacityScale = getOpacityScale(this.panel.color, maxValue);
  445. this.setCardSize();
  446. let cards = this.heatmap.selectAll('.heatmap-card').data(cardsData);
  447. cards.append('title');
  448. cards = cards
  449. .enter()
  450. .append('rect')
  451. .attr('x', this.getCardX.bind(this))
  452. .attr('width', this.getCardWidth.bind(this))
  453. .attr('y', this.getCardY.bind(this))
  454. .attr('height', this.getCardHeight.bind(this))
  455. .attr('rx', this.cardRound)
  456. .attr('ry', this.cardRound)
  457. .attr('class', 'bordered heatmap-card')
  458. .style('fill', this.getCardColor.bind(this))
  459. .style('stroke', this.getCardColor.bind(this))
  460. .style('stroke-width', 0)
  461. .style('opacity', this.getCardOpacity.bind(this));
  462. let $cards = this.$heatmap.find('.heatmap-card');
  463. console.log($cards);
  464. $cards
  465. .on('mouseenter', event => {
  466. this.tooltip.mouseOverBucket = true;
  467. this.highlightCard(event);
  468. })
  469. .on('mouseleave', event => {
  470. this.tooltip.mouseOverBucket = false;
  471. this.resetCardHighLight(event);
  472. });
  473. }
  474. highlightCard(event) {
  475. let color = d3.select(event.target).style('fill');
  476. let highlightColor = d3.color(color).darker(2);
  477. let strokeColor = d3.color(color).brighter(4);
  478. let current_card = d3.select(event.target);
  479. this.tooltip.originalFillColor = color;
  480. current_card
  481. .style('fill', highlightColor.toString())
  482. .style('stroke', strokeColor.toString())
  483. .style('stroke-width', 1);
  484. }
  485. resetCardHighLight(event) {
  486. d3
  487. .select(event.target)
  488. .style('fill', this.tooltip.originalFillColor)
  489. .style('stroke', this.tooltip.originalFillColor)
  490. .style('stroke-width', 0);
  491. }
  492. setCardSize() {
  493. let xGridSize = Math.floor(this.xScale(this.data.xBucketSize) - this.xScale(0));
  494. let yGridSize = Math.floor(this.yScale(this.yScale.invert(0) - this.data.yBucketSize));
  495. if (this.panel.yAxis.logBase !== 1) {
  496. let base = this.panel.yAxis.logBase;
  497. let splitFactor = this.data.yBucketSize || 1;
  498. yGridSize = Math.floor((this.yScale(1) - this.yScale(base)) / splitFactor);
  499. }
  500. this.cardWidth = xGridSize - this.cardPadding * 2;
  501. this.cardHeight = yGridSize ? yGridSize - this.cardPadding * 2 : 0;
  502. }
  503. getCardX(d) {
  504. let x;
  505. if (this.xScale(d.x) < 0) {
  506. // Cut card left to prevent overlay
  507. x = this.yAxisWidth + this.cardPadding;
  508. } else {
  509. x = this.xScale(d.x) + this.yAxisWidth + this.cardPadding;
  510. }
  511. return x;
  512. }
  513. getCardWidth(d) {
  514. let w;
  515. if (this.xScale(d.x) < 0) {
  516. // Cut card left to prevent overlay
  517. let cutted_width = this.xScale(d.x) + this.cardWidth;
  518. w = cutted_width > 0 ? cutted_width : 0;
  519. } else if (this.xScale(d.x) + this.cardWidth > this.chartWidth) {
  520. // Cut card right to prevent overlay
  521. w = this.chartWidth - this.xScale(d.x) - this.cardPadding;
  522. } else {
  523. w = this.cardWidth;
  524. }
  525. // Card width should be MIN_CARD_SIZE at least
  526. w = Math.max(w, MIN_CARD_SIZE);
  527. return w;
  528. }
  529. getCardY(d) {
  530. let y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding;
  531. if (this.panel.yAxis.logBase !== 1 && d.y === 0) {
  532. y = this.chartBottom - this.cardHeight - this.cardPadding;
  533. } else {
  534. if (y < this.chartTop) {
  535. y = this.chartTop;
  536. }
  537. }
  538. return y;
  539. }
  540. getCardHeight(d) {
  541. let y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding;
  542. let h = this.cardHeight;
  543. if (this.panel.yAxis.logBase !== 1 && d.y === 0) {
  544. return this.cardHeight;
  545. }
  546. // Cut card height to prevent overlay
  547. if (y < this.chartTop) {
  548. h = this.yScale(d.y) - this.cardPadding;
  549. } else if (this.yScale(d.y) > this.chartBottom) {
  550. h = this.chartBottom - y;
  551. } else if (y + this.cardHeight > this.chartBottom) {
  552. h = this.chartBottom - y;
  553. }
  554. // Height can't be more than chart height
  555. h = Math.min(h, this.chartHeight);
  556. // Card height should be MIN_CARD_SIZE at least
  557. h = Math.max(h, MIN_CARD_SIZE);
  558. return h;
  559. }
  560. getCardColor(d) {
  561. if (this.panel.color.mode === 'opacity') {
  562. return this.panel.color.cardColor;
  563. } else {
  564. return this.colorScale(d.count);
  565. }
  566. }
  567. getCardOpacity(d) {
  568. if (this.panel.color.mode === 'opacity') {
  569. return this.opacityScale(d.count);
  570. } else {
  571. return 1;
  572. }
  573. }
  574. onMouseDown(event) {
  575. this.selection.active = true;
  576. this.selection.x1 = event.offsetX;
  577. this.mouseUpHandler = () => {
  578. this.onMouseUp();
  579. };
  580. $(document).one('mouseup', this.mouseUpHandler.bind(this));
  581. }
  582. onMouseUp() {
  583. $(document).unbind('mouseup', this.mouseUpHandler.bind(this));
  584. this.mouseUpHandler = null;
  585. this.selection.active = false;
  586. let selectionRange = Math.abs(this.selection.x2 - this.selection.x1);
  587. if (this.selection.x2 >= 0 && selectionRange > MIN_SELECTION_WIDTH) {
  588. let timeFrom = this.xScale.invert(Math.min(this.selection.x1, this.selection.x2) - this.yAxisWidth);
  589. let timeTo = this.xScale.invert(Math.max(this.selection.x1, this.selection.x2) - this.yAxisWidth);
  590. this.ctrl.timeSrv.setTime({
  591. from: moment.utc(timeFrom),
  592. to: moment.utc(timeTo),
  593. });
  594. }
  595. this.clearSelection();
  596. }
  597. onMouseLeave() {
  598. appEvents.emit('graph-hover-clear');
  599. this.clearCrosshair();
  600. }
  601. onMouseMove(event) {
  602. if (!this.heatmap) {
  603. return;
  604. }
  605. if (this.selection.active) {
  606. // Clear crosshair and tooltip
  607. this.clearCrosshair();
  608. this.tooltip.destroy();
  609. this.selection.x2 = this.limitSelection(event.offsetX);
  610. this.drawSelection(this.selection.x1, this.selection.x2);
  611. } else {
  612. this.emitGraphHoverEvent(event);
  613. this.drawCrosshair(event.offsetX);
  614. this.tooltip.show(event, this.data);
  615. }
  616. }
  617. emitGraphHoverEvent(event) {
  618. let x = this.xScale.invert(event.offsetX - this.yAxisWidth).valueOf();
  619. let y = this.yScale.invert(event.offsetY);
  620. let pos = {
  621. pageX: event.pageX,
  622. pageY: event.pageY,
  623. x: x,
  624. x1: x,
  625. y: y,
  626. y1: y,
  627. panelRelY: null,
  628. };
  629. // Set minimum offset to prevent showing legend from another panel
  630. pos.panelRelY = Math.max(event.offsetY / this.height, 0.001);
  631. // broadcast to other graph panels that we are hovering
  632. appEvents.emit('graph-hover', { pos: pos, panel: this.panel });
  633. }
  634. limitSelection(x2) {
  635. x2 = Math.max(x2, this.yAxisWidth);
  636. x2 = Math.min(x2, this.chartWidth + this.yAxisWidth);
  637. return x2;
  638. }
  639. drawSelection(posX1, posX2) {
  640. if (this.heatmap) {
  641. this.heatmap.selectAll('.heatmap-selection').remove();
  642. let selectionX = Math.min(posX1, posX2);
  643. let selectionWidth = Math.abs(posX1 - posX2);
  644. if (selectionWidth > MIN_SELECTION_WIDTH) {
  645. this.heatmap
  646. .append('rect')
  647. .attr('class', 'heatmap-selection')
  648. .attr('x', selectionX)
  649. .attr('width', selectionWidth)
  650. .attr('y', this.chartTop)
  651. .attr('height', this.chartHeight);
  652. }
  653. }
  654. }
  655. clearSelection() {
  656. this.selection.x1 = -1;
  657. this.selection.x2 = -1;
  658. if (this.heatmap) {
  659. this.heatmap.selectAll('.heatmap-selection').remove();
  660. }
  661. }
  662. drawCrosshair(position) {
  663. if (this.heatmap) {
  664. this.heatmap.selectAll('.heatmap-crosshair').remove();
  665. let posX = position;
  666. posX = Math.max(posX, this.yAxisWidth);
  667. posX = Math.min(posX, this.chartWidth + this.yAxisWidth);
  668. this.heatmap
  669. .append('g')
  670. .attr('class', 'heatmap-crosshair')
  671. .attr('transform', 'translate(' + posX + ',0)')
  672. .append('line')
  673. .attr('x1', 1)
  674. .attr('y1', this.chartTop)
  675. .attr('x2', 1)
  676. .attr('y2', this.chartBottom)
  677. .attr('stroke-width', 1);
  678. }
  679. }
  680. drawSharedCrosshair(pos) {
  681. if (this.heatmap && this.ctrl.dashboard.graphTooltip !== 0) {
  682. let posX = this.xScale(pos.x) + this.yAxisWidth;
  683. this.drawCrosshair(posX);
  684. }
  685. }
  686. clearCrosshair() {
  687. if (this.heatmap) {
  688. this.heatmap.selectAll('.heatmap-crosshair').remove();
  689. }
  690. }
  691. render() {
  692. this.data = this.ctrl.data;
  693. this.panel = this.ctrl.panel;
  694. this.timeRange = this.ctrl.range;
  695. if (!this.setElementHeight() || !this.data) {
  696. return;
  697. }
  698. // Draw default axes and return if no data
  699. if (_.isEmpty(this.data.buckets)) {
  700. this.addHeatmapCanvas();
  701. this.addAxes();
  702. return;
  703. }
  704. this.addHeatmap();
  705. this.scope.yAxisWidth = this.yAxisWidth;
  706. this.scope.xAxisHeight = this.xAxisHeight;
  707. this.scope.chartHeight = this.chartHeight;
  708. this.scope.chartWidth = this.chartWidth;
  709. this.scope.chartTop = this.chartTop;
  710. }
  711. }