rendering.ts 25 KB

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