rendering.ts 23 KB

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