jquery.jsPlumb-1.0.2.js 36 KB

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