jquery.flot.tooltip.source.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. (function ($) {
  2. // plugin options, default values
  3. var defaultOptions = {
  4. tooltip: {
  5. show: false,
  6. cssClass: "flotTip",
  7. content: "%s | X: %x | Y: %y",
  8. // allowed templates are:
  9. // %s -> series label,
  10. // %c -> series color,
  11. // %lx -> x axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
  12. // %ly -> y axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
  13. // %x -> X value,
  14. // %y -> Y value,
  15. // %x.2 -> precision of X value,
  16. // %p -> percent
  17. // %n -> value (not percent) of pie chart
  18. xDateFormat: null,
  19. yDateFormat: null,
  20. monthNames: null,
  21. dayNames: null,
  22. shifts: {
  23. x: 10,
  24. y: 20
  25. },
  26. defaultTheme: true,
  27. snap: true,
  28. lines: false,
  29. clickTips: false,
  30. // callbacks
  31. onHover: function (flotItem, $tooltipEl) {},
  32. $compat: false
  33. }
  34. };
  35. // dummy default options object for legacy code (<0.8.5) - is deleted later
  36. defaultOptions.tooltipOpts = defaultOptions.tooltip;
  37. // object
  38. var FlotTooltip = function (plot) {
  39. // variables
  40. this.tipPosition = {x: 0, y: 0};
  41. this.init(plot);
  42. };
  43. // main plugin function
  44. FlotTooltip.prototype.init = function (plot) {
  45. var that = this;
  46. // detect other flot plugins
  47. var plotPluginsLength = $.plot.plugins.length;
  48. this.plotPlugins = [];
  49. if (plotPluginsLength) {
  50. for (var p = 0; p < plotPluginsLength; p++) {
  51. this.plotPlugins.push($.plot.plugins[p].name);
  52. }
  53. }
  54. plot.hooks.bindEvents.push(function (plot, eventHolder) {
  55. // get plot options
  56. that.plotOptions = plot.getOptions();
  57. // for legacy (<0.8.5) implementations
  58. if (typeof(that.plotOptions.tooltip) === 'boolean') {
  59. that.plotOptions.tooltipOpts.show = that.plotOptions.tooltip;
  60. that.plotOptions.tooltip = that.plotOptions.tooltipOpts;
  61. delete that.plotOptions.tooltipOpts;
  62. }
  63. // if not enabled return
  64. if (that.plotOptions.tooltip.show === false || typeof that.plotOptions.tooltip.show === 'undefined') return;
  65. // shortcut to access tooltip options
  66. that.tooltipOptions = that.plotOptions.tooltip;
  67. if (that.tooltipOptions.$compat) {
  68. that.wfunc = 'width';
  69. that.hfunc = 'height';
  70. } else {
  71. that.wfunc = 'innerWidth';
  72. that.hfunc = 'innerHeight';
  73. }
  74. // create tooltip DOM element
  75. var $tip = that.getDomElement();
  76. // bind event
  77. $( plot.getPlaceholder() ).bind("plothover", plothover);
  78. if (that.tooltipOptions.clickTips) {
  79. $( plot.getPlaceholder() ).bind("plotclick", plotclick);
  80. }
  81. that.clickmode = false;
  82. $(eventHolder).bind('mousemove', mouseMove);
  83. });
  84. plot.hooks.shutdown.push(function (plot, eventHolder){
  85. $(plot.getPlaceholder()).unbind("plothover", plothover);
  86. $(plot.getPlaceholder()).unbind("plotclick", plotclick);
  87. plot.removeTooltip();
  88. $(eventHolder).unbind("mousemove", mouseMove);
  89. });
  90. function mouseMove(e){
  91. var pos = {};
  92. pos.x = e.pageX;
  93. pos.y = e.pageY;
  94. plot.setTooltipPosition(pos);
  95. }
  96. /**
  97. * open the tooltip (if not already open) and freeze it on the current position till the next click
  98. */
  99. function plotclick(event, pos, item) {
  100. if (! that.clickmode) {
  101. // it is the click activating the clicktip
  102. plothover(event, pos, item);
  103. if (that.getDomElement().is(":visible")) {
  104. $(plot.getPlaceholder()).unbind("plothover", plothover);
  105. that.clickmode = true;
  106. }
  107. } else {
  108. // it is the click deactivating the clicktip
  109. $( plot.getPlaceholder() ).bind("plothover", plothover);
  110. plot.hideTooltip();
  111. that.clickmode = false;
  112. }
  113. }
  114. function plothover(event, pos, item) {
  115. // Simple distance formula.
  116. var lineDistance = function (p1x, p1y, p2x, p2y) {
  117. return Math.sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y));
  118. };
  119. // Here is some voodoo magic for determining the distance to a line form a given point {x, y}.
  120. var dotLineLength = function (x, y, x0, y0, x1, y1, o) {
  121. if (o && !(o =
  122. function (x, y, x0, y0, x1, y1) {
  123. if (typeof x0 !== 'undefined') return { x: x0, y: y };
  124. else if (typeof y0 !== 'undefined') return { x: x, y: y0 };
  125. var left,
  126. tg = -1 / ((y1 - y0) / (x1 - x0));
  127. return {
  128. x: left = (x1 * (x * tg - y + y0) + x0 * (x * -tg + y - y1)) / (tg * (x1 - x0) + y0 - y1),
  129. y: tg * left - tg * x + y
  130. };
  131. } (x, y, x0, y0, x1, y1),
  132. o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))
  133. ) {
  134. var l1 = lineDistance(x, y, x0, y0), l2 = lineDistance(x, y, x1, y1);
  135. return l1 > l2 ? l2 : l1;
  136. } else {
  137. var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
  138. return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
  139. }
  140. };
  141. if (item) {
  142. plot.showTooltip(item, that.tooltipOptions.snap ? item : pos);
  143. } else if (that.plotOptions.series.lines.show && that.tooltipOptions.lines === true) {
  144. var maxDistance = that.plotOptions.grid.mouseActiveRadius;
  145. var closestTrace = {
  146. distance: maxDistance + 1
  147. };
  148. var ttPos = pos;
  149. $.each(plot.getData(), function (i, series) {
  150. var xBeforeIndex = 0,
  151. xAfterIndex = -1;
  152. // Our search here assumes our data is sorted via the x-axis.
  153. // TODO: Improve efficiency somehow - search smaller sets of data.
  154. for (var j = 1; j < series.data.length; j++) {
  155. if (series.data[j - 1][0] <= pos.x && series.data[j][0] >= pos.x) {
  156. xBeforeIndex = j - 1;
  157. xAfterIndex = j;
  158. }
  159. }
  160. if (xAfterIndex === -1) {
  161. plot.hideTooltip();
  162. return;
  163. }
  164. var pointPrev = { x: series.data[xBeforeIndex][0], y: series.data[xBeforeIndex][1] },
  165. pointNext = { x: series.data[xAfterIndex][0], y: series.data[xAfterIndex][1] };
  166. var distToLine = dotLineLength(series.xaxis.p2c(pos.x), series.yaxis.p2c(pos.y), series.xaxis.p2c(pointPrev.x),
  167. series.yaxis.p2c(pointPrev.y), series.xaxis.p2c(pointNext.x), series.yaxis.p2c(pointNext.y), false);
  168. if (distToLine < closestTrace.distance) {
  169. var closestIndex = lineDistance(pointPrev.x, pointPrev.y, pos.x, pos.y) <
  170. lineDistance(pos.x, pos.y, pointNext.x, pointNext.y) ? xBeforeIndex : xAfterIndex;
  171. var pointSize = series.datapoints.pointsize;
  172. // Calculate the point on the line vertically closest to our cursor.
  173. var pointOnLine = [
  174. pos.x,
  175. pointPrev.y + ((pointNext.y - pointPrev.y) * ((pos.x - pointPrev.x) / (pointNext.x - pointPrev.x)))
  176. ];
  177. var item = {
  178. datapoint: pointOnLine,
  179. dataIndex: closestIndex,
  180. series: series,
  181. seriesIndex: i
  182. };
  183. closestTrace = {
  184. distance: distToLine,
  185. item: item
  186. };
  187. if (that.tooltipOptions.snap) {
  188. ttPos = {
  189. pageX: series.xaxis.p2c(pointOnLine[0]),
  190. pageY: series.yaxis.p2c(pointOnLine[1])
  191. };
  192. }
  193. }
  194. });
  195. if (closestTrace.distance < maxDistance + 1)
  196. plot.showTooltip(closestTrace.item, ttPos);
  197. else
  198. plot.hideTooltip();
  199. } else {
  200. plot.hideTooltip();
  201. }
  202. }
  203. // Quick little function for setting the tooltip position.
  204. plot.setTooltipPosition = function (pos) {
  205. var $tip = that.getDomElement();
  206. var totalTipWidth = $tip.outerWidth() + that.tooltipOptions.shifts.x;
  207. var totalTipHeight = $tip.outerHeight() + that.tooltipOptions.shifts.y;
  208. if ((pos.x - $(window).scrollLeft()) > ($(window)[that.wfunc]() - totalTipWidth)) {
  209. pos.x -= totalTipWidth;
  210. }
  211. if ((pos.y - $(window).scrollTop()) > ($(window)[that.hfunc]() - totalTipHeight)) {
  212. pos.y -= totalTipHeight;
  213. }
  214. /*
  215. The section applies the new positioning ONLY if pos.x and pos.y
  216. are numbers. If they are undefined or not a number, use the last
  217. known numerical position. This hack fixes a bug that kept pie
  218. charts from keeping their tooltip positioning.
  219. */
  220. if (isNaN(pos.x)) {
  221. that.tipPosition.x = that.tipPosition.xPrev;
  222. }
  223. else {
  224. that.tipPosition.x = pos.x;
  225. that.tipPosition.xPrev = pos.x;
  226. }
  227. if (isNaN(pos.y)) {
  228. that.tipPosition.y = that.tipPosition.yPrev;
  229. }
  230. else {
  231. that.tipPosition.y = pos.y;
  232. that.tipPosition.yPrev = pos.y;
  233. }
  234. };
  235. // Quick little function for showing the tooltip.
  236. plot.showTooltip = function (target, position, targetPosition) {
  237. var $tip = that.getDomElement();
  238. // convert tooltip content template to real tipText
  239. var tipText = that.stringFormat(that.tooltipOptions.content, target);
  240. if (tipText === '')
  241. return;
  242. $tip.html(tipText);
  243. plot.setTooltipPosition({ x: position.pageX, y: position.pageY });
  244. $tip.css({
  245. left: that.tipPosition.x + that.tooltipOptions.shifts.x,
  246. top: that.tipPosition.y + that.tooltipOptions.shifts.y
  247. }).show();
  248. // run callback
  249. if (typeof that.tooltipOptions.onHover === 'function') {
  250. that.tooltipOptions.onHover(target, $tip);
  251. }
  252. };
  253. // Quick little function for hiding the tooltip.
  254. plot.hideTooltip = function () {
  255. that.getDomElement().hide().html('');
  256. };
  257. plot.removeTooltip = function() {
  258. that.getDomElement().remove();
  259. };
  260. };
  261. /**
  262. * get or create tooltip DOM element
  263. * @return jQuery object
  264. */
  265. FlotTooltip.prototype.getDomElement = function () {
  266. var $tip = $('<div>');
  267. if (this.tooltipOptions && this.tooltipOptions.cssClass) {
  268. $tip = $('.' + this.tooltipOptions.cssClass);
  269. if( $tip.length === 0 ){
  270. $tip = $('<div />').addClass(this.tooltipOptions.cssClass);
  271. $tip.appendTo('body').hide().css({position: 'absolute'});
  272. if(this.tooltipOptions.defaultTheme) {
  273. $tip.css({
  274. 'background': '#fff',
  275. 'z-index': '1040',
  276. 'padding': '0.4em 0.6em',
  277. 'border-radius': '0.5em',
  278. 'font-size': '0.8em',
  279. 'border': '1px solid #111',
  280. 'display': 'none',
  281. 'white-space': 'nowrap'
  282. });
  283. }
  284. }
  285. }
  286. return $tip;
  287. };
  288. /**
  289. * core function, create tooltip content
  290. * @param {string} content - template with tooltip content
  291. * @param {object} item - Flot item
  292. * @return {string} real tooltip content for current item
  293. */
  294. FlotTooltip.prototype.stringFormat = function (content, item) {
  295. var percentPattern = /%p\.{0,1}(\d{0,})/;
  296. var seriesPattern = /%s/;
  297. var colorPattern = /%c/;
  298. var xLabelPattern = /%lx/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
  299. var yLabelPattern = /%ly/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
  300. var xPattern = /%x\.{0,1}(\d{0,})/;
  301. var yPattern = /%y\.{0,1}(\d{0,})/;
  302. var xPatternWithoutPrecision = "%x";
  303. var yPatternWithoutPrecision = "%y";
  304. var customTextPattern = "%ct";
  305. var nPiePattern = "%n";
  306. var x, y, customText, p, n;
  307. // for threshold plugin we need to read data from different place
  308. if (typeof item.series.threshold !== "undefined") {
  309. x = item.datapoint[0];
  310. y = item.datapoint[1];
  311. customText = item.datapoint[2];
  312. }
  313. // for CurvedLines plugin we need to read data from different place
  314. else if (typeof item.series.curvedLines !== "undefined") {
  315. x = item.datapoint[0];
  316. y = item.datapoint[1];
  317. }
  318. else if (typeof item.series.lines !== "undefined" && item.series.lines.steps) {
  319. x = item.series.datapoints.points[item.dataIndex * 2];
  320. y = item.series.datapoints.points[item.dataIndex * 2 + 1];
  321. // TODO: where to find custom text in this variant?
  322. customText = "";
  323. } else {
  324. x = item.series.data[item.dataIndex][0];
  325. y = item.series.data[item.dataIndex][1];
  326. customText = item.series.data[item.dataIndex][2];
  327. }
  328. // I think this is only in case of threshold plugin
  329. if (item.series.label === null && item.series.originSeries) {
  330. item.series.label = item.series.originSeries.label;
  331. }
  332. // if it is a function callback get the content string
  333. if (typeof(content) === 'function') {
  334. content = content(item.series.label, x, y, item);
  335. }
  336. // the case where the passed content is equal to false
  337. if (typeof(content) === 'boolean' && !content) {
  338. return '';
  339. }
  340. /* replacement of %ct and other multi-character templates must
  341. precede the replacement of single-character templates
  342. to avoid conflict between '%c' and '%ct' and similar substrings
  343. */
  344. if (customText)
  345. content = content.replace(customTextPattern, customText);
  346. // percent match for pie charts and stacked percent
  347. if (typeof (item.series.percent) !== 'undefined') {
  348. p = item.series.percent;
  349. } else if (typeof (item.series.percents) !== 'undefined') {
  350. p = item.series.percents[item.dataIndex];
  351. }
  352. if (typeof p === 'number') {
  353. content = this.adjustValPrecision(percentPattern, content, p);
  354. }
  355. // replace %n with number of items represented by slice in pie charts
  356. if (item.series.hasOwnProperty('pie')) {
  357. if (typeof (item.series.data[0][1] !== 'undefined')) {
  358. n = item.series.data[0][1];
  359. }
  360. }
  361. if (typeof n === 'number') {
  362. content = content.replace(nPiePattern, n);
  363. }
  364. // series match
  365. if (typeof(item.series.label) !== 'undefined') {
  366. content = content.replace(seriesPattern, item.series.label);
  367. } else {
  368. //remove %s if label is undefined
  369. content = content.replace(seriesPattern, "");
  370. }
  371. // color match
  372. if (typeof(item.series.color) !== 'undefined') {
  373. content = content.replace(colorPattern, item.series.color);
  374. } else {
  375. //remove %s if color is undefined
  376. content = content.replace(colorPattern, "");
  377. }
  378. // x axis label match
  379. if (this.hasAxisLabel('xaxis', item)) {
  380. content = content.replace(xLabelPattern, item.series.xaxis.options.axisLabel);
  381. } else {
  382. //remove %lx if axis label is undefined or axislabels plugin not present
  383. content = content.replace(xLabelPattern, "");
  384. }
  385. // y axis label match
  386. if (this.hasAxisLabel('yaxis', item)) {
  387. content = content.replace(yLabelPattern, item.series.yaxis.options.axisLabel);
  388. } else {
  389. //remove %ly if axis label is undefined or axislabels plugin not present
  390. content = content.replace(yLabelPattern, "");
  391. }
  392. // time mode axes with custom dateFormat
  393. if (this.isTimeMode('xaxis', item) && this.isXDateFormat(item)) {
  394. content = content.replace(xPattern, this.timestampToDate(x, this.tooltipOptions.xDateFormat, item.series.xaxis.options));
  395. }
  396. if (this.isTimeMode('yaxis', item) && this.isYDateFormat(item)) {
  397. content = content.replace(yPattern, this.timestampToDate(y, this.tooltipOptions.yDateFormat, item.series.yaxis.options));
  398. }
  399. // set precision if defined
  400. if (typeof x === 'number') {
  401. content = this.adjustValPrecision(xPattern, content, x);
  402. }
  403. if (typeof y === 'number') {
  404. content = this.adjustValPrecision(yPattern, content, y);
  405. }
  406. // change x from number to given label, if given
  407. if (typeof item.series.xaxis.ticks !== 'undefined') {
  408. var ticks;
  409. if (this.hasRotatedXAxisTicks(item)) {
  410. // xaxis.ticks will be an empty array if tickRotor is being used, but the values are available in rotatedTicks
  411. ticks = 'rotatedTicks';
  412. } else {
  413. ticks = 'ticks';
  414. }
  415. // see https://github.com/krzysu/flot.tooltip/issues/65
  416. var tickIndex = item.dataIndex + item.seriesIndex;
  417. for (var xIndex in item.series.xaxis[ticks]) {
  418. if (item.series.xaxis[ticks].hasOwnProperty(tickIndex) && !this.isTimeMode('xaxis', item)) {
  419. var valueX = (this.isCategoriesMode('xaxis', item)) ? item.series.xaxis[ticks][tickIndex].label : item.series.xaxis[ticks][tickIndex].v;
  420. if (valueX === x) {
  421. content = content.replace(xPattern, item.series.xaxis[ticks][tickIndex].label.replace(/\$/g, '$$$$'));
  422. }
  423. }
  424. }
  425. }
  426. // change y from number to given label, if given
  427. if (typeof item.series.yaxis.ticks !== 'undefined') {
  428. for (var yIndex in item.series.yaxis.ticks) {
  429. if (item.series.yaxis.ticks.hasOwnProperty(yIndex)) {
  430. var valueY = (this.isCategoriesMode('yaxis', item)) ? item.series.yaxis.ticks[yIndex].label : item.series.yaxis.ticks[yIndex].v;
  431. if (valueY === y) {
  432. content = content.replace(yPattern, item.series.yaxis.ticks[yIndex].label.replace(/\$/g, '$$$$'));
  433. }
  434. }
  435. }
  436. }
  437. // if no value customization, use tickFormatter by default
  438. if (typeof item.series.xaxis.tickFormatter !== 'undefined') {
  439. //escape dollar
  440. content = content.replace(xPatternWithoutPrecision, item.series.xaxis.tickFormatter(x, item.series.xaxis).replace(/\$/g, '$$'));
  441. }
  442. if (typeof item.series.yaxis.tickFormatter !== 'undefined') {
  443. //escape dollar
  444. content = content.replace(yPatternWithoutPrecision, item.series.yaxis.tickFormatter(y, item.series.yaxis).replace(/\$/g, '$$'));
  445. }
  446. return content;
  447. };
  448. // helpers just for readability
  449. FlotTooltip.prototype.isTimeMode = function (axisName, item) {
  450. return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'time');
  451. };
  452. FlotTooltip.prototype.isXDateFormat = function (item) {
  453. return (typeof this.tooltipOptions.xDateFormat !== 'undefined' && this.tooltipOptions.xDateFormat !== null);
  454. };
  455. FlotTooltip.prototype.isYDateFormat = function (item) {
  456. return (typeof this.tooltipOptions.yDateFormat !== 'undefined' && this.tooltipOptions.yDateFormat !== null);
  457. };
  458. FlotTooltip.prototype.isCategoriesMode = function (axisName, item) {
  459. return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'categories');
  460. };
  461. //
  462. FlotTooltip.prototype.timestampToDate = function (tmst, dateFormat, options) {
  463. var theDate = $.plot.dateGenerator(tmst, options);
  464. return $.plot.formatDate(theDate, dateFormat, this.tooltipOptions.monthNames, this.tooltipOptions.dayNames);
  465. };
  466. //
  467. FlotTooltip.prototype.adjustValPrecision = function (pattern, content, value) {
  468. var precision;
  469. var matchResult = content.match(pattern);
  470. if( matchResult !== null ) {
  471. if(RegExp.$1 !== '') {
  472. precision = RegExp.$1;
  473. value = value.toFixed(precision);
  474. // only replace content if precision exists, in other case use thickformater
  475. content = content.replace(pattern, value);
  476. }
  477. }
  478. return content;
  479. };
  480. // other plugins detection below
  481. // check if flot-axislabels plugin (https://github.com/markrcote/flot-axislabels) is used and that an axis label is given
  482. FlotTooltip.prototype.hasAxisLabel = function (axisName, item) {
  483. return ($.inArray('axisLabels', this.plotPlugins) !== -1 && typeof item.series[axisName].options.axisLabel !== 'undefined' && item.series[axisName].options.axisLabel.length > 0);
  484. };
  485. // check whether flot-tickRotor, a plugin which allows rotation of X-axis ticks, is being used
  486. FlotTooltip.prototype.hasRotatedXAxisTicks = function (item) {
  487. return ($.inArray('tickRotor',this.plotPlugins) !== -1 && typeof item.series.xaxis.rotatedTicks !== 'undefined');
  488. };
  489. //
  490. var init = function (plot) {
  491. new FlotTooltip(plot);
  492. };
  493. // define Flot plugin
  494. $.plot.plugins.push({
  495. init: init,
  496. options: defaultOptions,
  497. name: 'tooltip',
  498. version: '0.8.5'
  499. });
  500. })(jQuery);