jquery.flot.selection.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /* Flot plugin for selecting regions of a plot.
  2. Copyright (c) 2007-2013 IOLA and Ole Laursen.
  3. Licensed under the MIT license.
  4. The plugin supports these options:
  5. selection: {
  6. mode: null or "x" or "y" or "xy",
  7. color: color,
  8. shape: "round" or "miter" or "bevel",
  9. minSize: number of pixels
  10. }
  11. Selection support is enabled by setting the mode to one of "x", "y" or "xy".
  12. In "x" mode, the user will only be able to specify the x range, similarly for
  13. "y" mode. For "xy", the selection becomes a rectangle where both ranges can be
  14. specified. "color" is color of the selection (if you need to change the color
  15. later on, you can get to it with plot.getOptions().selection.color). "shape"
  16. is the shape of the corners of the selection.
  17. "minSize" is the minimum size a selection can be in pixels. This value can
  18. be customized to determine the smallest size a selection can be and still
  19. have the selection rectangle be displayed. When customizing this value, the
  20. fact that it refers to pixels, not axis units must be taken into account.
  21. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
  22. minute, setting "minSize" to 1 will not make the minimum selection size 1
  23. minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
  24. "plotunselected" events from being fired when the user clicks the mouse without
  25. dragging.
  26. When selection support is enabled, a "plotselected" event will be emitted on
  27. the DOM element you passed into the plot function. The event handler gets a
  28. parameter with the ranges selected on the axes, like this:
  29. placeholder.bind( "plotselected", function( event, ranges ) {
  30. alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
  31. // similar for yaxis - with multiple axes, the extra ones are in
  32. // x2axis, x3axis, ...
  33. });
  34. The "plotselected" event is only fired when the user has finished making the
  35. selection. A "plotselecting" event is fired during the process with the same
  36. parameters as the "plotselected" event, in case you want to know what's
  37. happening while it's happening,
  38. A "plotunselected" event with no arguments is emitted when the user clicks the
  39. mouse to remove the selection. As stated above, setting "minSize" to 0 will
  40. destroy this behavior.
  41. The plugin allso adds the following methods to the plot object:
  42. - setSelection( ranges, preventEvent )
  43. Set the selection rectangle. The passed in ranges is on the same form as
  44. returned in the "plotselected" event. If the selection mode is "x", you
  45. should put in either an xaxis range, if the mode is "y" you need to put in
  46. an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
  47. this:
  48. setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
  49. setSelection will trigger the "plotselected" event when called. If you don't
  50. want that to happen, e.g. if you're inside a "plotselected" handler, pass
  51. true as the second parameter. If you are using multiple axes, you can
  52. specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
  53. xaxis, the plugin picks the first one it sees.
  54. - clearSelection( preventEvent )
  55. Clear the selection rectangle. Pass in true to avoid getting a
  56. "plotunselected" event.
  57. - getSelection()
  58. Returns the current selection in the same format as the "plotselected"
  59. event. If there's currently no selection, the function returns null.
  60. */
  61. (function ($) {
  62. function init(plot) {
  63. var selection = {
  64. first: { x: -1, y: -1}, second: { x: -1, y: -1},
  65. show: false,
  66. active: false
  67. };
  68. // FIXME: The drag handling implemented here should be
  69. // abstracted out, there's some similar code from a library in
  70. // the navigation plugin, this should be massaged a bit to fit
  71. // the Flot cases here better and reused. Doing this would
  72. // make this plugin much slimmer.
  73. var savedhandlers = {};
  74. var mouseUpHandler = null;
  75. function onMouseMove(e) {
  76. if (selection.active) {
  77. updateSelection(e);
  78. plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
  79. }
  80. }
  81. function onMouseDown(e) {
  82. if (e.which != 1) // only accept left-click
  83. return;
  84. // cancel out any text selections
  85. document.body.focus();
  86. // prevent text selection and drag in old-school browsers
  87. if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
  88. savedhandlers.onselectstart = document.onselectstart;
  89. document.onselectstart = function () { return false; };
  90. }
  91. if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
  92. savedhandlers.ondrag = document.ondrag;
  93. document.ondrag = function () { return false; };
  94. }
  95. setSelectionPos(selection.first, e);
  96. selection.active = true;
  97. // this is a bit silly, but we have to use a closure to be
  98. // able to whack the same handler again
  99. mouseUpHandler = function (e) { onMouseUp(e); };
  100. $(document).one("mouseup", mouseUpHandler);
  101. }
  102. function onMouseUp(e) {
  103. mouseUpHandler = null;
  104. // revert drag stuff for old-school browsers
  105. if (document.onselectstart !== undefined)
  106. document.onselectstart = savedhandlers.onselectstart;
  107. if (document.ondrag !== undefined)
  108. document.ondrag = savedhandlers.ondrag;
  109. // no more dragging
  110. selection.active = false;
  111. updateSelection(e);
  112. if (selectionIsSane())
  113. triggerSelectedEvent(e);
  114. else {
  115. // this counts as a clear
  116. plot.getPlaceholder().trigger("plotunselected", [ ]);
  117. plot.getPlaceholder().trigger("plotselecting", [ null ]);
  118. }
  119. setTimeout(function() {
  120. plot.isSelecting = false;
  121. }, 10);
  122. return false;
  123. }
  124. function getSelection() {
  125. if (!selectionIsSane())
  126. return null;
  127. if (!selection.show) return null;
  128. var r = {}, c1 = selection.first, c2 = selection.second;
  129. var axes = plot.getAxes();
  130. // look if no axis is used
  131. var noAxisInUse = true;
  132. $.each(axes, function (name, axis) {
  133. if (axis.used) {
  134. anyUsed = false;
  135. }
  136. })
  137. $.each(axes, function (name, axis) {
  138. if (axis.used || noAxisInUse) {
  139. var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
  140. r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
  141. }
  142. });
  143. return r;
  144. }
  145. function triggerSelectedEvent(event) {
  146. var r = getSelection();
  147. // Add ctrlKey and metaKey to event
  148. r.ctrlKey = event.ctrlKey;
  149. r.metaKey = event.metaKey;
  150. plot.getPlaceholder().trigger("plotselected", [ r ]);
  151. // backwards-compat stuff, to be removed in future
  152. if (r.xaxis && r.yaxis)
  153. plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
  154. }
  155. function clamp(min, value, max) {
  156. return value < min ? min: (value > max ? max: value);
  157. }
  158. function setSelectionPos(pos, e) {
  159. var o = plot.getOptions();
  160. var offset = plot.getPlaceholder().offset();
  161. var plotOffset = plot.getPlotOffset();
  162. pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
  163. pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
  164. if (o.selection.mode == "y")
  165. pos.x = pos == selection.first ? 0 : plot.width();
  166. if (o.selection.mode == "x")
  167. pos.y = pos == selection.first ? 0 : plot.height();
  168. }
  169. function updateSelection(pos) {
  170. if (pos.pageX == null)
  171. return;
  172. setSelectionPos(selection.second, pos);
  173. if (selectionIsSane()) {
  174. plot.isSelecting = true;
  175. selection.show = true;
  176. plot.triggerRedrawOverlay();
  177. }
  178. else
  179. clearSelection(true);
  180. }
  181. function clearSelection(preventEvent) {
  182. if (selection.show) {
  183. selection.show = false;
  184. plot.triggerRedrawOverlay();
  185. if (!preventEvent)
  186. plot.getPlaceholder().trigger("plotunselected", [ ]);
  187. }
  188. }
  189. // function taken from markings support in Flot
  190. function extractRange(ranges, coord) {
  191. var axis, from, to, key, axes = plot.getAxes();
  192. for (var k in axes) {
  193. axis = axes[k];
  194. if (axis.direction == coord) {
  195. key = coord + axis.n + "axis";
  196. if (!ranges[key] && axis.n == 1)
  197. key = coord + "axis"; // support x1axis as xaxis
  198. if (ranges[key]) {
  199. from = ranges[key].from;
  200. to = ranges[key].to;
  201. break;
  202. }
  203. }
  204. }
  205. // backwards-compat stuff - to be removed in future
  206. if (!ranges[key]) {
  207. axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
  208. from = ranges[coord + "1"];
  209. to = ranges[coord + "2"];
  210. }
  211. // auto-reverse as an added bonus
  212. if (from != null && to != null && from > to) {
  213. var tmp = from;
  214. from = to;
  215. to = tmp;
  216. }
  217. return { from: from, to: to, axis: axis };
  218. }
  219. function setSelection(ranges, preventEvent) {
  220. var axis, range, o = plot.getOptions();
  221. if (o.selection.mode == "y") {
  222. selection.first.x = 0;
  223. selection.second.x = plot.width();
  224. }
  225. else {
  226. range = extractRange(ranges, "x");
  227. selection.first.x = range.axis.p2c(range.from);
  228. selection.second.x = range.axis.p2c(range.to);
  229. }
  230. if (o.selection.mode == "x") {
  231. selection.first.y = 0;
  232. selection.second.y = plot.height();
  233. }
  234. else {
  235. range = extractRange(ranges, "y");
  236. selection.first.y = range.axis.p2c(range.from);
  237. selection.second.y = range.axis.p2c(range.to);
  238. }
  239. selection.show = true;
  240. plot.triggerRedrawOverlay();
  241. if (!preventEvent && selectionIsSane())
  242. triggerSelectedEvent();
  243. }
  244. function selectionIsSane() {
  245. var minSize = plot.getOptions().selection.minSize;
  246. return Math.abs(selection.second.x - selection.first.x) >= minSize &&
  247. Math.abs(selection.second.y - selection.first.y) >= minSize;
  248. }
  249. plot.clearSelection = clearSelection;
  250. plot.setSelection = setSelection;
  251. plot.getSelection = getSelection;
  252. plot.hooks.bindEvents.push(function(plot, eventHolder) {
  253. var o = plot.getOptions();
  254. if (o.selection.mode != null) {
  255. eventHolder.mousemove(onMouseMove);
  256. eventHolder.mousedown(onMouseDown);
  257. }
  258. });
  259. plot.hooks.drawOverlay.push(function (plot, ctx) {
  260. // draw selection
  261. if (selection.show && selectionIsSane()) {
  262. var plotOffset = plot.getPlotOffset();
  263. var o = plot.getOptions();
  264. ctx.save();
  265. ctx.translate(plotOffset.left, plotOffset.top);
  266. var c = $.color.parse(o.selection.color);
  267. ctx.strokeStyle = c.scale('a', 0.8).toString();
  268. ctx.lineWidth = 1;
  269. ctx.lineJoin = o.selection.shape;
  270. ctx.fillStyle = c.scale('a', 0.4).toString();
  271. var x = Math.min(selection.first.x, selection.second.x) + 0.5,
  272. y = Math.min(selection.first.y, selection.second.y) + 0.5,
  273. w = Math.abs(selection.second.x - selection.first.x) - 1,
  274. h = Math.abs(selection.second.y - selection.first.y) - 1;
  275. ctx.fillRect(x, y, w, h);
  276. ctx.strokeRect(x, y, w, h);
  277. ctx.restore();
  278. }
  279. });
  280. plot.hooks.shutdown.push(function (plot, eventHolder) {
  281. eventHolder.unbind("mousemove", onMouseMove);
  282. eventHolder.unbind("mousedown", onMouseDown);
  283. if (mouseUpHandler) {
  284. $(document).unbind("mouseup", mouseUpHandler);
  285. // grafana addition
  286. // In L114 this plugin is overrinding document.onselectstart handler to prevent default or custom behaviour
  287. // Then this patch is being restored during mouseup event. But, mouseup handler is unbound when this plugin is destroyed
  288. // and the overridden onselectstart handler is not restored. The problematic behaviour surfaces when flot is re-rendered
  289. // as a consequence of panel's model update. When i.e. options are applied via onBlur
  290. // event on some input which results in flot re-render. The mouseup handler should be called to resture the original handlers
  291. // but by the time the document mouseup event occurs, the event handler is no longer there, so onselectstart is permanently overridden.
  292. // To fix that we are making sure that the overrides are reverted when this plugin is destroyed, the same way as they would
  293. // via mouseup event handler (L138)
  294. if (document.onselectstart !== undefined)
  295. document.onselectstart = savedhandlers.onselectstart;
  296. if (document.ondrag !== undefined)
  297. document.ondrag = savedhandlers.ondrag;
  298. }
  299. });
  300. }
  301. $.plot.plugins.push({
  302. init: init,
  303. options: {
  304. selection: {
  305. mode: null, // one of null, "x", "y" or "xy"
  306. color: "#e8cfac",
  307. shape: "round", // one of "round", "miter", or "bevel"
  308. minSize: 5 // minimum number of pixels
  309. }
  310. },
  311. name: 'selection',
  312. version: '1.1'
  313. });
  314. })(jQuery);