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. const 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 HeatmapRenderer(scope, elem, attrs, ctrl);
  22. }
  23. export class HeatmapRenderer {
  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. let 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. const axisText = elem.selectAll('.axis-y text').nodes();
  102. const maxTextWidth = _.max(
  103. _.map(axisText, text => {
  104. // Use SVG getBBox method
  105. return text.getBBox().width;
  106. })
  107. );
  108. return maxTextWidth;
  109. }
  110. getXAxisHeight(elem) {
  111. const axisLine = elem.select('.axis-x line');
  112. if (!axisLine.empty()) {
  113. const axisLinePosition = parseFloat(elem.select('.axis-x line').attr('y2'));
  114. const canvasWidth = parseFloat(elem.attr('height'));
  115. return canvasWidth - axisLinePosition;
  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. const ticks = this.chartWidth / DEFAULT_X_TICK_SIZE_PX;
  127. const grafanaTimeFormatter = ticksUtils.grafanaTimeFormat(ticks, this.timeRange.from, this.timeRange.to);
  128. let timeFormat;
  129. const dashboardTimeZone = this.ctrl.dashboard.getTimezone();
  130. if (dashboardTimeZone === 'utc') {
  131. timeFormat = d3.utcFormat(grafanaTimeFormatter);
  132. } else {
  133. timeFormat = d3.timeFormat(grafanaTimeFormatter);
  134. }
  135. const xAxis = d3
  136. .axisBottom(this.xScale)
  137. .ticks(ticks)
  138. .tickFormat(timeFormat)
  139. .tickPadding(X_AXIS_TICK_PADDING)
  140. .tickSize(this.chartHeight);
  141. const posY = this.margin.top;
  142. const posX = this.yAxisWidth;
  143. this.heatmap
  144. .append('g')
  145. .attr('class', 'axis axis-x')
  146. .attr('transform', 'translate(' + posX + ',' + posY + ')')
  147. .call(xAxis);
  148. // Remove horizontal line in the top of axis labels (called domain in d3)
  149. this.heatmap
  150. .select('.axis-x')
  151. .select('.domain')
  152. .remove();
  153. }
  154. addYAxis() {
  155. let ticks = Math.ceil(this.chartHeight / DEFAULT_Y_TICK_SIZE_PX);
  156. let tickInterval = ticksUtils.tickStep(this.data.heatmapStats.min, this.data.heatmapStats.max, ticks);
  157. let { yMin, yMax } = this.wideYAxisRange(this.data.heatmapStats.min, this.data.heatmapStats.max, tickInterval);
  158. // Rewrite min and max if it have been set explicitly
  159. yMin = this.panel.yAxis.min !== null ? this.panel.yAxis.min : yMin;
  160. yMax = this.panel.yAxis.max !== null ? this.panel.yAxis.max : yMax;
  161. // Adjust ticks after Y range widening
  162. tickInterval = ticksUtils.tickStep(yMin, yMax, ticks);
  163. ticks = Math.ceil((yMax - yMin) / tickInterval);
  164. const decimalsAuto = ticksUtils.getPrecision(tickInterval);
  165. let decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals;
  166. // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
  167. const flotTickSize = ticksUtils.getFlotTickSize(yMin, yMax, ticks, decimalsAuto);
  168. const scaledDecimals = ticksUtils.getScaledDecimals(decimals, flotTickSize);
  169. this.ctrl.decimals = decimals;
  170. this.ctrl.scaledDecimals = scaledDecimals;
  171. // Set default Y min and max if no data
  172. if (_.isEmpty(this.data.buckets)) {
  173. yMax = 1;
  174. yMin = -1;
  175. ticks = 3;
  176. decimals = 1;
  177. }
  178. this.data.yAxis = {
  179. min: yMin,
  180. max: yMax,
  181. ticks: ticks,
  182. };
  183. this.scope.yScale = this.yScale = d3
  184. .scaleLinear()
  185. .domain([yMin, yMax])
  186. .range([this.chartHeight, 0]);
  187. const yAxis = d3
  188. .axisLeft(this.yScale)
  189. .ticks(ticks)
  190. .tickFormat(this.tickValueFormatter(decimals, scaledDecimals))
  191. .tickSizeInner(0 - this.width)
  192. .tickSizeOuter(0)
  193. .tickPadding(Y_AXIS_TICK_PADDING);
  194. this.heatmap
  195. .append('g')
  196. .attr('class', 'axis axis-y')
  197. .call(yAxis);
  198. // Calculate Y axis width first, then move axis into visible area
  199. const posY = this.margin.top;
  200. const posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  201. this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
  202. // Remove vertical line in the right of axis labels (called domain in d3)
  203. this.heatmap
  204. .select('.axis-y')
  205. .select('.domain')
  206. .remove();
  207. }
  208. // Wide Y values range and anjust to bucket size
  209. wideYAxisRange(min, max, tickInterval) {
  210. const yWiding = (max * (this.dataRangeWidingFactor - 1) - min * (this.dataRangeWidingFactor - 1)) / 2;
  211. let yMin, yMax;
  212. if (tickInterval === 0) {
  213. yMax = max * this.dataRangeWidingFactor;
  214. yMin = min - min * (this.dataRangeWidingFactor - 1);
  215. tickInterval = (yMax - yMin) / 2;
  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, yMax;
  329. yMin = this.data.heatmapStats.minLog;
  330. if (this.data.heatmapStats.minLog > 1 || !this.data.heatmapStats.minLog) {
  331. yMin = 1;
  332. } else {
  333. yMin = this.adjustLogMin(this.data.heatmapStats.minLog, logBase);
  334. }
  335. // Adjust max Y value to log base
  336. yMax = this.adjustLogMax(this.data.heatmapStats.max, logBase);
  337. return { yMin, yMax };
  338. }
  339. adjustLogMax(max, base) {
  340. return Math.pow(base, Math.ceil(ticksUtils.logp(max, base)));
  341. }
  342. adjustLogMin(min, base) {
  343. return Math.pow(base, Math.floor(ticksUtils.logp(min, base)));
  344. }
  345. logScaleTickValues(domain, base) {
  346. const domainMin = domain[0];
  347. const domainMax = domain[1];
  348. const tickValues = [];
  349. if (domainMin < 1) {
  350. const underOneTicks = Math.floor(ticksUtils.logp(domainMin, base));
  351. for (let i = underOneTicks; i < 0; i++) {
  352. const tickValue = Math.pow(base, i);
  353. tickValues.push(tickValue);
  354. }
  355. }
  356. const ticks = Math.ceil(ticksUtils.logp(domainMax, base));
  357. for (let i = 0; i <= ticks; i++) {
  358. const tickValue = Math.pow(base, i);
  359. tickValues.push(tickValue);
  360. }
  361. return tickValues;
  362. }
  363. tickValueFormatter(decimals, scaledDecimals = null) {
  364. const format = this.panel.yAxis.format;
  365. return value => {
  366. try {
  367. return format !== 'none' ? kbn.valueFormats[format](value, decimals, scaledDecimals) : value;
  368. } catch (err) {
  369. console.error(err.message || err);
  370. return value;
  371. }
  372. };
  373. }
  374. fixYAxisTickSize() {
  375. this.heatmap
  376. .select('.axis-y')
  377. .selectAll('.tick line')
  378. .attr('x2', this.chartWidth);
  379. }
  380. addAxes() {
  381. this.chartHeight = this.height - this.margin.top - this.margin.bottom;
  382. this.chartTop = this.margin.top;
  383. this.chartBottom = this.chartTop + this.chartHeight;
  384. if (this.panel.dataFormat === 'tsbuckets') {
  385. this.addYAxisFromBuckets();
  386. } else {
  387. if (this.panel.yAxis.logBase === 1) {
  388. this.addYAxis();
  389. } else {
  390. this.addLogYAxis();
  391. }
  392. }
  393. this.yAxisWidth = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  394. this.chartWidth = this.width - this.yAxisWidth - this.margin.right;
  395. this.fixYAxisTickSize();
  396. this.addXAxis();
  397. this.xAxisHeight = this.getXAxisHeight(this.heatmap);
  398. if (!this.panel.yAxis.show) {
  399. this.heatmap
  400. .select('.axis-y')
  401. .selectAll('line')
  402. .style('opacity', 0);
  403. }
  404. if (!this.panel.xAxis.show) {
  405. this.heatmap
  406. .select('.axis-x')
  407. .selectAll('line')
  408. .style('opacity', 0);
  409. }
  410. }
  411. addHeatmapCanvas() {
  412. const heatmapElem = this.$heatmap[0];
  413. this.width = Math.floor(this.$heatmap.width()) - this.padding.right;
  414. this.height = Math.floor(this.$heatmap.height()) - this.padding.bottom;
  415. this.cardPadding = this.panel.cards.cardPadding !== null ? this.panel.cards.cardPadding : CARD_PADDING;
  416. this.cardRound = this.panel.cards.cardRound !== null ? this.panel.cards.cardRound : CARD_ROUND;
  417. if (this.heatmap) {
  418. this.heatmap.remove();
  419. }
  420. this.heatmap = d3
  421. .select(heatmapElem)
  422. .append('svg')
  423. .attr('width', this.width)
  424. .attr('height', this.height);
  425. }
  426. addHeatmap() {
  427. this.addHeatmapCanvas();
  428. this.addAxes();
  429. if (this.panel.yAxis.logBase !== 1 && this.panel.dataFormat !== 'tsbuckets') {
  430. const logBase = this.panel.yAxis.logBase;
  431. const domain = this.yScale.domain();
  432. const tickValues = this.logScaleTickValues(domain, logBase);
  433. this.data.buckets = mergeZeroBuckets(this.data.buckets, _.min(tickValues));
  434. }
  435. const cardsData = this.data.cards;
  436. const maxValueAuto = this.data.cardStats.max;
  437. const maxValue = this.panel.color.max || maxValueAuto;
  438. const minValue = this.panel.color.min || 0;
  439. const colorScheme = _.find(this.ctrl.colorSchemes, {
  440. value: this.panel.color.colorScheme,
  441. });
  442. this.colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, maxValue, minValue);
  443. this.opacityScale = getOpacityScale(this.panel.color, maxValue);
  444. this.setCardSize();
  445. let cards = this.heatmap.selectAll('.heatmap-card').data(cardsData);
  446. cards.append('title');
  447. cards = cards
  448. .enter()
  449. .append('rect')
  450. .attr('x', this.getCardX.bind(this))
  451. .attr('width', this.getCardWidth.bind(this))
  452. .attr('y', this.getCardY.bind(this))
  453. .attr('height', this.getCardHeight.bind(this))
  454. .attr('rx', this.cardRound)
  455. .attr('ry', this.cardRound)
  456. .attr('class', 'bordered heatmap-card')
  457. .style('fill', this.getCardColor.bind(this))
  458. .style('stroke', this.getCardColor.bind(this))
  459. .style('stroke-width', 0)
  460. .style('opacity', this.getCardOpacity.bind(this));
  461. const $cards = this.$heatmap.find('.heatmap-card');
  462. $cards
  463. .on('mouseenter', event => {
  464. this.tooltip.mouseOverBucket = true;
  465. this.highlightCard(event);
  466. })
  467. .on('mouseleave', event => {
  468. this.tooltip.mouseOverBucket = false;
  469. this.resetCardHighLight(event);
  470. });
  471. }
  472. highlightCard(event) {
  473. const color = d3.select(event.target).style('fill');
  474. const highlightColor = d3.color(color).darker(2);
  475. const strokeColor = d3.color(color).brighter(4);
  476. const currentCard = d3.select(event.target);
  477. this.tooltip.originalFillColor = color;
  478. currentCard
  479. .style('fill', highlightColor.toString())
  480. .style('stroke', strokeColor.toString())
  481. .style('stroke-width', 1);
  482. }
  483. resetCardHighLight(event) {
  484. d3
  485. .select(event.target)
  486. .style('fill', this.tooltip.originalFillColor)
  487. .style('stroke', this.tooltip.originalFillColor)
  488. .style('stroke-width', 0);
  489. }
  490. setCardSize() {
  491. const xGridSize = Math.floor(this.xScale(this.data.xBucketSize) - this.xScale(0));
  492. let yGridSize = Math.floor(this.yScale(this.yScale.invert(0) - this.data.yBucketSize));
  493. if (this.panel.yAxis.logBase !== 1) {
  494. const base = this.panel.yAxis.logBase;
  495. const splitFactor = this.data.yBucketSize || 1;
  496. yGridSize = Math.floor((this.yScale(1) - this.yScale(base)) / splitFactor);
  497. }
  498. this.cardWidth = xGridSize - this.cardPadding * 2;
  499. this.cardHeight = yGridSize ? yGridSize - this.cardPadding * 2 : 0;
  500. }
  501. getCardX(d) {
  502. let x;
  503. if (this.xScale(d.x) < 0) {
  504. // Cut card left to prevent overlay
  505. x = this.yAxisWidth + this.cardPadding;
  506. } else {
  507. x = this.xScale(d.x) + this.yAxisWidth + this.cardPadding;
  508. }
  509. return x;
  510. }
  511. getCardWidth(d) {
  512. let w;
  513. if (this.xScale(d.x) < 0) {
  514. // Cut card left to prevent overlay
  515. const cuttedWidth = this.xScale(d.x) + this.cardWidth;
  516. w = cuttedWidth > 0 ? cuttedWidth : 0;
  517. } else if (this.xScale(d.x) + this.cardWidth > this.chartWidth) {
  518. // Cut card right to prevent overlay
  519. w = this.chartWidth - this.xScale(d.x) - this.cardPadding;
  520. } else {
  521. w = this.cardWidth;
  522. }
  523. // Card width should be MIN_CARD_SIZE at least
  524. w = Math.max(w, MIN_CARD_SIZE);
  525. return w;
  526. }
  527. getCardY(d) {
  528. let y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding;
  529. if (this.panel.yAxis.logBase !== 1 && d.y === 0) {
  530. y = this.chartBottom - this.cardHeight - this.cardPadding;
  531. } else {
  532. if (y < this.chartTop) {
  533. y = this.chartTop;
  534. }
  535. }
  536. return y;
  537. }
  538. getCardHeight(d) {
  539. const y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding;
  540. let h = this.cardHeight;
  541. if (this.panel.yAxis.logBase !== 1 && d.y === 0) {
  542. return this.cardHeight;
  543. }
  544. // Cut card height to prevent overlay
  545. if (y < this.chartTop) {
  546. h = this.yScale(d.y) - this.cardPadding;
  547. } else if (this.yScale(d.y) > this.chartBottom) {
  548. h = this.chartBottom - y;
  549. } else if (y + this.cardHeight > this.chartBottom) {
  550. h = this.chartBottom - y;
  551. }
  552. // Height can't be more than chart height
  553. h = Math.min(h, this.chartHeight);
  554. // Card height should be MIN_CARD_SIZE at least
  555. h = Math.max(h, MIN_CARD_SIZE);
  556. return h;
  557. }
  558. getCardColor(d) {
  559. if (this.panel.color.mode === 'opacity') {
  560. return this.panel.color.cardColor;
  561. } else {
  562. return this.colorScale(d.count);
  563. }
  564. }
  565. getCardOpacity(d) {
  566. if (this.panel.color.mode === 'opacity') {
  567. return this.opacityScale(d.count);
  568. } else {
  569. return 1;
  570. }
  571. }
  572. getEventOffset(event) {
  573. const elemOffset = this.$heatmap.offset();
  574. const x = Math.floor(event.clientX - elemOffset.left);
  575. const y = Math.floor(event.clientY - elemOffset.top);
  576. return { x, y };
  577. }
  578. onMouseDown(event) {
  579. const offset = this.getEventOffset(event);
  580. this.selection.active = true;
  581. this.selection.x1 = offset.x;
  582. this.mouseUpHandler = () => {
  583. this.onMouseUp();
  584. };
  585. $(document).one('mouseup', this.mouseUpHandler.bind(this));
  586. }
  587. onMouseUp() {
  588. $(document).unbind('mouseup', this.mouseUpHandler.bind(this));
  589. this.mouseUpHandler = null;
  590. this.selection.active = false;
  591. const selectionRange = Math.abs(this.selection.x2 - this.selection.x1);
  592. if (this.selection.x2 >= 0 && selectionRange > MIN_SELECTION_WIDTH) {
  593. const timeFrom = this.xScale.invert(Math.min(this.selection.x1, this.selection.x2) - this.yAxisWidth);
  594. const timeTo = this.xScale.invert(Math.max(this.selection.x1, this.selection.x2) - this.yAxisWidth);
  595. this.ctrl.timeSrv.setTime({
  596. from: moment.utc(timeFrom),
  597. to: moment.utc(timeTo),
  598. });
  599. }
  600. this.clearSelection();
  601. }
  602. onMouseLeave() {
  603. appEvents.emit('graph-hover-clear');
  604. this.clearCrosshair();
  605. }
  606. onMouseMove(event) {
  607. if (!this.heatmap) {
  608. return;
  609. }
  610. const offset = this.getEventOffset(event);
  611. if (this.selection.active) {
  612. // Clear crosshair and tooltip
  613. this.clearCrosshair();
  614. this.tooltip.destroy();
  615. this.selection.x2 = this.limitSelection(offset.x);
  616. this.drawSelection(this.selection.x1, this.selection.x2);
  617. } else {
  618. const pos = this.getEventPos(event, offset);
  619. this.drawCrosshair(offset.x);
  620. this.tooltip.show(pos, this.data);
  621. this.emitGraphHoverEvent(pos);
  622. }
  623. }
  624. getEventPos(event, offset) {
  625. const x = this.xScale.invert(offset.x - this.yAxisWidth).valueOf();
  626. const y = this.yScale.invert(offset.y - this.chartTop);
  627. const pos = {
  628. pageX: event.pageX,
  629. pageY: event.pageY,
  630. x: x,
  631. x1: x,
  632. y: y,
  633. y1: y,
  634. panelRelY: null,
  635. offset,
  636. };
  637. return pos;
  638. }
  639. emitGraphHoverEvent(pos) {
  640. // Set minimum offset to prevent showing legend from another panel
  641. pos.panelRelY = Math.max(pos.offset.y / this.height, 0.001);
  642. // broadcast to other graph panels that we are hovering
  643. appEvents.emit('graph-hover', { pos: pos, panel: this.panel });
  644. }
  645. limitSelection(x2) {
  646. x2 = Math.max(x2, this.yAxisWidth);
  647. x2 = Math.min(x2, this.chartWidth + this.yAxisWidth);
  648. return x2;
  649. }
  650. drawSelection(posX1, posX2) {
  651. if (this.heatmap) {
  652. this.heatmap.selectAll('.heatmap-selection').remove();
  653. const selectionX = Math.min(posX1, posX2);
  654. const selectionWidth = Math.abs(posX1 - posX2);
  655. if (selectionWidth > MIN_SELECTION_WIDTH) {
  656. this.heatmap
  657. .append('rect')
  658. .attr('class', 'heatmap-selection')
  659. .attr('x', selectionX)
  660. .attr('width', selectionWidth)
  661. .attr('y', this.chartTop)
  662. .attr('height', this.chartHeight);
  663. }
  664. }
  665. }
  666. clearSelection() {
  667. this.selection.x1 = -1;
  668. this.selection.x2 = -1;
  669. if (this.heatmap) {
  670. this.heatmap.selectAll('.heatmap-selection').remove();
  671. }
  672. }
  673. drawCrosshair(position) {
  674. if (this.heatmap) {
  675. this.heatmap.selectAll('.heatmap-crosshair').remove();
  676. let posX = position;
  677. posX = Math.max(posX, this.yAxisWidth);
  678. posX = Math.min(posX, this.chartWidth + this.yAxisWidth);
  679. this.heatmap
  680. .append('g')
  681. .attr('class', 'heatmap-crosshair')
  682. .attr('transform', 'translate(' + posX + ',0)')
  683. .append('line')
  684. .attr('x1', 1)
  685. .attr('y1', this.chartTop)
  686. .attr('x2', 1)
  687. .attr('y2', this.chartBottom)
  688. .attr('stroke-width', 1);
  689. }
  690. }
  691. drawSharedCrosshair(pos) {
  692. if (this.heatmap && this.ctrl.dashboard.graphTooltip !== 0) {
  693. const posX = this.xScale(pos.x) + this.yAxisWidth;
  694. this.drawCrosshair(posX);
  695. }
  696. }
  697. clearCrosshair() {
  698. if (this.heatmap) {
  699. this.heatmap.selectAll('.heatmap-crosshair').remove();
  700. }
  701. }
  702. render() {
  703. this.data = this.ctrl.data;
  704. this.panel = this.ctrl.panel;
  705. this.timeRange = this.ctrl.range;
  706. if (!this.setElementHeight() || !this.data) {
  707. return;
  708. }
  709. // Draw default axes and return if no data
  710. if (_.isEmpty(this.data.buckets)) {
  711. this.addHeatmapCanvas();
  712. this.addAxes();
  713. return;
  714. }
  715. this.addHeatmap();
  716. this.scope.yAxisWidth = this.yAxisWidth;
  717. this.scope.xAxisHeight = this.xAxisHeight;
  718. this.scope.chartHeight = this.chartHeight;
  719. this.scope.chartWidth = this.chartWidth;
  720. this.scope.chartTop = this.chartTop;
  721. }
  722. }