jquery.jsPlumb-1.0.2-RC3.js 38 KB

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