jquery.jsPlumb-1.0.3.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. /*
  2. * jsPlumb 1.0.3
  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, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
  244. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  245. // points around if so (code could be tightened up)
  246. var perpendicular = sourceAnchor.orientation[0] != targetAnchor.orientation[0] || sourceAnchor.orientation[1] == targetAnchor.orientation[1];
  247. var p = [];
  248. var ma = self.majorAnchor, mi = self.minorAnchor;
  249. if (!perpendicular) {
  250. if (sourceAnchor.orientation[0] == 0) // X
  251. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  252. else p.push(point[0] - (ma * sourceAnchor.orientation[0]));
  253. if (sourceAnchor.orientation[1] == 0) // Y
  254. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  255. else p.push(point[1] + (ma * targetAnchor.orientation[1]));
  256. }
  257. else {
  258. if (targetAnchor.orientation[0] == 0) // X
  259. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  260. else p.push(point[0] + (ma * targetAnchor.orientation[0]));
  261. if (targetAnchor.orientation[1] == 0) // Y
  262. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  263. else p.push(point[1] + (ma * sourceAnchor.orientation[1]));
  264. }
  265. return p;
  266. };
  267. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth)
  268. {
  269. lineWidth = lineWidth || 0;
  270. var w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth, h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  271. var canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2), canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  272. var sx = sourcePos[0] < targetPos[0] ? w - (lineWidth/2): (lineWidth/2), sy = sourcePos[1] < targetPos[1] ? h-(lineWidth/2) : (lineWidth/2);
  273. var tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : w-(lineWidth/2), ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : h-(lineWidth/2);
  274. var CP = self._findControlPoint([sx,sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
  275. var CP2 = self._findControlPoint([tx,ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
  276. var minx1 = Math.min(sx,tx); var minx2 = Math.min(CP[0], CP2[0]); var minx = Math.min(minx1,minx2);
  277. var maxx1 = Math.max(sx,tx); var maxx2 = Math.max(CP[0], CP2[0]); var maxx = Math.max(maxx1,maxx2);
  278. if (maxx > w) w = maxx;
  279. if (minx < 0) {
  280. canvasX += minx; var ox = Math.abs(minx);
  281. w += ox; CP[0] += ox; sx += ox; tx +=ox; CP2[0] += ox;
  282. }
  283. var miny1 = Math.min(sy,ty); var miny2 = Math.min(CP[1], CP2[1]); var miny = Math.min(miny1,miny2);
  284. var maxy1 = Math.max(sy,ty); var maxy2 = Math.max(CP[1], CP2[1]); var maxy = Math.max(maxy1,maxy2);
  285. if (maxy > h) h = maxy;
  286. if (miny < 0) {
  287. canvasY += miny; var oy = Math.abs(miny);
  288. h += oy; CP[1] += oy; sy += oy; ty +=oy; CP2[1] += oy;
  289. }
  290. // return [ canvasx, canvasy, canvasWidth, canvasHeight,
  291. // sourceX, sourceY, targetX, targetY,
  292. // controlPoint1_X, controlPoint1_Y, controlPoint2_X, controlPoint2_Y
  293. return [canvasX, canvasY, w, h, sx, sy, tx, ty, CP[0], CP[1], CP2[0], CP2[1] ];
  294. };
  295. this.paint = function(d, ctx) {
  296. ctx.beginPath();
  297. ctx.moveTo(d[4],d[5]);
  298. ctx.bezierCurveTo(d[8],d[9],d[10],d[11],d[6],d[7]);
  299. ctx.stroke();
  300. }
  301. }
  302. },
  303. /**
  304. * Types of endpoint UIs. we supply three - a circle of default radius 10px, a rectangle of
  305. * default size 20x20, and an image (with no default). you can supply others of these if you want to - see the documentation
  306. * for a howto.
  307. */
  308. Endpoints : {
  309. /**
  310. * a round endpoint, with default radius 10 pixels.
  311. */
  312. Dot : function(params) {
  313. params = params || { radius:10 };
  314. var self = this;
  315. this.radius = params.radius;
  316. var defaultOffset = 0.5 * this.radius;
  317. var defaultInnerRadius = this.radius / 3;
  318. var parseValue = function(value) {
  319. try {
  320. return parseInt(value);
  321. }
  322. catch(e) {
  323. if (value.substring(value.length - 1) == '%')
  324. return parseInt(value.substring(0, value - 1));
  325. }
  326. }
  327. var calculateAdjustments = function(gradient) {
  328. var offsetAdjustment = defaultOffset;
  329. var innerRadius = defaultInnerRadius;
  330. if (gradient.offset) offsetAdjustment = parseValue(gradient.offset);
  331. if(gradient.innerRadius) innerRadius = parseValue(gradient.innerRadius);
  332. return [offsetAdjustment, innerRadius];
  333. };
  334. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  335. var radius = endpointStyle.radius || self.radius;
  336. var x = anchorPoint[0] - radius;
  337. var y = anchorPoint[1] - radius;
  338. jsPlumb.sizeCanvas(canvas, x, y, radius * 2, radius * 2);
  339. var ctx = canvas.getContext('2d');
  340. var style = {};
  341. applyPaintStyle(style, endpointStyle);
  342. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  343. applyPaintStyle(ctx, style);
  344. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  345. if (endpointStyle.gradient && !ie) {
  346. var adjustments = calculateAdjustments(endpointStyle.gradient);
  347. var yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0];
  348. var xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0];
  349. var g = ctx.createRadialGradient(radius, radius, radius, radius + xAdjust, radius + yAdjust, adjustments[1]);
  350. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  351. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  352. ctx.fillStyle = g;
  353. }
  354. ctx.beginPath();
  355. ctx.arc(radius, radius, radius, 0, Math.PI*2, true);
  356. ctx.closePath();
  357. ctx.fill();
  358. };
  359. },
  360. /**
  361. * A Rectangular endpoint, with default size 20x20.
  362. */
  363. Rectangle : function(params) {
  364. params = params || { width:20, height:20 };
  365. var self = this;
  366. this.width = params.width;
  367. this.height = params.height;
  368. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  369. var width = endpointStyle.width || self.width;
  370. var height = endpointStyle.height || self.height;
  371. var x = anchorPoint[0] - (width/2);
  372. var y = anchorPoint[1] - (height/2);
  373. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  374. var ctx = canvas.getContext('2d');
  375. //todo: the fillStyle needs some thought. we want to support a few options:
  376. // 1. nothing supplied; use the stroke color or the default if no stroke color.
  377. // 2. a fill color supplied - use it
  378. // 3. a gradient supplied - use it
  379. // 4. setting the endpoint to the same color as the bg of the element it is attached to.
  380. var style = {};
  381. applyPaintStyle(style, endpointStyle);
  382. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  383. applyPaintStyle(ctx, style);
  384. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  385. if (endpointStyle.gradient && !ie) {
  386. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  387. var y1 = orientation[1] == 1 ? height : orientation[1] == 0 ? height / 2 : 0;
  388. var y2 = orientation[1] == -1 ? height : orientation[1] == 0 ? height / 2 : 0;
  389. var x1 = orientation[0] == 1 ? width : orientation[0] == 0 ? width / 2 : 0;
  390. var x2 = orientation[0] == -1 ? width : orientation[0] == 0 ? height / 2 : 0;
  391. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  392. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  393. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  394. ctx.fillStyle = g;
  395. }
  396. ctx.beginPath();
  397. ctx.rect(0, 0, width, height);
  398. ctx.closePath();
  399. ctx.fill();
  400. };
  401. },
  402. /**
  403. * Image endpoint - draws an image as the endpoint. You must provide a 'url' property in the params object..
  404. */
  405. Image : function(params) {
  406. var self = this;
  407. this.img = new Image();
  408. var ready = false;
  409. this.img.onload = function() {
  410. self.ready = true;
  411. };
  412. this.img.src = params.url;
  413. var actuallyPaint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  414. var width = self.img.width || endpointStyle.width;
  415. var height = self.img.height || endpointStyle.height;
  416. var x = anchorPoint[0] - (width/2);
  417. var y = anchorPoint[1] - (height/2);
  418. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  419. var ctx = canvas.getContext('2d');
  420. ctx.drawImage(self.img,0,0);
  421. };
  422. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  423. if (self.ready) {
  424. actuallyPaint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
  425. }
  426. else
  427. window.setTimeout(function() {
  428. self.paint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle);
  429. }, 200);
  430. };
  431. }
  432. },
  433. /**
  434. * establishes a connection between two elements.
  435. * @param params object containing setup for the connection. see documentation.
  436. */
  437. connect : function(params) {
  438. var jpc = new jsPlumbConnection(params);
  439. var key = jpc.sourceId + "_" + jpc.targetId;
  440. connections[key] = jpc;
  441. var addToList = function(elId, jpc) {
  442. var l = connections[elId];
  443. if (l == null) {
  444. l = [];
  445. connections[elId] = l;
  446. }
  447. l.push(jpc);
  448. };
  449. // register this connection.
  450. addToList(jpc.sourceId, jpc);
  451. addToList(jpc.targetId, jpc);
  452. },
  453. /**
  454. * Remove one connection to an element.
  455. * @param sourceId id of the first window in the connection
  456. * @param targetId id of the second window in the connection
  457. */
  458. detach : function(sourceId, targetId) {
  459. var jpcs = connections[sourceId];
  460. var idx = -1;
  461. for (var i = 0; i < jpcs.length; i++) {
  462. if ((jpcs[i].sourceId == sourceId && jpcs[i].targetId == targetId) || (jpcs[i].targetId == sourceId && jpcs[i].sourceId == targetId)) {
  463. removeCanvas(jpcs[i].canvas);
  464. if (jpcs[i].drawEndpoints) {
  465. removeCanvas(jpcs[i].targetEndpointCanvas);
  466. removeCanvas(jpcs[i].sourceEndpointCanvas);
  467. }
  468. idx = i;
  469. break;
  470. }
  471. }
  472. if (idx != -1)
  473. jpcs.splice(idx, 1);
  474. // todo - dragging? if no more connections for an object turn off dragging by default, but
  475. // allow an override on it?
  476. },
  477. /**
  478. * remove all an element's connections.
  479. */
  480. detachAll : function(elId) {
  481. var jpcs = connections[elId];
  482. for (var i = 0; i < jpcs.length; i++) {
  483. removeCanvas(jpcs[i].canvas);
  484. if (jpcs[i].drawEndpoints) {
  485. removeCanvas(jpcs[i].targetEndpointCanvas);
  486. removeCanvas(jpcs[i].sourceEndpointCanvas);
  487. }
  488. }
  489. delete connections[elId];
  490. connections[elId] = [];
  491. },
  492. /**
  493. * remove all connections.
  494. */
  495. detachEverything : function() {
  496. for (var elId in connections) {
  497. var jpcs = connections[elId];
  498. if (jpcs.length) {
  499. try {
  500. for (var i = 0; i < jpcs.length; i++) {
  501. removeCanvas(jpcs[i].canvas);
  502. if (jpcs[i].drawEndpoints) {
  503. removeCanvas(jpcs[i].targetEndpointCanvas);
  504. removeCanvas(jpcs[i].sourceEndpointCanvas);
  505. }
  506. }
  507. } catch (e) { }
  508. }
  509. }
  510. delete connections;
  511. connections = [];
  512. },
  513. getConnections : function(elId) {
  514. return connections[elId];
  515. },
  516. /**
  517. * Set an element's connections to be hidden.
  518. */
  519. hide : function(elId) {
  520. setVisible(elId, "none");
  521. },
  522. /**
  523. * Creates an anchor with the given params.
  524. * x - the x location of the anchor as a percentage of the total width.
  525. * y - the y location of the anchor as a percentage of the total height.
  526. * orientation - an [x,y] array indicating the general direction a connection from the anchor should go in.
  527. * 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].
  528. */
  529. makeAnchor : function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  530. // backwards compatibility here. we used to require an object passed in but that makes the call very verbose. easier to use
  531. // 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.
  532. var params = {};
  533. if (arguments.length == 1) $.extend(params, x);
  534. else {
  535. params = {x:x, y:y};
  536. if (arguments.length >= 4) {
  537. params.orientation = [arguments[2], arguments[3]];
  538. }
  539. if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
  540. }
  541. return new Anchor(params);
  542. },
  543. /**
  544. * repaint element and its connections. element may be an id or the actual jQuery object.
  545. * this method gets new sizes for the elements before painting anything.
  546. */
  547. repaint : function(el) {
  548. var _repaint = function(el, elId) {
  549. var jpcs = connections[elId];
  550. var idx = -1;
  551. var loc = {'absolutePosition': el.offset()};
  552. for (var i = 0; i < jpcs.length; i++) {
  553. jpcs[i].paint(elId, loc, true);
  554. }
  555. };
  556. var _processElement = function(el) {
  557. var ele = typeof(el)=='string' ? $("#" + el) : el;
  558. var eleId = ele.attr("id");
  559. _repaint(ele, eleId);
  560. };
  561. // TODO: support a jQuery result object too!
  562. // support both lists...
  563. if (typeof el =='object') {
  564. for (var i = 0; i < el.length; i++)
  565. _processElement(el[i]);
  566. } // ...and single strings.
  567. else _processElement(el);
  568. },
  569. /**
  570. * repaint all connections.
  571. */
  572. repaintEverything : function() {
  573. for (var elId in connections) {
  574. var jpcs = connections[elId];
  575. if (jpcs.length) {
  576. try {
  577. for (var i = 0; i < jpcs.length; i++) {
  578. jpcs[i].repaint();
  579. }
  580. } catch (e) { }
  581. }
  582. }
  583. },
  584. /**
  585. * sets/unsets automatic repaint on window resize.
  586. */
  587. setAutomaticRepaint : function(value) {
  588. automaticRepaint = value;
  589. },
  590. /**
  591. * Sets the default size jsPlumb will use for a new canvas (we create a square canvas so
  592. * one value is all that is required). This is a hack for IE, because ExplorerCanvas seems
  593. * to need for a canvas to be larger than what you are going to draw on it at initialisation
  594. * time. The default value of this is 1200 pixels, which is quite large, but if for some
  595. * reason you're drawing connectors that are bigger, you should adjust this value appropriately.
  596. */
  597. setDefaultNewCanvasSize : function(size) {
  598. DEFAULT_NEW_CANVAS_SIZE = size;
  599. },
  600. /**
  601. * Sets the function to fire when the window size has changed and a repaint was fired.
  602. */
  603. setRepaintFunction : function(f) {
  604. repaintFunction = f;
  605. },
  606. /**
  607. * Set an element's connections to be visible.
  608. */
  609. show : function(elId) {
  610. setVisible(elId, "block");
  611. },
  612. /**
  613. * helper to size a canvas.
  614. */
  615. sizeCanvas : function(canvas, x, y, w, h) {
  616. canvas.style.height = h + "px"; canvas.height = h;
  617. canvas.style.width = w + "px"; canvas.width = w;
  618. canvas.style.left = x + "px"; canvas.style.top = y + "px";
  619. },
  620. /**
  621. * Toggles visibility of an element's connections.
  622. */
  623. toggle : function(elId) {
  624. var jpcs = connections[elId];
  625. if (jpcs.length > 0)
  626. setVisible(elId, "none" == jpcs[0].canvas.style.display ? "block" : "none");
  627. },
  628. /**
  629. * Unloads jsPlumb, deleting all storage. You should call this
  630. */
  631. unload : function() {
  632. delete connections;
  633. delete offsets;
  634. delete sizes;
  635. }
  636. };
  637. // ************** connection
  638. // ****************************************
  639. /**
  640. * allowed params:
  641. * source: source element (string or a jQuery element) (required)
  642. * target: target element (string or a jQuery element) (required)
  643. * anchors: optional array of anchor placements. defaults to BottomCenter for source
  644. * and TopCenter for target.
  645. */
  646. var jsPlumbConnection = function(params) {
  647. // ************** get the source and target and register the connection. *******************
  648. var self = this;
  649. // get source and target as jQuery objects
  650. this.source = (typeof params.source == 'string') ? $("#" + params.source) : params.source;
  651. this.target = (typeof params.target == 'string') ? $("#" + params.target) : params.target;
  652. this.sourceId = $(this.source).attr("id");
  653. this.targetId = $(this.target).attr("id");
  654. this.drawEndpoints = params.drawEndpoints != null ? params.drawEndpoints : true;
  655. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  656. // get anchor
  657. this.anchors = params.anchors || jsPlumb.DEFAULT_ANCHORS || [jsPlumb.Anchors.BottomCenter, jsPlumb.Anchors.TopCenter];
  658. // make connector
  659. this.connector = params.connector || jsPlumb.DEFAULT_CONNECTOR || new jsPlumb.Connectors.Bezier();
  660. this.paintStyle = params.paintStyle || jsPlumb.DEFAULT_PAINT_STYLE;
  661. // init endpoints
  662. this.endpoints = [];
  663. if(!params.endpoints) params.endpoints = [null,null];
  664. this.endpoints[0] = params.endpoints[0] || params.endpoint || jsPlumb.DEFAULT_ENDPOINTS[0] || jsPlumb.DEFAULT_ENDPOINT || new jsPlumb.Endpoints.Dot();
  665. this.endpoints[1] = params.endpoints[1] || params.endpoint || jsPlumb.DEFAULT_ENDPOINTS[1] ||jsPlumb.DEFAULT_ENDPOINT || new jsPlumb.Endpoints.Dot();
  666. this.endpointStyles = [];
  667. if (!params.endpointStyles) params.endpointStyles = [null,null];
  668. this.endpointStyles[0] = params.endpointStyles[0] || params.endpointStyle || jsPlumb.DEFAULT_ENDPOINT_STYLES[0] || jsPlumb.DEFAULT_ENDPOINT_STYLE;
  669. this.endpointStyles[1] = params.endpointStyles[1] || params.endpointStyle || jsPlumb.DEFAULT_ENDPOINT_STYLES[1] || jsPlumb.DEFAULT_ENDPOINT_STYLE;
  670. offsets[this.sourceId] = this.source.offset();
  671. sizes[this.sourceId] = [this.source.outerWidth(), this.source.outerHeight()];
  672. offsets[this.targetId] = this.target.offset();
  673. sizes[this.targetId] = [this.target.outerWidth(), this.target.outerHeight()];
  674. // *************** create canvases on which the connection will be drawn ************
  675. var canvas = newCanvas(jsPlumb.connectorClass);
  676. this.canvas = canvas;
  677. // create endpoint canvases
  678. if (this.drawEndpoints) {
  679. this.sourceEndpointCanvas = newCanvas(jsPlumb.endpointClass);
  680. this.targetEndpointCanvas = newCanvas(jsPlumb.endpointClass);
  681. // sit them on top of the underlying element?
  682. if (this.endpointsOnTop) {
  683. $(this.sourceEndpointCanvas).css("zIndex", this.source.css("zIndex") + 1);
  684. $(this.targetEndpointCanvas).css("zIndex", this.target.css("zIndex") + 1);
  685. } else {
  686. $(this.sourceEndpointCanvas).css("zIndex", this.source.css("zIndex") - 1);
  687. $(this.targetEndpointCanvas).css("zIndex", this.target.css("zIndex") - 1);
  688. }
  689. }
  690. // ************** store the anchors
  691. /**
  692. * paints the connection.
  693. * @param elId Id of the element that is in motion
  694. * @param ui jQuery's event system ui object (present if we came from a drag to get here)
  695. * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
  696. */
  697. this.paint = function(elId, ui, recalc) {
  698. // if the moving object is not the source we must transpose the two references.
  699. var swap = !(elId == this.sourceId);
  700. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  701. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  702. if (this.canvas.getContext) {
  703. if (recalc) {
  704. // get the current sizes of the two elements.
  705. var s = $("#" + elId);
  706. var t = $("#" + tId);
  707. sizes[elId] = [s.outerWidth(), s.outerHeight()];
  708. sizes[tId] = [t.outerWidth(), t.outerHeight()];
  709. offsets[elId] = s.offset();
  710. offsets[tId] = t.offset();
  711. } else {
  712. // faster to use the ui element if it was passed in. offset is a fallback.
  713. // fix for change in 1.8 (absolutePosition renamed to offset). plugin is compatible with
  714. // 1.8 and 1.7.
  715. var pos = ui.absolutePosition || ui.offset;
  716. var anOffset = ui != null ? pos : $("#" + elId).offset();
  717. offsets[elId] = anOffset;
  718. }
  719. var myOffset = offsets[elId];
  720. var otherOffset = offsets[tId];
  721. var myWH = sizes[elId];
  722. var otherWH = sizes[tId];
  723. var ctx = canvas.getContext('2d');
  724. var sAnchorP = this.anchors[sIdx].compute([myOffset.left, myOffset.top], myWH, [otherOffset.left, otherOffset.top], otherWH);
  725. var sAnchorO = this.anchors[sIdx].orientation;
  726. var tAnchorP = this.anchors[tIdx].compute([otherOffset.left, otherOffset.top], otherWH, [myOffset.left, myOffset.top], myWH);
  727. var tAnchorO = this.anchors[tIdx].orientation;
  728. var dim = this.connector.compute(sAnchorP, tAnchorP, this.anchors[sIdx], this.anchors[tIdx], this.paintStyle.lineWidth);
  729. jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
  730. applyPaintStyle(ctx, this.paintStyle);
  731. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  732. if (this.paintStyle.gradient && !ie) {
  733. var g = swap ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  734. for (var i = 0; i < this.paintStyle.gradient.stops.length; i++)
  735. g.addColorStop(this.paintStyle.gradient.stops[i][0],this.paintStyle.gradient.stops[i][1]);
  736. ctx.strokeStyle = g;
  737. }
  738. this.connector.paint(dim, ctx);
  739. if (this.drawEndpoints) {
  740. var style = this.endpointStyle || this.paintStyle;
  741. var sourceCanvas = swap ? this.targetEndpointCanvas : this.sourceEndpointCanvas;
  742. var targetCanvas = swap ? this.sourceEndpointCanvas : this.targetEndpointCanvas;
  743. this.endpoints[swap ? 1 : 0].paint(sAnchorP, sAnchorO, sourceCanvas, this.endpointStyles[swap ? 1 : 0] || this.paintStyle, this.paintStyle);
  744. this.endpoints[swap ? 0 : 1].paint(tAnchorP, tAnchorO, targetCanvas, this.endpointStyles[swap ? 0 : 1] || this.paintStyle, this.paintStyle);
  745. }
  746. }
  747. };
  748. this.repaint = function() {
  749. this.paint(this.sourceId, null, true);
  750. };
  751. // dragging
  752. var draggable = params.draggable == null ? true : params.draggable;
  753. if (draggable && self.source.draggable) {
  754. var dragOptions = params.dragOptions || jsPlumb.DEFAULT_DRAG_OPTIONS;
  755. var dragCascade = dragOptions.drag || function(e,u) {};
  756. var initDrag = function(element, dragFunc) {
  757. var opts = {};
  758. for (var i in dragOptions) {
  759. opts[i] = dragOptions[i];
  760. }
  761. opts.drag = dragFunc;
  762. element.draggable(opts);
  763. };
  764. initDrag(this.source, function(event, ui) {
  765. drag(self.source, ui);
  766. dragCascade(event, ui);
  767. });
  768. initDrag(this.target, function(event, ui) {
  769. drag(self.target, ui);
  770. dragCascade(event, ui);
  771. });
  772. }
  773. // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
  774. if (this.source.resize) {
  775. this.source.resize(function(e) {
  776. jsPlumb.repaint(self.sourceId);
  777. });
  778. }
  779. // finally, draw it.
  780. var o = this.source.offset();
  781. this.paint(this.sourceId, {'absolutePosition': this.source.offset()});
  782. };
  783. })();
  784. // jQuery plugin code
  785. (function($){
  786. $.fn.plumb = function(options) {
  787. var defaults = { };
  788. var options = $.extend(defaults, options);
  789. return this.each(function()
  790. {
  791. var obj = $(this);
  792. var params = {};
  793. params.source = obj;
  794. for (var i in options) {
  795. params[i] = options[i];
  796. }
  797. jsPlumb.connect(params);
  798. });
  799. };
  800. $.fn.detach = function(options) {
  801. return this.each(function()
  802. {
  803. var id = $(this).attr("id");
  804. if (typeof options == 'string') options = [options];
  805. for (var i = 0; i < options.length; i++)
  806. jsPlumb.detach(id, options[i]);
  807. });
  808. };
  809. $.fn.detachAll = function(options) {
  810. return this.each(function()
  811. {
  812. var id = $(this).attr("id");
  813. jsPlumb.detachAll(id);
  814. });
  815. };
  816. })(jQuery);