jquery.jsPlumb-1.0.0.js 34 KB

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