jquery.flot.selection.js 12 KB

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