rendering.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 {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 = data.cards;
  314. let maxValueAuto = data.cardStats.max;
  315. let maxValue = panel.color.max || maxValueAuto;
  316. let minValue = panel.color.min || 0;
  317. colorScale = getColorScale(maxValue, minValue);
  318. setOpacityScale(maxValue);
  319. setCardSize();
  320. let cards = heatmap.selectAll(".heatmap-card").data(cardsData);
  321. cards.append("title");
  322. cards = cards.enter().append("rect")
  323. .attr("x", getCardX)
  324. .attr("width", getCardWidth)
  325. .attr("y", getCardY)
  326. .attr("height", getCardHeight)
  327. .attr("rx", cardRound)
  328. .attr("ry", cardRound)
  329. .attr("class", "bordered heatmap-card")
  330. .style("fill", getCardColor)
  331. .style("stroke", getCardColor)
  332. .style("stroke-width", 0)
  333. .style("opacity", getCardOpacity);
  334. let $cards = $heatmap.find(".heatmap-card");
  335. $cards.on("mouseenter", (event) => {
  336. tooltip.mouseOverBucket = true;
  337. highlightCard(event);
  338. })
  339. .on("mouseleave", (event) => {
  340. tooltip.mouseOverBucket = false;
  341. resetCardHighLight(event);
  342. });
  343. }
  344. function highlightCard(event) {
  345. let color = d3.select(event.target).style("fill");
  346. let highlightColor = d3.color(color).darker(2);
  347. let strokeColor = d3.color(color).brighter(4);
  348. let current_card = d3.select(event.target);
  349. tooltip.originalFillColor = color;
  350. current_card.style("fill", highlightColor)
  351. .style("stroke", strokeColor)
  352. .style("stroke-width", 1);
  353. }
  354. function resetCardHighLight(event) {
  355. d3.select(event.target).style("fill", tooltip.originalFillColor)
  356. .style("stroke", tooltip.originalFillColor)
  357. .style("stroke-width", 0);
  358. }
  359. function getColorScale(maxValue, minValue = 0) {
  360. let colorScheme = _.find(ctrl.colorSchemes, {value: panel.color.colorScheme});
  361. let colorInterpolator = d3[colorScheme.value];
  362. let colorScaleInverted = colorScheme.invert === 'always' ||
  363. (colorScheme.invert === 'dark' && !contextSrv.user.lightTheme);
  364. let start = colorScaleInverted ? maxValue : minValue;
  365. let end = colorScaleInverted ? minValue : maxValue;
  366. return d3.scaleSequential(colorInterpolator).domain([start, end]);
  367. }
  368. function setOpacityScale(maxValue) {
  369. if (panel.color.colorScale === 'linear') {
  370. opacityScale = d3.scaleLinear()
  371. .domain([0, maxValue])
  372. .range([0, 1]);
  373. } else if (panel.color.colorScale === 'sqrt') {
  374. opacityScale = d3.scalePow().exponent(panel.color.exponent)
  375. .domain([0, maxValue])
  376. .range([0, 1]);
  377. }
  378. }
  379. function setCardSize() {
  380. let xGridSize = Math.floor(xScale(data.xBucketSize) - xScale(0));
  381. let yGridSize = Math.floor(yScale(yScale.invert(0) - data.yBucketSize));
  382. if (panel.yAxis.logBase !== 1) {
  383. let base = panel.yAxis.logBase;
  384. let splitFactor = data.yBucketSize || 1;
  385. yGridSize = Math.floor((yScale(1) - yScale(base)) / splitFactor);
  386. }
  387. cardWidth = xGridSize - cardPadding * 2;
  388. cardHeight = yGridSize ? yGridSize - cardPadding * 2 : 0;
  389. }
  390. function getCardX(d) {
  391. let x;
  392. if (xScale(d.x) < 0) {
  393. // Cut card left to prevent overlay
  394. x = yAxisWidth + cardPadding;
  395. } else {
  396. x = xScale(d.x) + yAxisWidth + cardPadding;
  397. }
  398. return x;
  399. }
  400. function getCardWidth(d) {
  401. let w;
  402. if (xScale(d.x) < 0) {
  403. // Cut card left to prevent overlay
  404. let cutted_width = xScale(d.x) + cardWidth;
  405. w = cutted_width > 0 ? cutted_width : 0;
  406. } else if (xScale(d.x) + cardWidth > chartWidth) {
  407. // Cut card right to prevent overlay
  408. w = chartWidth - xScale(d.x) - cardPadding;
  409. } else {
  410. w = cardWidth;
  411. }
  412. // Card width should be MIN_CARD_SIZE at least
  413. w = Math.max(w, MIN_CARD_SIZE);
  414. return w;
  415. }
  416. function getCardY(d) {
  417. let y = yScale(d.y) + chartTop - cardHeight - cardPadding;
  418. if (panel.yAxis.logBase !== 1 && d.y === 0) {
  419. y = chartBottom - cardHeight - cardPadding;
  420. } else {
  421. if (y < chartTop) {
  422. y = chartTop;
  423. }
  424. }
  425. return y;
  426. }
  427. function getCardHeight(d) {
  428. let y = yScale(d.y) + chartTop - cardHeight - cardPadding;
  429. let h = cardHeight;
  430. if (panel.yAxis.logBase !== 1 && d.y === 0) {
  431. return cardHeight;
  432. }
  433. // Cut card height to prevent overlay
  434. if (y < chartTop) {
  435. h = yScale(d.y) - cardPadding;
  436. } else if (yScale(d.y) > chartBottom) {
  437. h = chartBottom - y;
  438. } else if (y + cardHeight > chartBottom) {
  439. h = chartBottom - y;
  440. }
  441. // Height can't be more than chart height
  442. h = Math.min(h, chartHeight);
  443. // Card height should be MIN_CARD_SIZE at least
  444. h = Math.max(h, MIN_CARD_SIZE);
  445. return h;
  446. }
  447. function getCardColor(d) {
  448. if (panel.color.mode === 'opacity') {
  449. return panel.color.cardColor;
  450. } else {
  451. return colorScale(d.count);
  452. }
  453. }
  454. function getCardOpacity(d) {
  455. if (panel.color.mode === 'opacity') {
  456. return opacityScale(d.count);
  457. } else {
  458. return 1;
  459. }
  460. }
  461. /////////////////////////////
  462. // Selection and crosshair //
  463. /////////////////////////////
  464. // Shared crosshair and tooltip
  465. appEvents.on('graph-hover', event => {
  466. drawSharedCrosshair(event.pos);
  467. }, scope);
  468. appEvents.on('graph-hover-clear', () => {
  469. clearCrosshair();
  470. }, scope);
  471. function onMouseDown(event) {
  472. selection.active = true;
  473. selection.x1 = event.offsetX;
  474. mouseUpHandler = function() {
  475. onMouseUp();
  476. };
  477. $(document).one("mouseup", mouseUpHandler);
  478. }
  479. function onMouseUp() {
  480. $(document).unbind("mouseup", mouseUpHandler);
  481. mouseUpHandler = null;
  482. selection.active = false;
  483. let selectionRange = Math.abs(selection.x2 - selection.x1);
  484. if (selection.x2 >= 0 && selectionRange > MIN_SELECTION_WIDTH) {
  485. let timeFrom = xScale.invert(Math.min(selection.x1, selection.x2) - yAxisWidth);
  486. let timeTo = xScale.invert(Math.max(selection.x1, selection.x2) - yAxisWidth);
  487. ctrl.timeSrv.setTime({
  488. from: moment.utc(timeFrom),
  489. to: moment.utc(timeTo)
  490. });
  491. }
  492. clearSelection();
  493. }
  494. function onMouseLeave() {
  495. appEvents.emit('graph-hover-clear');
  496. clearCrosshair();
  497. }
  498. function onMouseMove(event) {
  499. if (!heatmap) { return; }
  500. if (selection.active) {
  501. // Clear crosshair and tooltip
  502. clearCrosshair();
  503. tooltip.destroy();
  504. selection.x2 = limitSelection(event.offsetX);
  505. drawSelection(selection.x1, selection.x2);
  506. } else {
  507. emitGraphHoverEvet(event);
  508. drawCrosshair(event.offsetX);
  509. tooltip.show(event, data);
  510. }
  511. }
  512. function emitGraphHoverEvet(event) {
  513. let x = xScale.invert(event.offsetX - yAxisWidth).valueOf();
  514. let y = yScale.invert(event.offsetY);
  515. let pos = {
  516. pageX: event.pageX,
  517. pageY: event.pageY,
  518. x: x, x1: x,
  519. y: y, y1: y,
  520. panelRelY: null
  521. };
  522. // Set minimum offset to prevent showing legend from another panel
  523. pos.panelRelY = Math.max(event.offsetY / height, 0.001);
  524. // broadcast to other graph panels that we are hovering
  525. appEvents.emit('graph-hover', {pos: pos, panel: panel});
  526. }
  527. function limitSelection(x2) {
  528. x2 = Math.max(x2, yAxisWidth);
  529. x2 = Math.min(x2, chartWidth + yAxisWidth);
  530. return x2;
  531. }
  532. function drawSelection(posX1, posX2) {
  533. if (heatmap) {
  534. heatmap.selectAll(".heatmap-selection").remove();
  535. let selectionX = Math.min(posX1, posX2);
  536. let selectionWidth = Math.abs(posX1 - posX2);
  537. if (selectionWidth > MIN_SELECTION_WIDTH) {
  538. heatmap.append("rect")
  539. .attr("class", "heatmap-selection")
  540. .attr("x", selectionX)
  541. .attr("width", selectionWidth)
  542. .attr("y", chartTop)
  543. .attr("height", chartHeight);
  544. }
  545. }
  546. }
  547. function clearSelection() {
  548. selection.x1 = -1;
  549. selection.x2 = -1;
  550. if (heatmap) {
  551. heatmap.selectAll(".heatmap-selection").remove();
  552. }
  553. }
  554. function drawCrosshair(position) {
  555. if (heatmap) {
  556. heatmap.selectAll(".heatmap-crosshair").remove();
  557. let posX = position;
  558. posX = Math.max(posX, yAxisWidth);
  559. posX = Math.min(posX, chartWidth + yAxisWidth);
  560. heatmap.append("g")
  561. .attr("class", "heatmap-crosshair")
  562. .attr("transform", "translate(" + posX + ",0)")
  563. .append("line")
  564. .attr("x1", 1)
  565. .attr("y1", chartTop)
  566. .attr("x2", 1)
  567. .attr("y2", chartBottom)
  568. .attr("stroke-width", 1);
  569. }
  570. }
  571. function drawSharedCrosshair(pos) {
  572. if (heatmap && ctrl.dashboard.graphTooltip !== 0) {
  573. let posX = xScale(pos.x) + yAxisWidth;
  574. drawCrosshair(posX);
  575. }
  576. }
  577. function clearCrosshair() {
  578. if (heatmap) {
  579. heatmap.selectAll(".heatmap-crosshair").remove();
  580. }
  581. }
  582. function render() {
  583. data = ctrl.data;
  584. panel = ctrl.panel;
  585. timeRange = ctrl.range;
  586. if (!setElementHeight() || !data) {
  587. return;
  588. }
  589. // Draw default axes and return if no data
  590. if (_.isEmpty(data.buckets)) {
  591. addHeatmapCanvas();
  592. addAxes();
  593. return;
  594. }
  595. addHeatmap();
  596. scope.yAxisWidth = yAxisWidth;
  597. scope.xAxisHeight = xAxisHeight;
  598. scope.chartHeight = chartHeight;
  599. scope.chartWidth = chartWidth;
  600. scope.chartTop = chartTop;
  601. }
  602. // Register selection listeners
  603. $heatmap.on("mousedown", onMouseDown);
  604. $heatmap.on("mousemove", onMouseMove);
  605. $heatmap.on("mouseleave", onMouseLeave);
  606. }
  607. function grafanaTimeFormat(ticks, min, max) {
  608. if (min && max && ticks) {
  609. let range = max - min;
  610. let secPerTick = (range/ticks) / 1000;
  611. let oneDay = 86400000;
  612. let oneYear = 31536000000;
  613. if (secPerTick <= 45) {
  614. return "%H:%M:%S";
  615. }
  616. if (secPerTick <= 7200 || range <= oneDay) {
  617. return "%H:%M";
  618. }
  619. if (secPerTick <= 80000) {
  620. return "%m/%d %H:%M";
  621. }
  622. if (secPerTick <= 2419200 || range <= oneYear) {
  623. return "%m/%d";
  624. }
  625. return "%Y-%m";
  626. }
  627. return "%H:%M";
  628. }
  629. function logp(value, base) {
  630. return Math.log(value) / Math.log(base);
  631. }
  632. function getPrecision(num) {
  633. let str = num.toString();
  634. let dot_index = str.indexOf(".");
  635. if (dot_index === -1) {
  636. return 0;
  637. } else {
  638. return str.length - dot_index - 1;
  639. }
  640. }