jquery.jsPlumb-1.0.1-RC1.js 36 KB

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