graph_tooltip.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import $ from 'jquery';
  2. import {
  3. textUtil,
  4. systemDateFormats,
  5. LegacyGraphHoverClearEvent,
  6. LegacyGraphHoverEvent,
  7. DataHoverClearEvent,
  8. } from '@grafana/data';
  9. import { appEvents } from 'app/core/core';
  10. import { CoreEvents } from 'app/types';
  11. export default function GraphTooltip(this: any, elem: any, dashboard: any, scope: any, getSeriesFn: any) {
  12. const self = this;
  13. const ctrl = scope.ctrl;
  14. const panel = ctrl.panel;
  15. const hoverEvent = new LegacyGraphHoverEvent({ pos: {}, point: {}, panel: this.panel });
  16. const $tooltip = $('<div class="graph-tooltip">');
  17. this.destroy = () => {
  18. $tooltip.remove();
  19. };
  20. this.findHoverIndexFromDataPoints = (posX: number, series: any, last: number) => {
  21. const ps = series.datapoints.pointsize;
  22. const initial = last * ps;
  23. const len = series.datapoints.points.length;
  24. let j;
  25. for (j = initial; j < len; j += ps) {
  26. // Special case of a non stepped line, highlight the very last point just before a null point
  27. if (
  28. (!series.lines.steps && series.datapoints.points[initial] != null && series.datapoints.points[j] == null) ||
  29. //normal case
  30. series.datapoints.points[j] > posX
  31. ) {
  32. return Math.max(j - ps, 0) / ps;
  33. }
  34. }
  35. return j / ps - 1;
  36. };
  37. this.findHoverIndexFromData = (posX: any, series: any) => {
  38. let lower = 0;
  39. let upper = series.data.length - 1;
  40. let middle;
  41. while (true) {
  42. if (lower > upper) {
  43. return Math.max(upper, 0);
  44. }
  45. middle = Math.floor((lower + upper) / 2);
  46. if (series.data[middle][0] === posX) {
  47. return middle;
  48. } else if (series.data[middle][0] < posX) {
  49. lower = middle + 1;
  50. } else {
  51. upper = middle - 1;
  52. }
  53. }
  54. };
  55. this.renderAndShow = (absoluteTime: string, innerHtml: string, pos: { pageX: number; pageY: any }, xMode: string) => {
  56. if (xMode === 'time') {
  57. innerHtml = '<div class="graph-tooltip-time">' + absoluteTime + '</div>' + innerHtml;
  58. }
  59. $tooltip.html(innerHtml).place_tt(pos.pageX, pos.pageY, { offset: 10 });
  60. };
  61. this.getMultiSeriesPlotHoverInfo = function (seriesList: any[], pos: { x: number }) {
  62. let value, i, series, hoverIndex, hoverDistance, pointTime, yaxis;
  63. // 3 sub-arrays, 1st for hidden series, 2nd for left yaxis, 3rd for right yaxis.
  64. let results: any = [[], [], []];
  65. //now we know the current X (j) position for X and Y values
  66. let lastValue = 0; //needed for stacked values
  67. let minDistance, minTime;
  68. for (i = 0; i < seriesList.length; i++) {
  69. series = seriesList[i];
  70. if (!series.data.length || (panel.legend.hideEmpty && series.allIsNull)) {
  71. // Init value so that it does not brake series sorting
  72. results[0].push({ hidden: true, value: 0 });
  73. continue;
  74. }
  75. if (!series.data.length || (panel.legend.hideZero && series.allIsZero)) {
  76. // Init value so that it does not brake series sorting
  77. results[0].push({ hidden: true, value: 0 });
  78. continue;
  79. }
  80. if (series.hideTooltip) {
  81. results[0].push({ hidden: true, value: 0 });
  82. continue;
  83. }
  84. hoverIndex = this.findHoverIndexFromData(pos.x, series);
  85. hoverDistance = pos.x - series.data[hoverIndex][0];
  86. pointTime = series.data[hoverIndex][0];
  87. // Take the closest point before the cursor, or if it does not exist, the closest after
  88. if (
  89. !minDistance ||
  90. (hoverDistance >= 0 && (hoverDistance < minDistance || minDistance < 0)) ||
  91. (hoverDistance < 0 && hoverDistance > minDistance)
  92. ) {
  93. minDistance = hoverDistance;
  94. minTime = pointTime;
  95. }
  96. value = series.data[hoverIndex][1];
  97. if (series.stack && value !== null && panel.tooltip.value_type !== 'individual') {
  98. lastValue += value;
  99. value = lastValue;
  100. }
  101. // Highlighting multiple Points depending on the plot type
  102. if (series.lines.steps || series.stack) {
  103. // stacked and steppedLine plots can have series with different length.
  104. // Stacked series can increase its length on each new stacked serie if null points found,
  105. // to speed the index search we begin always on the last found hoverIndex.
  106. hoverIndex = this.findHoverIndexFromDataPoints(pos.x, series, hoverIndex);
  107. }
  108. // Be sure we have a yaxis so that it does not brake series sorting
  109. yaxis = 0;
  110. if (series.yaxis) {
  111. yaxis = series.yaxis.n;
  112. }
  113. results[yaxis].push({
  114. value: value,
  115. hoverIndex: hoverIndex,
  116. color: series.color,
  117. label: series.aliasEscaped,
  118. time: pointTime,
  119. distance: hoverDistance,
  120. index: i,
  121. });
  122. }
  123. // Contat the 3 sub-arrays
  124. results = results[0].concat(results[1], results[2]);
  125. // Time of the point closer to pointer
  126. results.time = minTime;
  127. return results;
  128. };
  129. elem.mouseleave(() => {
  130. if (panel.tooltip?.shared) {
  131. const plot = elem.data().plot;
  132. if (plot) {
  133. $tooltip.detach();
  134. plot.unhighlight();
  135. }
  136. }
  137. dashboard.events.publish(new LegacyGraphHoverClearEvent());
  138. dashboard.events.publish(new DataHoverClearEvent());
  139. });
  140. elem.bind('plothover', (event: any, pos: { panelRelY: number; pageY: number }, item: any) => {
  141. self.show(pos, item);
  142. // broadcast to other graph panels that we are hovering!
  143. if (!dashboard.panelInEdit) {
  144. pos.panelRelY = (pos.pageY - elem.offset().top) / elem.height();
  145. hoverEvent.payload.pos = pos;
  146. hoverEvent.payload.panel = panel;
  147. hoverEvent.payload.point['time'] = (pos as any).x;
  148. dashboard.events.publish(hoverEvent);
  149. }
  150. });
  151. elem.bind('plotclick', (event: any, pos: any, item: any) => {
  152. appEvents.emit(CoreEvents.graphClicked, { pos: pos, panel: panel, item: item });
  153. });
  154. elem.bind('plotleave', () => {
  155. if (!panel.tooltip.shared) {
  156. return;
  157. }
  158. const plot = elem.data().plot;
  159. if (plot) {
  160. $tooltip.detach();
  161. plot.unhighlight();
  162. }
  163. });
  164. this.clear = (plot: { clearCrosshair: () => void; unhighlight: () => void }) => {
  165. $tooltip.detach();
  166. plot.clearCrosshair();
  167. plot.unhighlight();
  168. };
  169. this.show = (pos: any, item: any) => {
  170. const plot = elem.data().plot;
  171. const plotData = plot.getData();
  172. const xAxes = plot.getXAxes();
  173. const xMode = xAxes[0].options.mode;
  174. const seriesList = getSeriesFn();
  175. let allSeriesMode = panel.tooltip.shared;
  176. let group, value, absoluteTime, hoverInfo, i, series, seriesHtml, tooltipFormat;
  177. // if panelRelY is defined another panel wants us to show a tooltip
  178. // get pageX from position on x axis and pageY from relative position in original panel
  179. if (pos.panelRelY) {
  180. const pointOffset = plot.pointOffset({ x: pos.x });
  181. if (Number.isNaN(pointOffset.left) || pointOffset.left < 0 || pointOffset.left > elem.width()) {
  182. self.clear(plot);
  183. return;
  184. }
  185. pos.pageX = elem.offset().left + pointOffset.left;
  186. pos.pageY = elem.offset().top + elem.height() * pos.panelRelY;
  187. const scrollTop = $(window).scrollTop() ?? 0;
  188. const isVisible = pos.pageY >= scrollTop && pos.pageY <= $(window).innerHeight()! + scrollTop;
  189. if (!isVisible) {
  190. self.clear(plot);
  191. return;
  192. }
  193. plot.setCrosshair(pos);
  194. allSeriesMode = true;
  195. if (dashboard.sharedCrosshairModeOnly()) {
  196. // if only crosshair mode we are done
  197. return;
  198. }
  199. }
  200. if (seriesList.length === 0) {
  201. return;
  202. }
  203. if (seriesList[0].hasMsResolution) {
  204. tooltipFormat = systemDateFormats.fullDateMS;
  205. } else {
  206. tooltipFormat = systemDateFormats.fullDate;
  207. }
  208. if (allSeriesMode) {
  209. plot.unhighlight();
  210. const seriesHoverInfo = self.getMultiSeriesPlotHoverInfo(plotData, pos);
  211. seriesHtml = '';
  212. absoluteTime = dashboard.formatDate(seriesHoverInfo.time, tooltipFormat);
  213. // Dynamically reorder the hovercard for the current time point if the
  214. // option is enabled.
  215. if (panel.tooltip.sort === 2) {
  216. seriesHoverInfo.sort((a: { value: number }, b: { value: number }) => {
  217. return b.value - a.value;
  218. });
  219. } else if (panel.tooltip.sort === 1) {
  220. seriesHoverInfo.sort((a: { value: number }, b: { value: number }) => {
  221. return a.value - b.value;
  222. });
  223. }
  224. for (i = 0; i < seriesHoverInfo.length; i++) {
  225. hoverInfo = seriesHoverInfo[i];
  226. if (hoverInfo.hidden) {
  227. continue;
  228. }
  229. let highlightClass = '';
  230. if (item && hoverInfo.index === item.seriesIndex) {
  231. highlightClass = 'graph-tooltip-list-item--highlight';
  232. }
  233. series = seriesList[hoverInfo.index];
  234. value = textUtil.sanitize(series.formatValue(hoverInfo.value));
  235. const color = textUtil.sanitize(hoverInfo.color);
  236. const label = textUtil.sanitize(hoverInfo.label);
  237. seriesHtml +=
  238. '<div class="graph-tooltip-list-item ' + highlightClass + '"><div class="graph-tooltip-series-name">';
  239. seriesHtml += '<i class="fa fa-minus" style="color:' + color + ';"></i> ' + label + ':</div>';
  240. seriesHtml += '<div class="graph-tooltip-value">' + value + '</div></div>';
  241. plot.highlight(hoverInfo.index, hoverInfo.hoverIndex);
  242. }
  243. self.renderAndShow(absoluteTime, seriesHtml, pos, xMode);
  244. } else if (item) {
  245. // single series tooltip
  246. const color = textUtil.sanitize(item.series.color);
  247. series = seriesList[item.seriesIndex];
  248. group = '<div class="graph-tooltip-list-item"><div class="graph-tooltip-series-name">';
  249. group += '<i class="fa fa-minus" style="color:' + color + ';"></i> ' + series.aliasEscaped + ':</div>';
  250. if (panel.stack && panel.tooltip.value_type === 'individual') {
  251. value = item.datapoint[1] - item.datapoint[2];
  252. } else {
  253. value = item.datapoint[1];
  254. }
  255. value = textUtil.sanitize(series.formatValue(value));
  256. absoluteTime = dashboard.formatDate(item.datapoint[0], tooltipFormat);
  257. group += '<div class="graph-tooltip-value">' + value + '</div>';
  258. self.renderAndShow(absoluteTime, group, pos, xMode);
  259. } else {
  260. // no hit
  261. $tooltip.detach();
  262. }
  263. };
  264. }