rendering.ts 23 KB

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