rendering.ts 23 KB

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