jquery.flot.selection.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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();
  114. else {
  115. // this counts as a clear
  116. plot.getPlaceholder().trigger("plotunselected", [ ]);
  117. plot.getPlaceholder().trigger("plotselecting", [ null ]);
  118. }
  119. return false;
  120. }
  121. function getSelection() {
  122. if (!selectionIsSane())
  123. return null;
  124. if (!selection.show) return null;
  125. var r = {}, c1 = selection.first, c2 = selection.second;
  126. $.each(plot.getAxes(), function (name, axis) {
  127. if (axis.used) {
  128. var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
  129. r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
  130. }
  131. });
  132. return r;
  133. }
  134. function triggerSelectedEvent() {
  135. var r = getSelection();
  136. plot.getPlaceholder().trigger("plotselected", [ r ]);
  137. // backwards-compat stuff, to be removed in future
  138. if (r.xaxis && r.yaxis)
  139. plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
  140. }
  141. function clamp(min, value, max) {
  142. return value < min ? min: (value > max ? max: value);
  143. }
  144. function setSelectionPos(pos, e) {
  145. var o = plot.getOptions();
  146. var offset = plot.getPlaceholder().offset();
  147. var plotOffset = plot.getPlotOffset();
  148. pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
  149. pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
  150. if (o.selection.mode == "y")
  151. pos.x = pos == selection.first ? 0 : plot.width();
  152. if (o.selection.mode == "x")
  153. pos.y = pos == selection.first ? 0 : plot.height();
  154. }
  155. function updateSelection(pos) {
  156. if (pos.pageX == null)
  157. return;
  158. setSelectionPos(selection.second, pos);
  159. if (selectionIsSane()) {
  160. selection.show = true;
  161. plot.triggerRedrawOverlay();
  162. }
  163. else
  164. clearSelection(true);
  165. }
  166. function clearSelection(preventEvent) {
  167. if (selection.show) {
  168. selection.show = false;
  169. plot.triggerRedrawOverlay();
  170. if (!preventEvent)
  171. plot.getPlaceholder().trigger("plotunselected", [ ]);
  172. }
  173. }
  174. // function taken from markings support in Flot
  175. function extractRange(ranges, coord) {
  176. var axis, from, to, key, axes = plot.getAxes();
  177. for (var k in axes) {
  178. axis = axes[k];
  179. if (axis.direction == coord) {
  180. key = coord + axis.n + "axis";
  181. if (!ranges[key] && axis.n == 1)
  182. key = coord + "axis"; // support x1axis as xaxis
  183. if (ranges[key]) {
  184. from = ranges[key].from;
  185. to = ranges[key].to;
  186. break;
  187. }
  188. }
  189. }
  190. // backwards-compat stuff - to be removed in future
  191. if (!ranges[key]) {
  192. axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
  193. from = ranges[coord + "1"];
  194. to = ranges[coord + "2"];
  195. }
  196. // auto-reverse as an added bonus
  197. if (from != null && to != null && from > to) {
  198. var tmp = from;
  199. from = to;
  200. to = tmp;
  201. }
  202. return { from: from, to: to, axis: axis };
  203. }
  204. function setSelection(ranges, preventEvent) {
  205. var axis, range, o = plot.getOptions();
  206. if (o.selection.mode == "y") {
  207. selection.first.x = 0;
  208. selection.second.x = plot.width();
  209. }
  210. else {
  211. range = extractRange(ranges, "x");
  212. selection.first.x = range.axis.p2c(range.from);
  213. selection.second.x = range.axis.p2c(range.to);
  214. }
  215. if (o.selection.mode == "x") {
  216. selection.first.y = 0;
  217. selection.second.y = plot.height();
  218. }
  219. else {
  220. range = extractRange(ranges, "y");
  221. selection.first.y = range.axis.p2c(range.from);
  222. selection.second.y = range.axis.p2c(range.to);
  223. }
  224. selection.show = true;
  225. plot.triggerRedrawOverlay();
  226. if (!preventEvent && selectionIsSane())
  227. triggerSelectedEvent();
  228. }
  229. function selectionIsSane() {
  230. var minSize = plot.getOptions().selection.minSize;
  231. return Math.abs(selection.second.x - selection.first.x) >= minSize &&
  232. Math.abs(selection.second.y - selection.first.y) >= minSize;
  233. }
  234. plot.clearSelection = clearSelection;
  235. plot.setSelection = setSelection;
  236. plot.getSelection = getSelection;
  237. plot.hooks.bindEvents.push(function(plot, eventHolder) {
  238. var o = plot.getOptions();
  239. if (o.selection.mode != null) {
  240. eventHolder.mousemove(onMouseMove);
  241. eventHolder.mousedown(onMouseDown);
  242. }
  243. });
  244. plot.hooks.drawOverlay.push(function (plot, ctx) {
  245. // draw selection
  246. if (selection.show && selectionIsSane()) {
  247. var plotOffset = plot.getPlotOffset();
  248. var o = plot.getOptions();
  249. ctx.save();
  250. ctx.translate(plotOffset.left, plotOffset.top);
  251. var c = $.color.parse(o.selection.color);
  252. ctx.strokeStyle = c.scale('a', 0.8).toString();
  253. ctx.lineWidth = 1;
  254. ctx.lineJoin = o.selection.shape;
  255. ctx.fillStyle = c.scale('a', 0.4).toString();
  256. var x = Math.min(selection.first.x, selection.second.x) + 0.5,
  257. y = Math.min(selection.first.y, selection.second.y) + 0.5,
  258. w = Math.abs(selection.second.x - selection.first.x) - 1,
  259. h = Math.abs(selection.second.y - selection.first.y) - 1;
  260. ctx.fillRect(x, y, w, h);
  261. ctx.strokeRect(x, y, w, h);
  262. ctx.restore();
  263. }
  264. });
  265. plot.hooks.shutdown.push(function (plot, eventHolder) {
  266. eventHolder.unbind("mousemove", onMouseMove);
  267. eventHolder.unbind("mousedown", onMouseDown);
  268. if (mouseUpHandler)
  269. $(document).unbind("mouseup", mouseUpHandler);
  270. });
  271. }
  272. $.plot.plugins.push({
  273. init: init,
  274. options: {
  275. selection: {
  276. mode: null, // one of null, "x", "y" or "xy"
  277. color: "#e8cfac",
  278. shape: "round", // one of "round", "miter", or "bevel"
  279. minSize: 5 // minimum number of pixels
  280. }
  281. },
  282. name: 'selection',
  283. version: '1.1'
  284. });
  285. })(jQuery);