rendering.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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 { getColorFromHexRgbOrName } from '@grafana/ui/src/utils/colorsPalette';
  12. import { GrafanaTheme } from '@grafana/ui';
  13. const MIN_CARD_SIZE = 1,
  14. CARD_PADDING = 1,
  15. CARD_ROUND = 0,
  16. DATA_RANGE_WIDING_FACTOR = 1.2,
  17. DEFAULT_X_TICK_SIZE_PX = 100,
  18. DEFAULT_Y_TICK_SIZE_PX = 50,
  19. X_AXIS_TICK_PADDING = 10,
  20. Y_AXIS_TICK_PADDING = 5,
  21. MIN_SELECTION_WIDTH = 2;
  22. export default function rendering(scope, elem, attrs, ctrl) {
  23. return new HeatmapRenderer(scope, elem, attrs, ctrl);
  24. }
  25. export class HeatmapRenderer {
  26. width: number;
  27. height: number;
  28. yScale: any;
  29. xScale: any;
  30. chartWidth: number;
  31. chartHeight: number;
  32. chartTop: number;
  33. chartBottom: number;
  34. yAxisWidth: number;
  35. xAxisHeight: number;
  36. cardPadding: number;
  37. cardRound: number;
  38. cardWidth: number;
  39. cardHeight: number;
  40. colorScale: any;
  41. opacityScale: any;
  42. mouseUpHandler: any;
  43. data: any;
  44. panel: any;
  45. $heatmap: any;
  46. tooltip: HeatmapTooltip;
  47. heatmap: any;
  48. timeRange: any;
  49. selection: any;
  50. padding: any;
  51. margin: any;
  52. dataRangeWidingFactor: number;
  53. constructor(private scope, private elem, attrs, private ctrl) {
  54. // $heatmap is JQuery object, but heatmap is D3
  55. this.$heatmap = this.elem.find('.heatmap-panel');
  56. this.tooltip = new HeatmapTooltip(this.$heatmap, this.scope);
  57. this.selection = {
  58. active: false,
  59. x1: -1,
  60. x2: -1,
  61. };
  62. this.padding = { left: 0, right: 0, top: 0, bottom: 0 };
  63. this.margin = { left: 25, right: 15, top: 10, bottom: 20 };
  64. this.dataRangeWidingFactor = DATA_RANGE_WIDING_FACTOR;
  65. this.ctrl.events.on('render', this.onRender.bind(this));
  66. this.ctrl.tickValueFormatter = this.tickValueFormatter.bind(this);
  67. /////////////////////////////
  68. // Selection and crosshair //
  69. /////////////////////////////
  70. // Shared crosshair and tooltip
  71. appEvents.on('graph-hover', this.onGraphHover.bind(this), this.scope);
  72. appEvents.on('graph-hover-clear', this.onGraphHoverClear.bind(this), this.scope);
  73. // Register selection listeners
  74. this.$heatmap.on('mousedown', this.onMouseDown.bind(this));
  75. this.$heatmap.on('mousemove', this.onMouseMove.bind(this));
  76. this.$heatmap.on('mouseleave', this.onMouseLeave.bind(this));
  77. }
  78. onGraphHoverClear() {
  79. this.clearCrosshair();
  80. }
  81. onGraphHover(event) {
  82. this.drawSharedCrosshair(event.pos);
  83. }
  84. onRender() {
  85. this.render();
  86. this.ctrl.renderingCompleted();
  87. }
  88. setElementHeight() {
  89. try {
  90. let height = this.ctrl.height || this.panel.height || this.ctrl.row.height;
  91. if (_.isString(height)) {
  92. height = parseInt(height.replace('px', ''), 10);
  93. }
  94. height -= this.panel.legend.show ? 28 : 11; // bottom padding and space for legend
  95. this.$heatmap.css('height', height + 'px');
  96. return true;
  97. } catch (e) {
  98. // IE throws errors sometimes
  99. return false;
  100. }
  101. }
  102. getYAxisWidth(elem) {
  103. const axisText = elem.selectAll('.axis-y text').nodes();
  104. const maxTextWidth = _.max(
  105. _.map(axisText, text => {
  106. // Use SVG getBBox method
  107. return text.getBBox().width;
  108. })
  109. );
  110. return maxTextWidth;
  111. }
  112. getXAxisHeight(elem) {
  113. const axisLine = elem.select('.axis-x line');
  114. if (!axisLine.empty()) {
  115. const axisLinePosition = parseFloat(elem.select('.axis-x line').attr('y2'));
  116. const canvasWidth = parseFloat(elem.attr('height'));
  117. return canvasWidth - axisLinePosition;
  118. } else {
  119. // Default height
  120. return 30;
  121. }
  122. }
  123. addXAxis() {
  124. this.scope.xScale = this.xScale = d3
  125. .scaleTime()
  126. .domain([this.timeRange.from, this.timeRange.to])
  127. .range([0, this.chartWidth]);
  128. const ticks = this.chartWidth / DEFAULT_X_TICK_SIZE_PX;
  129. const grafanaTimeFormatter = ticksUtils.grafanaTimeFormat(ticks, this.timeRange.from, this.timeRange.to);
  130. let timeFormat;
  131. const dashboardTimeZone = this.ctrl.dashboard.getTimezone();
  132. if (dashboardTimeZone === 'utc') {
  133. timeFormat = d3.utcFormat(grafanaTimeFormatter);
  134. } else {
  135. timeFormat = d3.timeFormat(grafanaTimeFormatter);
  136. }
  137. const xAxis = d3
  138. .axisBottom(this.xScale)
  139. .ticks(ticks)
  140. .tickFormat(timeFormat)
  141. .tickPadding(X_AXIS_TICK_PADDING)
  142. .tickSize(this.chartHeight);
  143. const posY = this.margin.top;
  144. const posX = this.yAxisWidth;
  145. this.heatmap
  146. .append('g')
  147. .attr('class', 'axis axis-x')
  148. .attr('transform', 'translate(' + posX + ',' + posY + ')')
  149. .call(xAxis);
  150. // Remove horizontal line in the top of axis labels (called domain in d3)
  151. this.heatmap
  152. .select('.axis-x')
  153. .select('.domain')
  154. .remove();
  155. }
  156. addYAxis() {
  157. let ticks = Math.ceil(this.chartHeight / DEFAULT_Y_TICK_SIZE_PX);
  158. let tickInterval = ticksUtils.tickStep(this.data.heatmapStats.min, this.data.heatmapStats.max, ticks);
  159. let { yMin, yMax } = this.wideYAxisRange(this.data.heatmapStats.min, this.data.heatmapStats.max, tickInterval);
  160. // Rewrite min and max if it have been set explicitly
  161. yMin = this.panel.yAxis.min !== null ? this.panel.yAxis.min : yMin;
  162. yMax = this.panel.yAxis.max !== null ? this.panel.yAxis.max : yMax;
  163. // Adjust ticks after Y range widening
  164. tickInterval = ticksUtils.tickStep(yMin, yMax, ticks);
  165. ticks = Math.ceil((yMax - yMin) / tickInterval);
  166. const decimalsAuto = ticksUtils.getPrecision(tickInterval);
  167. let decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals;
  168. // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
  169. const flotTickSize = ticksUtils.getFlotTickSize(yMin, yMax, ticks, decimalsAuto);
  170. const scaledDecimals = ticksUtils.getScaledDecimals(decimals, flotTickSize);
  171. this.ctrl.decimals = decimals;
  172. this.ctrl.scaledDecimals = scaledDecimals;
  173. // Set default Y min and max if no data
  174. if (_.isEmpty(this.data.buckets)) {
  175. yMax = 1;
  176. yMin = -1;
  177. ticks = 3;
  178. decimals = 1;
  179. }
  180. this.data.yAxis = {
  181. min: yMin,
  182. max: yMax,
  183. ticks: ticks,
  184. };
  185. this.scope.yScale = this.yScale = d3
  186. .scaleLinear()
  187. .domain([yMin, yMax])
  188. .range([this.chartHeight, 0]);
  189. const yAxis = d3
  190. .axisLeft(this.yScale)
  191. .ticks(ticks)
  192. .tickFormat(this.tickValueFormatter(decimals, scaledDecimals))
  193. .tickSizeInner(0 - this.width)
  194. .tickSizeOuter(0)
  195. .tickPadding(Y_AXIS_TICK_PADDING);
  196. this.heatmap
  197. .append('g')
  198. .attr('class', 'axis axis-y')
  199. .call(yAxis);
  200. // Calculate Y axis width first, then move axis into visible area
  201. const posY = this.margin.top;
  202. const posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
  203. this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
  204. // Remove vertical line in the right of axis labels (called domain in d3)
  205. this.heatmap
  206. .select('.axis-y')
  207. .select('.domain')
  208. .remove();
  209. }
  210. // Wide Y values range and anjust to bucket size
  211. wideYAxisRange(min, max, tickInterval) {
  212. const yWiding = (max * (this.dataRangeWidingFactor - 1) - min * (this.dataRangeWidingFactor - 1)) / 2;
  213. let yMin, yMax;
  214. if (tickInterval === 0) {
  215. yMax = max * this.dataRangeWidingFactor;
  216. yMin = min - min * (this.dataRangeWidingFactor - 1);
  217. } else {
  218. yMax = Math.ceil((max + yWiding) / tickInterval) * tickInterval;
  219. yMin = Math.floor((min - yWiding) / tickInterval) * tickInterval;
  220. }
  221. // Don't wide axis below 0 if all values are positive
  222. if (min >= 0 && yMin < 0) {
  223. yMin = 0;
  224. }
  225. return { yMin, yMax };
  226. }
  227. addLogYAxis() {
  228. const logBase = this.panel.yAxis.logBase;
  229. let { yMin, yMax } = this.adjustLogRange(this.data.heatmapStats.minLog, this.data.heatmapStats.max, logBase);
  230. yMin =
  231. this.panel.yAxis.min && this.panel.yAxis.min !== '0' ? this.adjustLogMin(this.panel.yAxis.min, logBase) : yMin;
  232. yMax = this.panel.yAxis.max !== null ? this.adjustLogMax(this.panel.yAxis.max, logBase) : yMax;
  233. // Set default Y min and max if no data
  234. if (_.isEmpty(this.data.buckets)) {
  235. yMax = Math.pow(logBase, 2);
  236. yMin = 1;
  237. }
  238. this.scope.yScale = this.yScale = d3
  239. .scaleLog()
  240. .base(this.panel.yAxis.logBase)
  241. .domain([yMin, yMax])
  242. .range([this.chartHeight, 0]);
  243. const domain = this.yScale.domain();
  244. const tickValues = this.logScaleTickValues(domain, logBase);
  245. const decimalsAuto = ticksUtils.getPrecision(yMin);
  246. const decimals = this.panel.yAxis.decimals || decimalsAuto;
  247. // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
  248. const flotTickSize = ticksUtils.getFlotTickSize(yMin, yMax, tickValues.length, decimalsAuto);
  249. const scaledDecimals = ticksUtils.getScaledDecimals(decimals, flotTickSize);
  250. this.ctrl.decimals = decimals;
  251. this.ctrl.scaledDecimals = scaledDecimals;
  252. this.data.yAxis = {
  253. min: yMin,
  254. max: yMax,
  255. ticks: tickValues.length,
  256. };
  257. const yAxis = d3
  258. .axisLeft(this.yScale)
  259. .tickValues(tickValues)
  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. const posY = this.margin.top;
  270. const 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 (yMin < 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 tickValues = _.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. const 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. const yAxis = d3
  307. .axisLeft(this.yScale)
  308. .tickValues(tickValues)
  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 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. const 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 getColorFromHexRgbOrName(
  561. this.panel.color.cardColor,
  562. contextSrv.user.lightTheme ? GrafanaTheme.Light : GrafanaTheme.Dark
  563. );
  564. } else {
  565. return this.colorScale(d.count);
  566. }
  567. }
  568. getCardOpacity(d) {
  569. if (this.panel.color.mode === 'opacity') {
  570. return this.opacityScale(d.count);
  571. } else {
  572. return 1;
  573. }
  574. }
  575. getEventOffset(event) {
  576. const elemOffset = this.$heatmap.offset();
  577. const x = Math.floor(event.clientX - elemOffset.left);
  578. const y = Math.floor(event.clientY - elemOffset.top);
  579. return { x, y };
  580. }
  581. onMouseDown(event) {
  582. const offset = this.getEventOffset(event);
  583. this.selection.active = true;
  584. this.selection.x1 = offset.x;
  585. this.mouseUpHandler = () => {
  586. this.onMouseUp();
  587. };
  588. $(document).one('mouseup', this.mouseUpHandler.bind(this));
  589. }
  590. onMouseUp() {
  591. $(document).unbind('mouseup', this.mouseUpHandler.bind(this));
  592. this.mouseUpHandler = null;
  593. this.selection.active = false;
  594. const selectionRange = Math.abs(this.selection.x2 - this.selection.x1);
  595. if (this.selection.x2 >= 0 && selectionRange > MIN_SELECTION_WIDTH) {
  596. const timeFrom = this.xScale.invert(Math.min(this.selection.x1, this.selection.x2) - this.yAxisWidth);
  597. const timeTo = this.xScale.invert(Math.max(this.selection.x1, this.selection.x2) - this.yAxisWidth);
  598. this.ctrl.timeSrv.setTime({
  599. from: moment.utc(timeFrom),
  600. to: moment.utc(timeTo),
  601. });
  602. }
  603. this.clearSelection();
  604. }
  605. onMouseLeave() {
  606. appEvents.emit('graph-hover-clear');
  607. this.clearCrosshair();
  608. }
  609. onMouseMove(event) {
  610. if (!this.heatmap) {
  611. return;
  612. }
  613. const offset = this.getEventOffset(event);
  614. if (this.selection.active) {
  615. // Clear crosshair and tooltip
  616. this.clearCrosshair();
  617. this.tooltip.destroy();
  618. this.selection.x2 = this.limitSelection(offset.x);
  619. this.drawSelection(this.selection.x1, this.selection.x2);
  620. } else {
  621. const pos = this.getEventPos(event, offset);
  622. this.drawCrosshair(offset.x);
  623. this.tooltip.show(pos, this.data);
  624. this.emitGraphHoverEvent(pos);
  625. }
  626. }
  627. getEventPos(event, offset) {
  628. const x = this.xScale.invert(offset.x - this.yAxisWidth).valueOf();
  629. const y = this.yScale.invert(offset.y - this.chartTop);
  630. const pos = {
  631. pageX: event.pageX,
  632. pageY: event.pageY,
  633. x: x,
  634. x1: x,
  635. y: y,
  636. y1: y,
  637. panelRelY: null,
  638. offset,
  639. };
  640. return pos;
  641. }
  642. emitGraphHoverEvent(pos) {
  643. // Set minimum offset to prevent showing legend from another panel
  644. pos.panelRelY = Math.max(pos.offset.y / this.height, 0.001);
  645. // broadcast to other graph panels that we are hovering
  646. appEvents.emit('graph-hover', { pos: pos, panel: this.panel });
  647. }
  648. limitSelection(x2) {
  649. x2 = Math.max(x2, this.yAxisWidth);
  650. x2 = Math.min(x2, this.chartWidth + this.yAxisWidth);
  651. return x2;
  652. }
  653. drawSelection(posX1, posX2) {
  654. if (this.heatmap) {
  655. this.heatmap.selectAll('.heatmap-selection').remove();
  656. const selectionX = Math.min(posX1, posX2);
  657. const selectionWidth = Math.abs(posX1 - posX2);
  658. if (selectionWidth > MIN_SELECTION_WIDTH) {
  659. this.heatmap
  660. .append('rect')
  661. .attr('class', 'heatmap-selection')
  662. .attr('x', selectionX)
  663. .attr('width', selectionWidth)
  664. .attr('y', this.chartTop)
  665. .attr('height', this.chartHeight);
  666. }
  667. }
  668. }
  669. clearSelection() {
  670. this.selection.x1 = -1;
  671. this.selection.x2 = -1;
  672. if (this.heatmap) {
  673. this.heatmap.selectAll('.heatmap-selection').remove();
  674. }
  675. }
  676. drawCrosshair(position) {
  677. if (this.heatmap) {
  678. this.heatmap.selectAll('.heatmap-crosshair').remove();
  679. let posX = position;
  680. posX = Math.max(posX, this.yAxisWidth);
  681. posX = Math.min(posX, this.chartWidth + this.yAxisWidth);
  682. this.heatmap
  683. .append('g')
  684. .attr('class', 'heatmap-crosshair')
  685. .attr('transform', 'translate(' + posX + ',0)')
  686. .append('line')
  687. .attr('x1', 1)
  688. .attr('y1', this.chartTop)
  689. .attr('x2', 1)
  690. .attr('y2', this.chartBottom)
  691. .attr('stroke-width', 1);
  692. }
  693. }
  694. drawSharedCrosshair(pos) {
  695. if (this.heatmap && this.ctrl.dashboard.graphTooltip !== 0) {
  696. const posX = this.xScale(pos.x) + this.yAxisWidth;
  697. this.drawCrosshair(posX);
  698. }
  699. }
  700. clearCrosshair() {
  701. if (this.heatmap) {
  702. this.heatmap.selectAll('.heatmap-crosshair').remove();
  703. }
  704. }
  705. render() {
  706. this.data = this.ctrl.data;
  707. this.panel = this.ctrl.panel;
  708. this.timeRange = this.ctrl.range;
  709. if (!this.setElementHeight() || !this.data) {
  710. return;
  711. }
  712. // Draw default axes and return if no data
  713. if (_.isEmpty(this.data.buckets)) {
  714. this.addHeatmapCanvas();
  715. this.addAxes();
  716. return;
  717. }
  718. this.addHeatmap();
  719. this.scope.yAxisWidth = this.yAxisWidth;
  720. this.scope.xAxisHeight = this.xAxisHeight;
  721. this.scope.chartHeight = this.chartHeight;
  722. this.scope.chartWidth = this.chartWidth;
  723. this.scope.chartTop = this.chartTop;
  724. }
  725. }