jquery.jsPlumb-1.0.4-RC1.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /*
  2. * jsPlumb 1.0.4-RC1
  3. *
  4. * Provides a way to visually connect elements on an HTML page.
  5. *
  6. * http://morrisonpitt.com/jsPlumb/demo.html
  7. * http://code.google.com/p/jsPlumb
  8. *
  9. */
  10. if (!Array.prototype.indexOf) {
  11. Array.prototype.indexOf = function( v, b, s ) {
  12. for( var i = +b || 0, l = this.length; i < l; i++ ) {
  13. if( this[i]===v || s && this[i]==v ) { return i; }
  14. }
  15. return -1;
  16. };
  17. }
  18. (function() {
  19. var repaintFunction = function() { jsPlumb.repaintEverything(); };
  20. var automaticRepaint = true;
  21. function repaintEverything() {
  22. if (automaticRepaint)
  23. repaintFunction();
  24. };
  25. var resizeTimer = null;
  26. $(window).bind('resize', function() {
  27. if (resizeTimer) clearTimeout(resizeTimer);
  28. resizeTimer = setTimeout(repaintEverything, 100);
  29. });
  30. var connections = {};
  31. var draggableStates = {};
  32. var _draggableByDefault = true;
  33. var offsets = [];
  34. var sizes = [];
  35. var DEFAULT_NEW_CANVAS_SIZE = 1200; // only used for IE; a canvas needs a size before the init call to excanvas (for some reason. no idea why.)
  36. /**
  37. * applies all the styles to the given context. this just wraps the $.extend function.
  38. *
  39. * @param context
  40. * @param styles
  41. */
  42. var applyPaintStyle = function(context, styles) {
  43. $.extend(context, styles);
  44. };
  45. /**
  46. * Handles the drawing of an element.
  47. * @param element jQuery element
  48. * @param ui UI object from jQuery's event system. may be null.
  49. */
  50. var _draw = function(element, ui) {
  51. var id = element.attr("id");
  52. var l = connections[id];
  53. for (var i = 0; i < l.length; i++)
  54. l[i].paint(id, ui);
  55. };
  56. /**
  57. * Sets whether or not the given element(s) should be draggable, regardless of what a particular
  58. * plumb command may request.
  59. *
  60. * @param element May be a string, an jQuery object, or a list of strings.
  61. * @param draggable Whether or not the given element(s) should be draggable.
  62. */
  63. var _setDraggable = function(element, draggable) {
  64. var _helper = function(el, id) {
  65. draggableStates[id] = draggable;
  66. if (el.draggable) {
  67. el.draggable("option", "disabled", !draggable);
  68. }
  69. };
  70. if (typeof element == 'object' && element.length) {
  71. for (var i = 0; i < element.length; i++) {
  72. _helper($(element[i]), element[i]);
  73. }
  74. }
  75. else {
  76. var el = typeof element == 'string' ? $("#" + element) : element;
  77. var id = el.attr("id");
  78. _helper(el, id);
  79. }
  80. };
  81. /**
  82. * private method to do the business of hiding/showing.
  83. * @param elId Id of the element in question
  84. * @param state String specifying a value for the css 'display' property ('block' or 'none').
  85. */
  86. var _setVisible = function(elId, state) {
  87. var jpcs = connections[elId];
  88. for (var i = 0; i < jpcs.length; i++) {
  89. jpcs[i].canvas.style.display=state;
  90. if (jpcs[i].drawEndpoints) {
  91. jpcs[i].sourceEndpointCanvas.style.display=state;
  92. jpcs[i].targetEndpointCanvas.style.display=state;
  93. }
  94. }
  95. };
  96. /**
  97. * helper to create a canvas.
  98. * @param clazz optional class name for the canvas.
  99. */
  100. var _newCanvas = function(clazz) {
  101. var canvas = document.createElement("canvas");
  102. document.body.appendChild(canvas);
  103. canvas.style.position="absolute";
  104. if (clazz) { canvas.className=clazz; }
  105. if (/MSIE/.test(navigator.userAgent) && !window.opera) {
  106. // for IE we have to set a big canvas size. actually you can override this, too, if 1200 pixels
  107. // is not big enough for the biggest connector/endpoint canvas you have at startup.
  108. jsPlumb.sizeCanvas(canvas, 0, 0, DEFAULT_NEW_CANVAS_SIZE, DEFAULT_NEW_CANVAS_SIZE);
  109. canvas = G_vmlCanvasManager.initElement(canvas);
  110. }
  111. return canvas;
  112. };
  113. /**
  114. * helper to remove a canvas from the DOM.
  115. */
  116. var _removeCanvas = function(canvas) {
  117. if (canvas != null) {
  118. try { document.body.removeChild(canvas); }
  119. catch (e) { }
  120. }
  121. };
  122. /**
  123. * generic anchor - can be situated anywhere. params should contain three values, and may optionally have an 'offsets' argument:
  124. *
  125. * x - the x location of the anchor as a percentage of the total width.
  126. * y - the y location of the anchor as a percentage of the total height.
  127. * orientation - an [x,y] array indicating the general direction a connection from the anchor should go in.
  128. * offsets - an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out. may be null.
  129. *
  130. */
  131. var Anchor = function(params) {
  132. var self = this;
  133. this.x = params.x || 0; this.y = params.y || 0; this.orientation = params.orientation || [0,0]; this.offsets = params.offsets || [0,0];
  134. this.compute = function(xy, wh, txy, twh) {
  135. return [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  136. }
  137. };
  138. /**
  139. * jsPlumb public API
  140. */
  141. var jsPlumb = window.jsPlumb = {
  142. connectorClass : '_jsPlumb_connector',
  143. endpointClass : '_jsPlumb_endpoint',
  144. DEFAULT_PAINT_STYLE : { lineWidth : 10, strokeStyle : "red" },
  145. DEFAULT_ENDPOINT_STYLE : { fillStyle : null }, // meaning it will be derived from the stroke style of the connector.
  146. DEFAULT_ENDPOINT_STYLES : [ null, null ], // meaning it will be derived from the stroke style of the connector.
  147. DEFAULT_DRAG_OPTIONS : { },
  148. DEFAULT_CONNECTOR : null,
  149. DEFAULT_ENDPOINT : null,
  150. DEFAULT_ENDPOINTS : [null, null], // new in 0.0.4, the ability to specify diff. endpoints. DEFAULT_ENDPOINT is here for backwards compatibility.
  151. /**
  152. * Places you can anchor a connection to. These are helpers for common locations; they all just return an instance
  153. * of Anchor that has been configured appropriately.
  154. *
  155. * You can write your own one of these; you
  156. * just need to provide a 'compute' method and an 'orientation'. so you'd say something like this:
  157. *
  158. * jsPlumb.Anchors.MY_ANCHOR = {
  159. * compute : function(xy, wh, txy, twh) { return some mathematics on those variables; },
  160. * orientation : [ox, oy]
  161. * };
  162. *
  163. * compute takes the [x,y] position of the top left corner of the anchored element,
  164. * and the element's [width,height] (all in pixels), as well as the location and dimension of the element it's plumbed to,
  165. * and returns where the anchor should be located.
  166. *
  167. * the 'orientation' array (returned here as [ox,oy]) indicates the general direction a connection from the anchor
  168. * should go in, if possible. it is an [x,y] matrix where a value of 0 means no preference,
  169. * -1 means go in a negative direction for the given axis, and 1 means go in a positive
  170. * direction. so consider a TopCenter anchor: the orientation matrix for it is [0,-1],
  171. * meaning connections naturally want to go upwards on screen. in a Bezier implementation, for example,
  172. * the curve would start out going in that direction, before bending towards the target anchor.
  173. */
  174. Anchors :
  175. {
  176. TopCenter : new Anchor({x:0.5, y:0, orientation:[0,-1] }),
  177. BottomCenter : new Anchor({x:0.5, y:1, orientation:[0, 1] }),
  178. LeftMiddle: new Anchor({x:0, y:0.5, orientation:[-1,0] }),
  179. RightMiddle : new Anchor({x:1, y:0.5, orientation:[1,0] }),
  180. Center : new Anchor({x:0.5, y:0.5, orientation:[0,0] }),
  181. TopRight : new Anchor({x:1, y:0, orientation:[0,-1] }),
  182. BottomRight : new Anchor({x:1, y:1, orientation:[0,1] }),
  183. TopLeft : new Anchor({x:0, y:0, orientation:[0,-1] }),
  184. BottomLeft : new Anchor({x:0, y:1, orientation:[0,1] })
  185. },
  186. /**
  187. * Types of connectors, eg. Straight, Bezier.
  188. */
  189. Connectors :
  190. {
  191. /**
  192. * The Straight connector draws a simple straight line between the two anchor points.
  193. */
  194. Straight : function() {
  195. var self = this;
  196. /**
  197. * Computes the new size and position of the canvas.
  198. * @param sourceAnchor Absolute position on screen of the source object's anchor.
  199. * @param targetAnchor Absolute position on screen of the target object's anchor.
  200. * @param positionMatrix Indicates the relative positions of the left,top of the
  201. * two plumbed objects. so [0,0] indicates that the source is to the left of, and
  202. * above, the target. [1,0] means the source is to the right and above. [0,1] means
  203. * the source is to the left and below. [1,1] means the source is to the right
  204. * and below. this is used to figure out which direction to draw the connector in.
  205. * @returns an array of positioning information. the first two values are
  206. * the [left, top] absolute position the canvas should be placed on screen. the
  207. * next two values are the [width,height] the canvas should be. after that each
  208. * Connector can put whatever it likes into the array:it will be passed back in
  209. * to the paint call. This particular function stores the origin and destination of
  210. * the line it is going to draw. a more involved implementation, like a Bezier curve,
  211. * would store the control point info in this array too.
  212. */
  213. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth) {
  214. var w = Math.abs(sourcePos[0] - targetPos[0]);
  215. var h = Math.abs(sourcePos[1] - targetPos[1]);
  216. // these are padding to ensure the whole connector line appears
  217. var xo = 0.45 * w, yo = 0.45 * h;
  218. // these are padding to ensure the whole connector line appears
  219. w *= 1.9; h *=1.9;
  220. var x = Math.min(sourcePos[0], targetPos[0]) - xo;
  221. var y = Math.min(sourcePos[1], targetPos[1]) - yo;
  222. if (w < 2 * lineWidth) {
  223. // minimum size is 2 * line Width
  224. w = 2 * lineWidth;
  225. // if we set this then we also have to place the canvas
  226. x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - lineWidth;
  227. xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;;
  228. }
  229. if (h < 2 * lineWidth) {
  230. // minimum size is 2 * line Width
  231. h = 2 * lineWidth;
  232. // if we set this then we also have to place the canvas
  233. y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - lineWidth;
  234. yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;;
  235. }
  236. var sx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  237. var sy = sourcePos[1] < targetPos[1] ? h-yo : yo;
  238. var tx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  239. var ty = sourcePos[1] < targetPos[1] ? yo : h-yo;
  240. var retVal = [ x, y, w, h, sx, sy, tx, ty ];
  241. // return [canvasX, canvasY, canvasWidth, canvasHeight,
  242. // sourceX, sourceY, targetX, targetY]
  243. return retVal;
  244. };
  245. this.paint = function(dimensions, ctx)
  246. {
  247. ctx.beginPath();
  248. ctx.moveTo(dimensions[4], dimensions[5]);
  249. ctx.lineTo(dimensions[6], dimensions[7]);
  250. ctx.stroke();
  251. };
  252. },
  253. /**
  254. * This Connector draws a Bezier curve with two control points.
  255. * @param curviness How 'curvy' you want the curve to be! This is a directive for the
  256. * placement of control points, not endpoints of the curve, so your curve does not
  257. * actually touch the given point, but it has the tendency to lean towards it. the larger
  258. * this value, the greater the curve is pulled from a straight line.
  259. *
  260. * a future implementation of this could take the control points as arguments, rather
  261. * than fixing the curve to one basic shape.
  262. */
  263. Bezier : function(curviness) {
  264. var self = this;
  265. this.majorAnchor = curviness || 150;
  266. this.minorAnchor = 10;
  267. this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
  268. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  269. // points around if so (code could be tightened up)
  270. var perpendicular = sourceAnchor.orientation[0] != targetAnchor.orientation[0] || sourceAnchor.orientation[1] == targetAnchor.orientation[1];
  271. var p = [];
  272. var ma = self.majorAnchor, mi = self.minorAnchor;
  273. if (!perpendicular) {
  274. if (sourceAnchor.orientation[0] == 0) // X
  275. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  276. else p.push(point[0] - (ma * sourceAnchor.orientation[0]));
  277. if (sourceAnchor.orientation[1] == 0) // Y
  278. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  279. else p.push(point[1] + (ma * targetAnchor.orientation[1]));
  280. }
  281. else {
  282. if (targetAnchor.orientation[0] == 0) // X
  283. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  284. else p.push(point[0] + (ma * targetAnchor.orientation[0]));
  285. if (targetAnchor.orientation[1] == 0) // Y
  286. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  287. else p.push(point[1] + (ma * sourceAnchor.orientation[1]));
  288. }
  289. return p;
  290. };
  291. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth)
  292. {
  293. lineWidth = lineWidth || 0;
  294. var w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth, h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  295. var canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2), canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  296. var sx = sourcePos[0] < targetPos[0] ? w - (lineWidth/2): (lineWidth/2), sy = sourcePos[1] < targetPos[1] ? h-(lineWidth/2) : (lineWidth/2);
  297. var tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : w-(lineWidth/2), ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : h-(lineWidth/2);
  298. var CP = self._findControlPoint([sx,sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
  299. var CP2 = self._findControlPoint([tx,ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
  300. var minx1 = Math.min(sx,tx); var minx2 = Math.min(CP[0], CP2[0]); var minx = Math.min(minx1,minx2);
  301. var maxx1 = Math.max(sx,tx); var maxx2 = Math.max(CP[0], CP2[0]); var maxx = Math.max(maxx1,maxx2);
  302. if (maxx > w) w = maxx;
  303. if (minx < 0) {
  304. canvasX += minx; var ox = Math.abs(minx);
  305. w += ox; CP[0] += ox; sx += ox; tx +=ox; CP2[0] += ox;
  306. }
  307. var miny1 = Math.min(sy,ty); var miny2 = Math.min(CP[1], CP2[1]); var miny = Math.min(miny1,miny2);
  308. var maxy1 = Math.max(sy,ty); var maxy2 = Math.max(CP[1], CP2[1]); var maxy = Math.max(maxy1,maxy2);
  309. if (maxy > h) h = maxy;
  310. if (miny < 0) {
  311. canvasY += miny; var oy = Math.abs(miny);
  312. h += oy; CP[1] += oy; sy += oy; ty +=oy; CP2[1] += oy;
  313. }
  314. // return [ canvasx, canvasy, canvasWidth, canvasHeight,
  315. // sourceX, sourceY, targetX, targetY,
  316. // controlPoint1_X, controlPoint1_Y, controlPoint2_X, controlPoint2_Y
  317. return [canvasX, canvasY, w, h, sx, sy, tx, ty, CP[0], CP[1], CP2[0], CP2[1] ];
  318. };
  319. this.paint = function(d, ctx) {
  320. ctx.beginPath();
  321. ctx.moveTo(d[4],d[5]);
  322. ctx.bezierCurveTo(d[8],d[9],d[10],d[11],d[6],d[7]);
  323. ctx.stroke();
  324. }
  325. }
  326. },
  327. /**
  328. * Types of endpoint UIs. we supply three - a circle of default radius 10px, a rectangle of
  329. * default size 20x20, and an image (with no default). you can supply others of these if you want to - see the documentation
  330. * for a howto.
  331. */
  332. Endpoints : {
  333. /**
  334. * a round endpoint, with default radius 10 pixels.
  335. */
  336. Dot : function(params) {
  337. params = params || { radius:10 };
  338. var self = this;
  339. this.radius = params.radius;
  340. var defaultOffset = 0.5 * this.radius;
  341. var defaultInnerRadius = this.radius / 3;
  342. var parseValue = function(value) {
  343. try {
  344. return parseInt(value);
  345. }
  346. catch(e) {
  347. if (value.substring(value.length - 1) == '%')
  348. return parseInt(value.substring(0, value - 1));
  349. }
  350. }
  351. var calculateAdjustments = function(gradient) {
  352. var offsetAdjustment = defaultOffset;
  353. var innerRadius = defaultInnerRadius;
  354. if (gradient.offset) offsetAdjustment = parseValue(gradient.offset);
  355. if(gradient.innerRadius) innerRadius = parseValue(gradient.innerRadius);
  356. return [offsetAdjustment, innerRadius];
  357. };
  358. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  359. var radius = endpointStyle.radius || self.radius;
  360. var x = anchorPoint[0] - radius;
  361. var y = anchorPoint[1] - radius;
  362. jsPlumb.sizeCanvas(canvas, x, y, radius * 2, radius * 2);
  363. var ctx = canvas.getContext('2d');
  364. var style = {};
  365. applyPaintStyle(style, endpointStyle);
  366. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  367. applyPaintStyle(ctx, style);
  368. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  369. if (endpointStyle.gradient && !ie) {
  370. var adjustments = calculateAdjustments(endpointStyle.gradient);
  371. var yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0];
  372. var xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0];
  373. var g = ctx.createRadialGradient(radius, radius, radius, radius + xAdjust, radius + yAdjust, adjustments[1]);
  374. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  375. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  376. ctx.fillStyle = g;
  377. }
  378. ctx.beginPath();
  379. ctx.arc(radius, radius, radius, 0, Math.PI*2, true);
  380. ctx.closePath();
  381. ctx.fill();
  382. };
  383. },
  384. /**
  385. * A Rectangular endpoint, with default size 20x20.
  386. */
  387. Rectangle : function(params) {
  388. params = params || { width:20, height:20 };
  389. var self = this;
  390. this.width = params.width;
  391. this.height = params.height;
  392. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  393. var width = endpointStyle.width || self.width;
  394. var height = endpointStyle.height || self.height;
  395. var x = anchorPoint[0] - (width/2);
  396. var y = anchorPoint[1] - (height/2);
  397. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  398. var ctx = canvas.getContext('2d');
  399. //todo: the fillStyle needs some thought. we want to support a few options:
  400. // 1. nothing supplied; use the stroke color or the default if no stroke color.
  401. // 2. a fill color supplied - use it
  402. // 3. a gradient supplied - use it
  403. // 4. setting the endpoint to the same color as the bg of the element it is attached to.
  404. var style = {};
  405. applyPaintStyle(style, endpointStyle);
  406. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  407. applyPaintStyle(ctx, style);
  408. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  409. if (endpointStyle.gradient && !ie) {
  410. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  411. var y1 = orientation[1] == 1 ? height : orientation[1] == 0 ? height / 2 : 0;
  412. var y2 = orientation[1] == -1 ? height : orientation[1] == 0 ? height / 2 : 0;
  413. var x1 = orientation[0] == 1 ? width : orientation[0] == 0 ? width / 2 : 0;
  414. var x2 = orientation[0] == -1 ? width : orientation[0] == 0 ? height / 2 : 0;
  415. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  416. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  417. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  418. ctx.fillStyle = g;
  419. }
  420. ctx.beginPath();
  421. ctx.rect(0, 0, width, height);
  422. ctx.closePath();
  423. ctx.fill();
  424. };
  425. },
  426. /**
  427. * Image endpoint - draws an image as the endpoint. You must provide a 'url' property in the params object..
  428. */
  429. Image : function(params) {
  430. var self = this;
  431. this.img = new Image();
  432. var ready = false;
  433. this.img.onload = function() {
  434. self.ready = true;
  435. };
  436. this.img.src = params.url;
  437. var actuallyPaint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  438. var width = self.img.width || endpointStyle.width;
  439. var height = self.img.height || endpointStyle.height;
  440. var x = anchorPoint[0] - (width/2);
  441. var y = anchorPoint[1] - (height/2);
  442. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  443. var ctx = canvas.getContext('2d');
  444. ctx.drawImage(self.img,0,0);
  445. };
  446. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  447. if (self.ready) {
  448. actuallyPaint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
  449. }
  450. else
  451. window.setTimeout(function() {
  452. self.paint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle);
  453. }, 200);
  454. };
  455. }
  456. },
  457. /**
  458. * establishes a connection between two elements.
  459. * @param params object containing setup for the connection. see documentation.
  460. */
  461. connect : function(params) {
  462. var jpc = new jsPlumbConnection(params);
  463. var key = jpc.sourceId + "_" + jpc.targetId;
  464. connections[key] = jpc;
  465. var addToList = function(elId, jpc) {
  466. var l = connections[elId];
  467. if (l == null) {
  468. l = [];
  469. connections[elId] = l;
  470. }
  471. l.push(jpc);
  472. };
  473. // register this connection.
  474. addToList(jpc.sourceId, jpc);
  475. addToList(jpc.targetId, jpc);
  476. },
  477. /**
  478. * Remove one connection to an element.
  479. * @param sourceId id of the first window in the connection
  480. * @param targetId id of the second window in the connection
  481. */
  482. detach : function(sourceId, targetId) {
  483. var jpcs = connections[sourceId];
  484. var idx = -1;
  485. for (var i = 0; i < jpcs.length; i++) {
  486. if ((jpcs[i].sourceId == sourceId && jpcs[i].targetId == targetId) || (jpcs[i].targetId == sourceId && jpcs[i].sourceId == targetId)) {
  487. _removeCanvas(jpcs[i].canvas);
  488. if (jpcs[i].drawEndpoints) {
  489. _removeCanvas(jpcs[i].targetEndpointCanvas);
  490. _removeCanvas(jpcs[i].sourceEndpointCanvas);
  491. }
  492. idx = i;
  493. break;
  494. }
  495. }
  496. if (idx != -1)
  497. jpcs.splice(idx, 1);
  498. // todo - dragging? if no more connections for an object turn off dragging by default, but
  499. // allow an override on it?
  500. },
  501. /**
  502. * remove all an element's connections.
  503. */
  504. detachAll : function(elId) {
  505. var jpcs = connections[elId];
  506. for (var i = 0; i < jpcs.length; i++) {
  507. _removeCanvas(jpcs[i].canvas);
  508. if (jpcs[i].drawEndpoints) {
  509. _removeCanvas(jpcs[i].targetEndpointCanvas);
  510. _removeCanvas(jpcs[i].sourceEndpointCanvas);
  511. }
  512. }
  513. delete connections[elId];
  514. connections[elId] = [];
  515. },
  516. /**
  517. * remove all connections.
  518. */
  519. detachEverything : function() {
  520. for (var elId in connections) {
  521. var jpcs = connections[elId];
  522. if (jpcs.length) {
  523. try {
  524. for (var i = 0; i < jpcs.length; i++) {
  525. _removeCanvas(jpcs[i].canvas);
  526. if (jpcs[i].drawEndpoints) {
  527. _removeCanvas(jpcs[i].targetEndpointCanvas);
  528. _removeCanvas(jpcs[i].sourceEndpointCanvas);
  529. }
  530. }
  531. } catch (e) { }
  532. }
  533. }
  534. delete connections;
  535. connections = [];
  536. },
  537. getConnections : function(elId) {
  538. return connections[elId];
  539. },
  540. /**
  541. * Set an element's connections to be hidden.
  542. */
  543. hide : function(elId) {
  544. _setVisible(elId, "none");
  545. },
  546. /**
  547. * Creates an anchor with the given params.
  548. * x - the x location of the anchor as a percentage of the total width.
  549. * y - the y location of the anchor as a percentage of the total height.
  550. * orientation - an [x,y] array indicating the general direction a connection from the anchor should go in.
  551. * offsets - an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out. optional. defaults to [0,0].
  552. */
  553. makeAnchor : function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  554. // backwards compatibility here. we used to require an object passed in but that makes the call very verbose. easier to use
  555. // by just passing in four values. but for backwards compatibility if we are given only one value we assume it's a call in the old form.
  556. var params = {};
  557. if (arguments.length == 1) $.extend(params, x);
  558. else {
  559. params = {x:x, y:y};
  560. if (arguments.length >= 4) {
  561. params.orientation = [arguments[2], arguments[3]];
  562. }
  563. if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
  564. }
  565. return new Anchor(params);
  566. },
  567. /**
  568. * repaint element and its connections. element may be an id or the actual jQuery object.
  569. * this method gets new sizes for the elements before painting anything.
  570. */
  571. repaint : function(el) {
  572. var _repaint = function(el, elId) {
  573. var jpcs = connections[elId];
  574. var idx = -1;
  575. var loc = {'absolutePosition': el.offset()};
  576. for (var i = 0; i < jpcs.length; i++) {
  577. jpcs[i].paint(elId, loc, true);
  578. }
  579. };
  580. var _processElement = function(el) {
  581. var ele = typeof(el)=='string' ? $("#" + el) : el;
  582. var eleId = ele.attr("id");
  583. _repaint(ele, eleId);
  584. };
  585. // TODO: support a jQuery result object too!
  586. // support both lists...
  587. if (typeof el =='object') {
  588. for (var i = 0; i < el.length; i++)
  589. _processElement(el[i]);
  590. } // ...and single strings.
  591. else _processElement(el);
  592. },
  593. /**
  594. * repaint all connections.
  595. */
  596. repaintEverything : function() {
  597. for (var elId in connections) {
  598. var jpcs = connections[elId];
  599. if (jpcs.length) {
  600. try {
  601. for (var i = 0; i < jpcs.length; i++) {
  602. jpcs[i].repaint();
  603. }
  604. } catch (e) { }
  605. }
  606. }
  607. },
  608. /**
  609. * sets/unsets automatic repaint on window resize.
  610. */
  611. setAutomaticRepaint : function(value) {
  612. automaticRepaint = value;
  613. },
  614. /**
  615. * Sets the default size jsPlumb will use for a new canvas (we create a square canvas so
  616. * one value is all that is required). This is a hack for IE, because ExplorerCanvas seems
  617. * to need for a canvas to be larger than what you are going to draw on it at initialisation
  618. * time. The default value of this is 1200 pixels, which is quite large, but if for some
  619. * reason you're drawing connectors that are bigger, you should adjust this value appropriately.
  620. */
  621. setDefaultNewCanvasSize : function(size) {
  622. DEFAULT_NEW_CANVAS_SIZE = size;
  623. },
  624. /**
  625. * Sets whether or not a given element is draggable, regardless of what any plumb command
  626. * may request.
  627. */
  628. setDraggable: function(element, draggable) {
  629. _setDraggable(element, draggable);
  630. },
  631. /**
  632. * Sets whether or not elements are draggable by default. Default for this is true.
  633. */
  634. setDraggableByDefault: function(draggable) {
  635. _draggableByDefault = draggable;
  636. },
  637. /**
  638. * Sets the function to fire when the window size has changed and a repaint was fired.
  639. */
  640. setRepaintFunction : function(f) {
  641. repaintFunction = f;
  642. },
  643. /**
  644. * Set an element's connections to be visible.
  645. */
  646. show : function(elId) {
  647. _setVisible(elId, "block");
  648. },
  649. /**
  650. * helper to size a canvas.
  651. */
  652. sizeCanvas : function(canvas, x, y, w, h) {
  653. canvas.style.height = h + "px"; canvas.height = h;
  654. canvas.style.width = w + "px"; canvas.width = w;
  655. canvas.style.left = x + "px"; canvas.style.top = y + "px";
  656. },
  657. /**
  658. * Toggles visibility of an element's connections.
  659. */
  660. toggle : function(elId) {
  661. var jpcs = connections[elId];
  662. if (jpcs.length > 0)
  663. _setVisible(elId, "none" == jpcs[0].canvas.style.display ? "block" : "none");
  664. },
  665. /**
  666. * Unloads jsPlumb, deleting all storage. You should call this
  667. */
  668. unload : function() {
  669. delete connections;
  670. delete offsets;
  671. delete sizes;
  672. delete draggableStates;
  673. }
  674. };
  675. // ************** connection
  676. // ****************************************
  677. /**
  678. * allowed params:
  679. * source: source element (string or a jQuery element) (required)
  680. * target: target element (string or a jQuery element) (required)
  681. * anchors: optional array of anchor placements. defaults to BottomCenter for source
  682. * and TopCenter for target.
  683. */
  684. var jsPlumbConnection = function(params) {
  685. // ************** get the source and target and register the connection. *******************
  686. var self = this;
  687. // get source and target as jQuery objects
  688. this.source = (typeof params.source == 'string') ? $("#" + params.source) : params.source;
  689. this.target = (typeof params.target == 'string') ? $("#" + params.target) : params.target;
  690. this.sourceId = $(this.source).attr("id");
  691. this.targetId = $(this.target).attr("id");
  692. this.drawEndpoints = params.drawEndpoints != null ? params.drawEndpoints : true;
  693. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  694. // get anchor
  695. this.anchors = params.anchors || jsPlumb.DEFAULT_ANCHORS || [jsPlumb.Anchors.BottomCenter, jsPlumb.Anchors.TopCenter];
  696. // make connector
  697. this.connector = params.connector || jsPlumb.DEFAULT_CONNECTOR || new jsPlumb.Connectors.Bezier();
  698. this.paintStyle = params.paintStyle || jsPlumb.DEFAULT_PAINT_STYLE;
  699. // init endpoints
  700. this.endpoints = [];
  701. if(!params.endpoints) params.endpoints = [null,null];
  702. this.endpoints[0] = params.endpoints[0] || params.endpoint || jsPlumb.DEFAULT_ENDPOINTS[0] || jsPlumb.DEFAULT_ENDPOINT || new jsPlumb.Endpoints.Dot();
  703. this.endpoints[1] = params.endpoints[1] || params.endpoint || jsPlumb.DEFAULT_ENDPOINTS[1] ||jsPlumb.DEFAULT_ENDPOINT || new jsPlumb.Endpoints.Dot();
  704. this.endpointStyles = [];
  705. if (!params.endpointStyles) params.endpointStyles = [null,null];
  706. this.endpointStyles[0] = params.endpointStyles[0] || params.endpointStyle || jsPlumb.DEFAULT_ENDPOINT_STYLES[0] || jsPlumb.DEFAULT_ENDPOINT_STYLE;
  707. this.endpointStyles[1] = params.endpointStyles[1] || params.endpointStyle || jsPlumb.DEFAULT_ENDPOINT_STYLES[1] || jsPlumb.DEFAULT_ENDPOINT_STYLE;
  708. offsets[this.sourceId] = this.source.offset();
  709. sizes[this.sourceId] = [this.source.outerWidth(), this.source.outerHeight()];
  710. offsets[this.targetId] = this.target.offset();
  711. sizes[this.targetId] = [this.target.outerWidth(), this.target.outerHeight()];
  712. // *************** create canvases on which the connection will be drawn ************
  713. var canvas = _newCanvas(jsPlumb.connectorClass);
  714. this.canvas = canvas;
  715. // create endpoint canvases
  716. if (this.drawEndpoints) {
  717. this.sourceEndpointCanvas = _newCanvas(jsPlumb.endpointClass);
  718. this.targetEndpointCanvas = _newCanvas(jsPlumb.endpointClass);
  719. // sit them on top of the underlying element?
  720. var setZIndex = function(canvas, source, above) {
  721. var adj = above ? 1 : -1;
  722. var zIndex = $(source).css("zIndex");
  723. $(canvas).css("zIndex", zIndex != "auto" ? zIndex + adj : "auto");
  724. };
  725. setZIndex(this.sourceEndpointCanvas, this.source, this.endpointsOnTop);
  726. setZIndex(this.targetEndpointCanvas, this.target, this.endpointsOnTop);
  727. }
  728. // ************** store the anchors
  729. /**
  730. * paints the connection.
  731. * @param elId Id of the element that is in motion
  732. * @param ui jQuery's event system ui object (present if we came from a drag to get here)
  733. * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
  734. */
  735. this.paint = function(elId, ui, recalc) {
  736. // if the moving object is not the source we must transpose the two references.
  737. var swap = !(elId == this.sourceId);
  738. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  739. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  740. if (this.canvas.getContext) {
  741. if (recalc) {
  742. // get the current sizes of the two elements.
  743. var s = $("#" + elId);
  744. var t = $("#" + tId);
  745. sizes[elId] = [s.outerWidth(), s.outerHeight()];
  746. sizes[tId] = [t.outerWidth(), t.outerHeight()];
  747. offsets[elId] = s.offset();
  748. offsets[tId] = t.offset();
  749. } else {
  750. // faster to use the ui element if it was passed in. offset is a fallback.
  751. // fix for change in 1.8 (absolutePosition renamed to offset). plugin is compatible with
  752. // 1.8 and 1.7.
  753. var pos = ui.absolutePosition || ui.offset;
  754. var anOffset = ui != null ? pos : $("#" + elId).offset();
  755. offsets[elId] = anOffset;
  756. }
  757. var myOffset = offsets[elId];
  758. var otherOffset = offsets[tId];
  759. var myWH = sizes[elId];
  760. var otherWH = sizes[tId];
  761. var ctx = canvas.getContext('2d');
  762. var sAnchorP = this.anchors[sIdx].compute([myOffset.left, myOffset.top], myWH, [otherOffset.left, otherOffset.top], otherWH);
  763. var sAnchorO = this.anchors[sIdx].orientation;
  764. var tAnchorP = this.anchors[tIdx].compute([otherOffset.left, otherOffset.top], otherWH, [myOffset.left, myOffset.top], myWH);
  765. var tAnchorO = this.anchors[tIdx].orientation;
  766. var dim = this.connector.compute(sAnchorP, tAnchorP, this.anchors[sIdx], this.anchors[tIdx], this.paintStyle.lineWidth);
  767. jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
  768. applyPaintStyle(ctx, this.paintStyle);
  769. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  770. if (this.paintStyle.gradient && !ie) {
  771. var g = swap ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  772. for (var i = 0; i < this.paintStyle.gradient.stops.length; i++)
  773. g.addColorStop(this.paintStyle.gradient.stops[i][0],this.paintStyle.gradient.stops[i][1]);
  774. ctx.strokeStyle = g;
  775. }
  776. this.connector.paint(dim, ctx);
  777. if (this.drawEndpoints) {
  778. var style = this.endpointStyle || this.paintStyle;
  779. var sourceCanvas = swap ? this.targetEndpointCanvas : this.sourceEndpointCanvas;
  780. var targetCanvas = swap ? this.sourceEndpointCanvas : this.targetEndpointCanvas;
  781. this.endpoints[swap ? 1 : 0].paint(sAnchorP, sAnchorO, sourceCanvas, this.endpointStyles[swap ? 1 : 0] || this.paintStyle, this.paintStyle);
  782. this.endpoints[swap ? 0 : 1].paint(tAnchorP, tAnchorO, targetCanvas, this.endpointStyles[swap ? 0 : 1] || this.paintStyle, this.paintStyle);
  783. }
  784. }
  785. };
  786. this.repaint = function() {
  787. this.paint(this.sourceId, null, true);
  788. };
  789. // dragging
  790. var draggable = params.draggable == null ? _draggableByDefault : params.draggable;
  791. if (draggable && self.source.draggable) {
  792. var dragOptions = params.dragOptions || jsPlumb.DEFAULT_DRAG_OPTIONS;
  793. var dragCascade = dragOptions.drag || function(e,u) {};
  794. var initDrag = function(element, dragFunc) {
  795. var opts = $.extend({drag:dragFunc}, dragOptions);
  796. var draggable = draggableStates[element.attr("id")];
  797. opts.disabled = draggable == null ? false : !draggable;
  798. element.draggable(opts);
  799. };
  800. initDrag(this.source, function(event, ui) {
  801. _draw(self.source, ui);
  802. dragCascade(event, ui);
  803. });
  804. initDrag(this.target, function(event, ui) {
  805. _draw(self.target, ui);
  806. dragCascade(event, ui);
  807. });
  808. }
  809. // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
  810. if (this.source.resize) {
  811. this.source.resize(function(e) {
  812. jsPlumb.repaint(self.sourceId);
  813. });
  814. }
  815. // finally, draw it.
  816. var o = this.source.offset();
  817. this.paint(this.sourceId, {'absolutePosition': this.source.offset()});
  818. };
  819. })();
  820. // jQuery plugin code
  821. (function($){
  822. $.fn.plumb = function(options) {
  823. var defaults = { };
  824. var options = $.extend(defaults, options);
  825. return this.each(function()
  826. {
  827. var obj = $(this);
  828. var params = {};
  829. params.source = obj;
  830. for (var i in options) {
  831. params[i] = options[i];
  832. }
  833. jsPlumb.connect(params);
  834. });
  835. };
  836. $.fn.detach = function(options) {
  837. return this.each(function()
  838. {
  839. var id = $(this).attr("id");
  840. if (typeof options == 'string') options = [options];
  841. for (var i = 0; i < options.length; i++)
  842. jsPlumb.detach(id, options[i]);
  843. });
  844. };
  845. $.fn.detachAll = function(options) {
  846. return this.each(function()
  847. {
  848. var id = $(this).attr("id");
  849. jsPlumb.detachAll(id);
  850. });
  851. };
  852. })(jQuery);