jsPlumb-1.2-RC1.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  1. /*
  2. * jsPlumb 1.2-RC1
  3. *
  4. * Provides a way to visually connect elements on an HTML page.
  5. *
  6. * 1.1.1 contains bugfixes and API additions on 1.1.0.
  7. *
  8. *
  9. * http://morrisonpitt.com/jsPlumb/demo.html
  10. * http://code.google.com/p/jsPlumb
  11. *
  12. */
  13. (function() {
  14. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  15. var log = null;
  16. var repaintFunction = function() { jsPlumb.repaintEverything(); };
  17. var automaticRepaint = true;
  18. function repaintEverything() {
  19. if (automaticRepaint)
  20. repaintFunction();
  21. };
  22. var resizeTimer = null;
  23. /*TODO: abstract this out from jQuery too! but how...because jsPlumb is not loaded yet.
  24. $(window).bind('resize', function() {
  25. if (resizeTimer) clearTimeout(resizeTimer);
  26. resizeTimer = setTimeout(repaintEverything, 100);
  27. });*/
  28. /**
  29. * map of element id -> endpoint lists. an element can have an arbitrary number of endpoints on it,
  30. * and not all of them have to be connected to anything.
  31. */
  32. var endpointsByElement = {};
  33. var offsets = [];
  34. var floatingConnections = {};
  35. var draggableStates = {};
  36. var _draggableByDefault = true;
  37. var sizes = [];
  38. 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.)
  39. var _findIndex = function( a, v, b, s ) {
  40. var _eq = function(o1, o2) {
  41. if (o1 === o2) return true;
  42. else if (typeof o1 == 'object' && typeof o2 == 'object') {
  43. var same = true;
  44. for(var propertyName in o1) {
  45. if(!_eq(o1[propertyName], o2[propertyName])) {
  46. same = false;
  47. break;
  48. }
  49. }
  50. for(var propertyName in o2) {
  51. if(!_eq(o2[propertyName], o1[propertyName])) {
  52. same = false;
  53. break;
  54. }
  55. }
  56. return same;
  57. }
  58. };
  59. for( var i = +b || 0, l = a.length; i < l; i++ ) {
  60. if( _eq(a[i], v)) return i;
  61. }
  62. return -1;
  63. };
  64. /**
  65. * helper method to add an item to a list, creating the list if it does not yet exist.
  66. */
  67. var _addToList = function(map, key, value) {
  68. var l = map[key];
  69. if (l == null) {
  70. l = [];
  71. map[key] = l;
  72. }
  73. l.push(value);
  74. };
  75. /**
  76. * Handles the dragging of an element.
  77. * @param element jQuery element
  78. * @param ui UI object from current library's event system
  79. */
  80. var _draw = function(element, ui) {
  81. var id = _getAttribute(element, "id");
  82. var endpoints = endpointsByElement[id];
  83. if (endpoints) {
  84. _updateOffset(id, ui);
  85. var myOffset = offsets[id];
  86. var myWH = sizes[id];
  87. // loop through endpoints for this element
  88. for (var i = 0; i < endpoints.length; i++) {
  89. var e = endpoints[i];
  90. var anchorLoc = endpoints[i].anchor.compute([myOffset.left, myOffset.top], myWH);
  91. e.paint(anchorLoc);
  92. var l = e.connections;
  93. for (var j = 0; j < l.length; j++)
  94. l[j].paint(id, ui); // ...and paint them.
  95. }
  96. }
  97. };
  98. /**
  99. * helper function: the second argument is a function taking two args - the first is an id
  100. * ui element from the current library (or list of them), and the second is the function
  101. * to run.
  102. */
  103. var _elementProxy = function(element, fn) {
  104. var retVal = null;
  105. if (typeof element == 'object' && element.length) {
  106. retVal = [];
  107. for (var i = 0; i < element.length; i++) {
  108. var el = _getElementObject(element[i]);
  109. var id = _getAttribute(el, "id");
  110. retVal.push(fn(el, id)); // append return values to what we will return
  111. }
  112. }
  113. else {
  114. var el = _getElementObject(element);
  115. var id = _getAttribute(el, "id");
  116. retVal = fn(el, id);
  117. }
  118. return retVal;
  119. };
  120. /**
  121. * gets the named attribute from the given element (id or element object)
  122. */
  123. var _getAttribute = function(el, attName) {
  124. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  125. return jsPlumb.CurrentLibrary.getAttribute(ele, attName);
  126. };
  127. var _setAttribute = function(el, attName, attValue) {
  128. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  129. jsPlumb.CurrentLibrary.setAttribute(ele, attName, attValue);
  130. };
  131. var _addClass = function(el, clazz) {
  132. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  133. jsPlumb.CurrentLibrary.addClass(ele, clazz);
  134. };
  135. var _getElementObject = function(elId) {
  136. return jsPlumb.CurrentLibrary.getElementObject(elId);
  137. };
  138. var _getOffset = function(el) {
  139. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  140. return jsPlumb.CurrentLibrary.getOffset(ele);
  141. };
  142. var _getSize = function(el) {
  143. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  144. return jsPlumb.CurrentLibrary.getSize(ele);
  145. };
  146. var _appendCanvas = function(canvas) {
  147. document.body.appendChild(canvas);
  148. };
  149. /**
  150. * gets an id for the given element, creating and setting one if necessary.
  151. */
  152. var _getId = function(element) {
  153. var id = _getAttribute(element, "id");
  154. if (!id) {
  155. id = "_jsPlumb_" + new String((new Date()).getTime());
  156. _setAttribute(element, "id", id);
  157. }
  158. return id;
  159. };
  160. /**
  161. * inits a draggable if it's not already initialised.
  162. *
  163. * TODO: we need to hook in each library to this method. they need to be given the opportunity to
  164. * wrap/insert lifecycle functions, because each library does different things. for instance, jQuery
  165. * supports the notion of 'revert', which will clean up a dragged endpoint; MooTools does not. jQuery
  166. * also supports 'opacity' and MooTools does not; jQuery supports z-index of the draggable; MooTools
  167. * does not. i could go on. the point is...oh. initDraggable can do this. ok.
  168. */
  169. var _initDraggableIfNecessary = function(element, elementId, isDraggable, dragOptions) {
  170. // dragging
  171. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  172. if (draggable && jsPlumb.CurrentLibrary.isDragSupported(element)) {
  173. var options = dragOptions || jsPlumb.Defaults.DragOptions;
  174. options = jsPlumb.extend({}, options); // make a copy.
  175. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  176. var initDrag = function(element, elementId, dragFunc) {
  177. options[dragEvent] = _wrap(options[dragEvent], dragFunc);
  178. var draggable = draggableStates[elementId];
  179. // TODO: this is still jQuery specific.
  180. options.disabled = draggable == null ? false : !draggable;
  181. jsPlumb.CurrentLibrary.initDraggable(element, options);
  182. };
  183. initDrag(element, elementId, function() {
  184. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  185. _draw(element, ui);
  186. _addClass(element, "jsPlumb_dragged");
  187. });
  188. }
  189. };
  190. var _log = function(msg) {
  191. // not implemented. yet.
  192. }
  193. /**
  194. * helper to create a canvas.
  195. * @param clazz optional class name for the canvas.
  196. */
  197. var _newCanvas = function(clazz) {
  198. var canvas = document.createElement("canvas");
  199. _appendCanvas(canvas);
  200. canvas.style.position="absolute";
  201. if (clazz) { canvas.className=clazz; }
  202. _getId(canvas); // set an id.
  203. if (ie) {
  204. // for IE we have to set a big canvas size. actually you can override this, too, if 1200 pixels
  205. // is not big enough for the biggest connector/endpoint canvas you have at startup.
  206. jsPlumb.sizeCanvas(canvas, 0, 0, DEFAULT_NEW_CANVAS_SIZE, DEFAULT_NEW_CANVAS_SIZE);
  207. canvas = G_vmlCanvasManager.initElement(canvas);
  208. }
  209. return canvas;
  210. };
  211. /**
  212. * performs the given function operation on all the connections found for the given element
  213. * id; this means we find all the endpoints for the given element, and then for each endpoint
  214. * find the connectors connected to it. then we pass each connection in to the given
  215. * function.
  216. */
  217. var _operation = function(elId, func) {
  218. var endpoints = endpointsByElement[elId];
  219. if (endpoints && endpoints.length) {
  220. for (var i = 0; i < endpoints.length; i++) {
  221. for (var j = 0; j < endpoints[i].connections.length; j++) {
  222. var retVal = func(endpoints[i].connections[j]);
  223. // if the function passed in returns true, we exit.
  224. // most functions return false.
  225. if (retVal) return;
  226. }
  227. }
  228. }
  229. };
  230. /**
  231. * perform an operation on all elements.
  232. */
  233. var _operationOnAll = function(func) {
  234. for (var elId in endpointsByElement) {
  235. _operation(elId, func);
  236. }
  237. };
  238. /**
  239. * helper to remove an element from the DOM.
  240. */
  241. var _removeElement = function(element) {
  242. if (element != null) {
  243. try { document.body.removeChild(element); }
  244. catch (e) { }
  245. }
  246. };
  247. /**
  248. * helper to remove a list of elements from the DOM.
  249. */
  250. var _removeElements = function(elements) {
  251. for (var i in elements)
  252. _removeElement(elements[i]);
  253. };
  254. /**
  255. * helper method to remove an item from a list.
  256. */
  257. var _removeFromList = function(map, key, value) {
  258. var l = map[key];
  259. if (l != null) {
  260. var i = _findIndex(l, value);
  261. if (i >= 0) {
  262. delete( l[i] );
  263. l.splice( i, 1 );
  264. return true;
  265. }
  266. }
  267. return false;
  268. };
  269. /**
  270. * Sets whether or not the given element(s) should be draggable, regardless of what a particular
  271. * plumb command may request.
  272. *
  273. * @param element May be a string, a jQuery elements, or a list of strings/jquery elements.
  274. * @param draggable Whether or not the given element(s) should be draggable.
  275. */
  276. var _setDraggable = function(element, draggable) {
  277. var _helper = function(el, id) {
  278. draggableStates[id] = draggable;
  279. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  280. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  281. }
  282. };
  283. return _elementProxy(element, _helper);
  284. };
  285. /**
  286. * private method to do the business of hiding/showing.
  287. * @param el either Id of the element in question or a jquery object for the element.
  288. * @param state String specifying a value for the css 'display' property ('block' or 'none').
  289. */
  290. var _setVisible = function(el, state) {
  291. var elId = _getAttribute(el, "id");
  292. var f = function(jpc) {
  293. jpc.canvas.style.display = state;
  294. };
  295. _operation(elId, f);
  296. };
  297. /**
  298. * toggles the draggable state of the given element(s).
  299. * @param el either an id, or a jquery object, or a list of ids/jquery objects.
  300. */
  301. var _toggleDraggable = function(el) {
  302. var fn = function(el, elId) {
  303. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  304. state = !state;
  305. draggableStates[elId] = state;
  306. //el.draggable("option", "disabled", !state);
  307. jsPlumb.CurrentLibrary.setDraggable(el, state);
  308. return state;
  309. };
  310. return _elementProxy(el, fn);
  311. };
  312. /**
  313. * private method to do the business of toggling hiding/showing.
  314. * @param elId Id of the element in question
  315. */
  316. var _toggleVisible = function(elId) {
  317. var f = function(jpc) {
  318. var state = ('none' == jpc.canvas.style.display);
  319. jpc.canvas.style.display = state ? "block" : "none";
  320. };
  321. _operation(elId, f);
  322. //todo this should call _elementProxy, and pass in the _operation(elId, f) call as a function. cos _toggleDraggable does that.
  323. };
  324. /**
  325. * updates the offset and size for a given element, and stores the values.
  326. * if 'offset' is not null we use that (it would have been passed in from a drag call) because it's faster; but if it is null,
  327. * or if 'recalc' is true in order to force a recalculation, we use the offset, outerWidth and outerHeight methods to get
  328. * the current values.
  329. */
  330. var _updateOffset = function(elId, offset, recalc) {
  331. if (recalc || offset == null) { // if forced repaint or no offset available, we recalculate.
  332. // get the current size and offset, and store them
  333. var s = _getElementObject(elId);
  334. sizes[elId] = _getSize(elId);
  335. offsets[elId] = _getOffset(elId);
  336. } else {
  337. offsets[elId] = offset;
  338. }
  339. };
  340. /**
  341. * wraps one function with another, creating a placeholder for the wrapped function
  342. * if it was null. this is used to wrap the various drag/drop event functions - to allow
  343. * jsPlumb to be notified of important lifecycle events without imposing itself on the user's
  344. * drap/drop functionality.
  345. * TODO: determine whether or not we should support an error handler concept, if one of the functions fails.
  346. */
  347. var _wrap = function(wrappedFunction, newFunction) {
  348. wrappedFunction = wrappedFunction || function() { };
  349. newFunction = newFunction || function() { };
  350. return function() {
  351. try { newFunction.apply(this, arguments); }
  352. catch (e) { }
  353. try { wrappedFunction.apply(this, arguments); }
  354. catch (e) { }
  355. };
  356. }
  357. /*
  358. Class: Anchor
  359. Models a position relative to the origin of some element that an Endpoint can be located.
  360. */
  361. /*
  362. Function: Anchor
  363. Constructor for the Anchor class
  364. Parameters:
  365. params - Anchor parameters. This should contain three values, and may optionally have an 'offsets' argument:
  366. - x : the x location of the anchor as a fraction of the total width.
  367. - y : the y location of the anchor as a fraction of the total height.
  368. - orientation : an [x,y] array indicating the general direction a connection from the anchor should go in. for more info on this, see the documentation, or the docs in jquery-jsPlumb-defaults-XXX.js for the default Anchors.
  369. - offsets : an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out. may be null.
  370. */
  371. var Anchor = function(params) {
  372. var self = this;
  373. this.x = params.x || 0; this.y = params.y || 0;
  374. var orientation = params.orientation || [0,0];
  375. this.offsets = params.offsets || [0,0];
  376. this.compute = function(xy, wh, txy, twh) {
  377. return [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  378. }
  379. this.getOrientation = function() { return orientation; };
  380. };
  381. /**
  382. * An Anchor that floats. its orientation is computed dynamically from its position relative to the anchor it is floating relative to.
  383. *
  384. */
  385. var FloatingAnchor = function(params) {
  386. // this is the anchor that this floating anchor is referenced to for purposes of calculating the orientation.
  387. var ref = params.reference;
  388. // the canvas this refers to.
  389. var refCanvas = params.referenceCanvas;
  390. var size = _getSize(refCanvas);
  391. // these are used to store the current relative position of our anchor wrt the reference anchor. they only indicate
  392. // direction, so have a value of 1 or -1 (or, very rarely, 0). these values are written by the compute method, and read
  393. // by the getOrientation method.
  394. var xDir = 0, yDir = 0;
  395. // temporary member used to store an orientation when the floating anchor is hovering over another anchor.
  396. var orientation = null;
  397. this.compute = function(xy, wh, txy, twh) {
  398. // set these for the getOrientation method to use.
  399. xDir = 0;//xy[0] < txy[0] ? -1 : xy[0] == txy[0] ? 0 : 1;
  400. yDir = 0;//xy[1] < txy[1] ? -1 : xy[1] == txy[1] ? 0 : 1;
  401. return [xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
  402. };
  403. this.getOrientation = function() {
  404. if (orientation) return orientation;
  405. else {
  406. var o = ref.getOrientation();
  407. // here we take into account the orientation of the other anchor: if it declares zero for some direction, we declare zero too.
  408. // this might not be the most awesome. perhaps we can come up with a better way. it's just so that the line we draw looks
  409. // like it makes sense. maybe this wont make sense.
  410. return [Math.abs(o[0]) * xDir * -1, Math.abs(o[1]) * yDir * -1];
  411. }
  412. };
  413. /**
  414. * notification the endpoint associated with this anchor is hovering over another anchor;
  415. * we want to assume that anchor's orientation for the duration of the hover.
  416. */
  417. this.over = function(anchor) {
  418. orientation = anchor.getOrientation();
  419. };
  420. /**
  421. * notification the endpoint associated with this anchor is no longer hovering
  422. * over another anchor; we should resume calculating orientation as we normally do.
  423. */
  424. this.out = function() {
  425. orientation = null;
  426. };
  427. };
  428. // ************** connection
  429. // ****************************************
  430. /**
  431. * allowed params:
  432. * source: source element (string or a jQuery element) (required)
  433. * target: target element (string or a jQuery element) (required)
  434. *
  435. * anchors: optional array of anchor placements. defaults to BottomCenter for source
  436. * and TopCenter for target.
  437. */
  438. var Connection = function(params) {
  439. // ************** get the source and target and register the connection. *******************
  440. var self = this;
  441. // get source and target as jQuery objects
  442. this.source = _getElementObject(params.source);
  443. this.target = _getElementObject(params.target);
  444. this.sourceId = _getAttribute(this.source, "id");
  445. this.targetId = _getAttribute(this.target, "id");
  446. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  447. // init endpoints
  448. this.endpoints = [];
  449. this.endpointStyles = [];
  450. var prepareEndpoint = function(existing, index, params) {
  451. if (existing) self.endpoints[index] = existing;
  452. else {
  453. if(!params.endpoints) params.endpoints = [null,null];
  454. var ep = params.endpoints[index] || params.endpoint || jsPlumb.Defaults.Endpoints[index] || jsPlumb.Defaults.Endpoint|| new jsPlumb.Endpoints.Dot();
  455. if (!params.endpointStyles) params.endpointStyles = [null,null];
  456. var es = params.endpointStyles[index] || params.endpointStyle || jsPlumb.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyle;
  457. var a = params.anchors ? params.anchors[index] : jsPlumb.Defaults.Anchors[index] || jsPlumb.Anchors.BottomCenter;
  458. self.endpoints[index] = new Endpoint({style:es, endpoint:ep, connections:[self], anchor:a, source:self.source });
  459. }
  460. };
  461. prepareEndpoint(params.sourceEndpoint, 0, params);
  462. prepareEndpoint(params.targetEndpoint, 1, params);
  463. this.connector = this.endpoints[0].connector || this.endpoints[1].connector || params.connector || jsPlumb.Defaults.Connector || new jsPlumb.Connectors.Bezier();
  464. this.paintStyle = this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || jsPlumb.Defaults.PaintStyle;
  465. _updateOffset(this.sourceId);
  466. _updateOffset(this.targetId);
  467. // paint the endpoints
  468. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  469. var anchorLoc = this.endpoints[0].anchor.compute([myOffset.left, myOffset.top], myWH);
  470. this.endpoints[0].paint(anchorLoc);
  471. myOffset = offsets[this.targetId]; myWH = sizes[this.targetId];
  472. anchorLoc = this.endpoints[1].anchor.compute([myOffset.left, myOffset.top], myWH);
  473. this.endpoints[1].paint(anchorLoc);
  474. // *************** create canvas on which the connection will be drawn ************
  475. var canvas = _newCanvas(jsPlumb.connectorClass);
  476. this.canvas = canvas;
  477. /**
  478. * paints the connection.
  479. * @param elId Id of the element that is in motion
  480. * @param ui current library's event system ui object (present if we came from a drag to get here)
  481. * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
  482. */
  483. this.paint = function(elId, ui, recalc) {
  484. if (log) log.debug("Painting Connection; element in motion is " + elId + "; ui is [" + ui + "]; recalc is [" + recalc + "]");
  485. var fai = self.floatingAnchorIndex;
  486. // if the moving object is not the source we must transpose the two references.
  487. var swap = !(elId == this.sourceId);
  488. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  489. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  490. var el = swap ? this.target : this.source;
  491. if (this.canvas.getContext) {
  492. _updateOffset(elId, ui, recalc);
  493. if (recalc) _updateOffset(tId); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  494. var myOffset = offsets[elId];
  495. var otherOffset = offsets[tId];
  496. var myWH = sizes[elId];
  497. var otherWH = sizes[tId];
  498. var ctx = canvas.getContext('2d');
  499. var sAnchorP = this.endpoints[sIdx].anchor.compute([myOffset.left, myOffset.top], myWH, [otherOffset.left, otherOffset.top], otherWH);
  500. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  501. var tAnchorP = this.endpoints[tIdx].anchor.compute([otherOffset.left, otherOffset.top], otherWH, [myOffset.left, myOffset.top], myWH);
  502. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  503. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, this.paintStyle.lineWidth);
  504. jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
  505. jsPlumb.extend(ctx, this.paintStyle);
  506. if (this.paintStyle.gradient && !ie) {
  507. var g = swap ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  508. for (var i = 0; i < this.paintStyle.gradient.stops.length; i++)
  509. g.addColorStop(this.paintStyle.gradient.stops[i][0],this.paintStyle.gradient.stops[i][1]);
  510. ctx.strokeStyle = g;
  511. }
  512. this.connector.paint(dim, ctx);
  513. }
  514. };
  515. this.repaint = function() {
  516. this.paint(this.sourceId, null, true);
  517. };
  518. _initDraggableIfNecessary(self.source, self.sourceId, params.draggable, params.dragOptions);
  519. _initDraggableIfNecessary(self.target, self.targetId, params.draggable, params.dragOptions);
  520. // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
  521. if (this.source.resize) {
  522. this.source.resize(function(e) {
  523. jsPlumb.repaint(self.sourceId);
  524. });
  525. }
  526. };
  527. /*
  528. Class: Endpoint
  529. Models an endpoint. Can have one to N connections emanating from it (although how to handle that in the UI is
  530. a very good question). also has a Canvas and paint style.
  531. */
  532. /*
  533. Function: Endpoint
  534. This is the Endpoint class constructor.
  535. Parameters:
  536. anchor - anchor for the endpoint, of type jsPlumb.Anchor. may be null.
  537. endpoint - endpoint object, of type jsPlumb.Endpoint. may be null.
  538. style - endpoint style, a js object. may be null.
  539. source - element the endpoint is attached to, of type jquery object. Required.
  540. canvas - canvas element to use. may be, and most often is, null.
  541. connections - optional list of connections to configure the endpoint with.
  542. isSource - boolean. indicates the endpoint can act as a source of new connections. optional.
  543. dragOptions - if isSource is set to true, you can supply arguments for the jquery draggable method. optional.
  544. connectionStyle - if isSource is set to true, this is the paint style for connections from this endpoint. optional.
  545. connector - optional connector type to use.
  546. isTarget - boolean. indicates the endpoint can act as a target of new connections. optional.
  547. dropOptions - if isTarget is set to true, you can supply arguments for the jquery droppable method. optional.
  548. reattach - optional boolean that determines whether or not the connections reattach after they
  549. have been dragged off an endpoint and left floating. defaults to false: connections
  550. dropped in this way will just be deleted.
  551. */
  552. var Endpoint = function(params) {
  553. params = params || {};
  554. // make a copy. then we can use the wrapper function.
  555. jsPlumb.extend({}, params);
  556. var self = this;
  557. self.anchor = params.anchor || jsPlumb.Anchors.TopCenter;
  558. var _endpoint = params.endpoint || new jsPlumb.Endpoints.Dot();
  559. var _style = params.style || jsPlumb.Defaults.EndpointStyle;
  560. this.connectorStyle = params.connectorStyle;
  561. this.connector = params.connector;
  562. var _element = params.source;
  563. var _elementId = _getAttribute(_element, "id");
  564. var _maxConnections = params.maxConnections || 1; // maximum number of connections this endpoint can be the source of.
  565. this.canvas = params.canvas || _newCanvas(jsPlumb.endpointClass);
  566. this.connections = params.connections || [];
  567. var _reattach = params.reattach || false;
  568. var floatingEndpoint = null;
  569. var inPlaceCopy = null;
  570. this.addConnection = function(connection) {
  571. self.connections.push(connection);
  572. };
  573. this.removeConnection = function(connection) {
  574. var idx = _findIndex(self.connections, connection);
  575. if (idx >= 0)
  576. self.connections.splice(idx, 1);
  577. };
  578. this.makeInPlaceCopy = function() {
  579. var e = new Endpoint({anchor:self.anchor, source:_element, style:_style, endpoint:_endpoint});
  580. return e;
  581. };
  582. /**
  583. * returns whether or not this endpoint is connected to the given endpoint.
  584. * @param endpoint Endpoint to test.
  585. * @since 1.1.1
  586. *
  587. * todo: needs testing. will this work if the endpoint passed in is the source?
  588. */
  589. this.isConnectedTo = function(endpoint) {
  590. var found = false;
  591. if (endpoint) {
  592. for (var i = 0; i < self.connections.length; i++) {
  593. if (self.connections[i].endpoints[1] == endpoint) {
  594. found = true;
  595. break;
  596. }
  597. }
  598. }
  599. return found;
  600. };
  601. this.isFloating = function() { return floatingEndpoint != null; };
  602. /**
  603. * first pass at default ConnectorSelector: returns the first connection, if we have any.
  604. * modified a little, 5/10/2010: now it only returns a connector if we have not got equal to or more than _maxConnector connectors
  605. * attached. otherwise it is assumed a new connector is ok. but note with this setup we can't select any other connection than the first
  606. * one. what if this could return a list? that implies everything should work with a list - dragging etc. could be nasty. could also
  607. * be cool.
  608. */
  609. var connectorSelector = function() {
  610. return self.connections.length == 0 || self.connections.length < _maxConnections ? null : self.connections[0];
  611. };
  612. this.isFull = function() { return _maxConnections < 1 ? false : (self.connections.length >= _maxConnections); };
  613. /**
  614. * paints the Endpoint, recalculating offset and anchor positions if necessary.
  615. */
  616. this.paint = function(anchorPoint, connectorPaintStyle, canvas) {
  617. if (log) log.debug("Painting Endpoint with elementId [" + _elementId + "]; anchorPoint is [" + anchorPoint + "]");
  618. if (anchorPoint == null) {
  619. // do we always want to force a repaint here? i dont think so!
  620. var xy = offsets[_elementId];
  621. var wh = sizes[_elementId];
  622. if (xy == null || wh == null) {
  623. _updateOffset(_elementId);
  624. xy = offsets[_elementId];
  625. wh = sizes[_elementId];
  626. }
  627. anchorPoint = self.anchor.compute([xy.left, xy.top], wh);
  628. }
  629. _endpoint.paint(anchorPoint, self.anchor.getOrientation(), canvas || self.canvas, _style, connectorPaintStyle || _style);
  630. };
  631. // is this a connection source? we make it draggable and have the drag listener
  632. // maintain a connection with a floating endpoint.
  633. if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  634. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  635. // first the question is, how many connections are on this endpoint? if it's only one, then excellent. otherwise we will either need a way
  636. // to select one connection from the list, or drag them all. if we had a pluggable 'ConnectorSelector' interface we could probably
  637. // provide a way for people to implement their own UI components to do the connector selection. the question in that particular case would be how much
  638. // information the interface needs from jsPlumb at execution time. if, however, we leave out the connector selection, and drag them all,
  639. // that wouldn't be too hard to organise. perhaps that behaviour would be on a switch for the endpoint, or perhaps the ConnectorSelector
  640. // interface returns a List, with the default implementation just returning everything. i think i like that.
  641. //
  642. // let's say for now that there is just one endpoint, cos we need to get this going before we can consider a list of them anyway.
  643. // the major difference between that case and the case of a new endpoint is actually quite small - it's a question of where the
  644. // Connection comes from. for a new one, we create a new one. obviously. otherwise we just get the jpc from the Endpoint
  645. // (remember we're only assuming one connection right now). so all of the UI stuff we do to create the floating endpoint etc
  646. // will still be valid, but when we stop dragging, we'll have to do something different. if we stop with a valid drop i think it will
  647. // be the same process. but if we stop with an invalid drop we have to reset the Connection to how it was when we got it.
  648. var start = function() {
  649. inPlaceCopy = self.makeInPlaceCopy();
  650. inPlaceCopy.paint();
  651. n = document.createElement("div");
  652. _appendCanvas(n);
  653. // create and assign an id, and initialize the offset.
  654. var id = "" + new String(new Date().getTime());
  655. _setAttribute(_getElementObject(n), "id", id);
  656. _updateOffset(id);
  657. // store the id of the dragging div and the source element. the drop function
  658. // will pick these up.
  659. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  660. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  661. // create a floating anchor
  662. var floatingAnchor = new FloatingAnchor({reference:self.anchor, referenceCanvas:self.canvas});
  663. floatingEndpoint = new Endpoint({
  664. style:{fillStyle:'rgba(0,0,0,0)'},
  665. endpoint:_endpoint,
  666. anchor:floatingAnchor,
  667. source:n
  668. });
  669. jpc = connectorSelector();
  670. if (jpc == null) {
  671. // create a connection. one end is this endpoint, the other is a floating endpoint.
  672. jpc = new Connection({
  673. sourceEndpoint:self,
  674. targetEndpoint:floatingEndpoint,
  675. source:_getElementObject(_element),
  676. target:_getElementObject(n),
  677. anchors:[self.anchor, floatingAnchor],
  678. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  679. connector: params.connector
  680. });
  681. // todo ...unregister on stop
  682. self.addConnection(jpc);
  683. } else {
  684. existingJpc = true;
  685. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1;
  686. jpc.floatingAnchorIndex = anchorIdx;
  687. // probably we should remove the connection? and add it back if the user
  688. // does not drop it somewhere proper.
  689. self.removeConnection(jpc);
  690. if (anchorIdx == 0){
  691. existingJpcParams = [jpc.source, jpc.sourceId];
  692. jpc.source = _getElementObject(n);
  693. jpc.sourceId = id;
  694. }else {
  695. existingJpcParams = [jpc.target, jpc.targetId];
  696. jpc.target = _getElementObject(n);
  697. jpc.targetId = id;
  698. }
  699. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  700. jpc.endpoints[anchorIdx] = floatingEndpoint;
  701. }
  702. // register it.
  703. floatingConnections[id] = jpc;
  704. // todo unregister on stop
  705. floatingEndpoint.addConnection(jpc);
  706. // only register for the target endpoint; we will not be dragging the source at any time
  707. // before this connection is either discarded or made into a permanent connection.
  708. _addToList(endpointsByElement, id, floatingEndpoint);
  709. };
  710. var dragOptions = params.dragOptions || { };
  711. var defaultOpts = jsPlumb.extend({}, jsPlumb.CurrentLibrary.defaultDragOptions);
  712. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  713. var startEvent = jsPlumb.CurrentLibrary.dragEvents['start'];
  714. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  715. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  716. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  717. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() {
  718. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  719. _draw(_getElementObject(n), _ui);
  720. });
  721. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  722. function() {
  723. _removeFromList(endpointsByElement, id, floatingEndpoint);
  724. _removeElements([floatingEndpoint.canvas, n, inPlaceCopy.canvas]);
  725. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  726. if (jpc.endpoints[idx] == floatingEndpoint) {
  727. // if the connection was an existing one:
  728. if (existingJpc && jpc.suspendedEndpoint) {
  729. if (_reattach) {
  730. jpc.floatingAnchorIndex = null;
  731. if (idx == 0) {
  732. jpc.source = existingJpcParams[0];
  733. jpc.sourceId = existingJpcParams[1];
  734. } else {
  735. jpc.target = existingJpcParams[0];
  736. jpc.targetId = existingJpcParams[1];
  737. }
  738. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  739. jpc.suspendedEndpoint.addConnection(jpc);
  740. jsPlumb.repaint(existingJpcParams[1]);
  741. }
  742. else {
  743. jpc.endpoints[0].removeConnection(jpc);
  744. jpc.endpoints[1].removeConnection(jpc);
  745. _removeElement(jpc.canvas);
  746. }
  747. } else {
  748. _removeElement(jpc.canvas);
  749. self.removeConnection(jpc);
  750. }
  751. }
  752. jpc = null;
  753. delete floatingEndpoint;
  754. delete inPlaceCopy;
  755. self.paint();
  756. }
  757. );
  758. var i = _getElementObject(self.canvas);
  759. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
  760. };
  761. // connector target
  762. if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  763. var dropOptions = params.dropOptions || jsPlumb.Defaults.DropOptions;
  764. dropOptions = jsPlumb.extend({}, dropOptions);
  765. var originalAnchor = null;
  766. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
  767. var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
  768. var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
  769. dropOptions[dropEvent]= _wrap(dropOptions[dropEvent], function() {
  770. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  771. var id = _getAttribute(_getElementObject(draggable), "dragId");
  772. var elId = _getAttribute(_getElementObject(draggable),"elId");
  773. var jpc = floatingConnections[id];
  774. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  775. if (idx == 0) {
  776. jpc.source = _element;
  777. jpc.sourceId = _elementId;
  778. } else {
  779. jpc.target = _element;
  780. jpc.targetId = _elementId;
  781. }
  782. // remove this jpc from the current endpoint
  783. jpc.endpoints[idx].removeConnection(jpc);
  784. if (jpc.suspendedEndpoint)
  785. jpc.suspendedEndpoint.removeConnection(jpc);
  786. jpc.endpoints[idx] = self;
  787. self.addConnection(jpc);
  788. _initDraggableIfNecessary(_element, _elementId, params.draggable, {});
  789. jsPlumb.repaint(elId);
  790. delete floatingConnections[id];
  791. });
  792. dropOptions[overEvent]= _wrap(dropOptions[overEvent], function() {
  793. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  794. var id = _getAttribute(_getElementObject(draggable),"dragId");
  795. var jpc = floatingConnections[id];
  796. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  797. jpc.endpoints[idx].anchor.over(self.anchor);
  798. });
  799. dropOptions[outEvent] = _wrap(dropOptions[outEvent], function() {
  800. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  801. var id = _getAttribute(_getElementObject(draggable),"dragId");
  802. var jpc = floatingConnections[id];
  803. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  804. jpc.endpoints[idx].anchor.out();
  805. });
  806. jsPlumb.CurrentLibrary.initDroppable(_getElementObject(self.canvas), dropOptions);
  807. }
  808. return self;
  809. };
  810. /*
  811. Class: jsPlumb
  812. This is the main entry point to jsPlumb. There are a bunch of static methods you can
  813. use to connect/disconnect etc. Some methods are also added to jQuery's "$.fn" object itself, but
  814. in general jsPlumb is moving away from that model, preferring instead the static class
  815. approach. One of the reasons for this is that with no methods added to the jQuery $.fn object,
  816. it will be easier to provide support for other libraries such as MooTools.
  817. */
  818. var jsPlumb = window.jsPlumb = {
  819. /*
  820. Property: Defaults
  821. These are the default settings for jsPlumb, that is what will be used if you do not supply specific pieces of information
  822. to the various API calls. A convenient way to implement your own look and feel can be to override these defaults by including a script
  823. somewhere after the jsPlumb include, but before you make any calls to jsPlumb, for instance in this example we set the PaintStyle to be
  824. a blue line of 27 pixels:
  825. > jsPlumb.Defaults.PaintStyle = { lineWidth:27, strokeStyle:'blue' }
  826. */
  827. Defaults : {
  828. Anchors : [ null, null ],
  829. Connector : null,
  830. DragOptions: { },
  831. DropOptions: { },
  832. Endpoint : null,
  833. Endpoints : [ null, null ],
  834. EndpointStyle : { fillStyle : null },
  835. EndpointStyles : [ null, null ],
  836. MaxConnections : null,
  837. PaintStyle : { lineWidth : 10, strokeStyle : 'red' },
  838. Scope : "_jsPlumb_DefaultScope"
  839. },
  840. /*
  841. Property: connectorClass
  842. The CSS class to set on Connection canvas elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  843. */
  844. connectorClass : '_jsPlumb_connector',
  845. /*
  846. Property: endpointClass
  847. The CSS class to set on Endpoint canvas elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  848. */
  849. endpointClass : '_jsPlumb_endpoint',
  850. /*
  851. Property: Anchors
  852. Default jsPlumb Anchors. These are supplied in the file jquery.jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  853. to form jquery.jsPlumb-all-x.x.x.js. You can provide your own Anchors by supplying them in a script that is loaded after jsPlumb, for instance:
  854. > jsPlumb.Anchors.MyAnchor = { ....anchor code here. see the documentation. }
  855. */
  856. Anchors : {},
  857. /*
  858. Property: Connectors
  859. Default jsPlumb Connectors. These are supplied in the file jquery.jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  860. to form jquery.jsPlumb-all-x.x.x.js. You can provide your own Connectors by supplying them in a script that is loaded after jsPlumb, for instance:
  861. > jsPlumb.Connectors.MyConnector = { ....connector code here. see the documentation. }
  862. */
  863. Connectors : {},
  864. /*
  865. Property: Endpoints
  866. Default jsPlumb Endpoints. These are supplied in the file jquery.jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  867. to form jquery.jsPlumb-all-x.x.x.js. You can provide your own Endpoints by supplying them in a script that is loaded after jsPlumb, for instance:
  868. > jsPlumb.Endpoints.MyEndpoint = { ....endpoint code here. see the documentation. }
  869. */
  870. Endpoints : {},
  871. /*
  872. Function: addEndpoint
  873. Adds an Endpoint to a given element.
  874. Parameters:
  875. target - Element to add the endpoint to. either an element id, or a jQuery object representing some element.
  876. params - Object containing Endpoint options (more info required)
  877. Returns:
  878. The newly created Endpoint.
  879. See Also:
  880. <addEndpoints>
  881. */
  882. addEndpoint : function(target, params) {
  883. params = jsPlumb.extend({}, params);
  884. var el = _getElementObject(target);
  885. var id = _getAttribute(target,"id");
  886. params.source = el;
  887. _updateOffset(id);
  888. var e = new Endpoint(params);
  889. _addToList(endpointsByElement, id, e);
  890. var myOffset = offsets[id];
  891. var myWH = sizes[id];
  892. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH);
  893. e.paint(anchorLoc);
  894. return e;
  895. },
  896. /*
  897. Function: addEndpoint
  898. Adds a list of Endpoints to a given element.
  899. Parameters:
  900. target - element to add the endpoint to. either an element id, or a jQuery object representing some element.
  901. endpoints - List of objects containing Endpoint options. one Endpoint is created for each entry in this list.
  902. Returns:
  903. List of newly created Endpoints, one for each entry in the 'endpoints' argument.
  904. See Also:
  905. <addEndpoint>
  906. */
  907. addEndpoints : function(target, endpoints) {
  908. var results = [];
  909. for (var i = 0; i < endpoints.length; i++) {
  910. results.push(jsPlumb.addEndpoint(target, endpoints[i]));
  911. }
  912. return results;
  913. },
  914. /*
  915. Function: animate
  916. Wrapper around standard jQuery animate function; injects a call to jsPlumb in the 'step' function (creating it if necessary).
  917. This only supports the two-arg version of the animate call in jQuery - the one that takes an 'options' object as the second arg.
  918. Parameters:
  919. el - Element to animate. Either an id, or a jQuery object representing the element.
  920. properties - The 'properties' argument you want passed to the standard jQuery animate call.
  921. options - The 'options' argument you want passed to the standard jQuery animate call.
  922. Returns:
  923. void
  924. */
  925. animate : function(el, properties, options) {
  926. var ele = _getElementObject(el);
  927. var id = _getAttribute(el,"id");
  928. //TODO this is not agnostic yet.
  929. options = options || {};
  930. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  931. options[stepFunction] = _wrap(options[stepFunction], function()
  932. {
  933. jsPlumb.repaint(id);
  934. });
  935. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  936. },
  937. /*
  938. Function: connect
  939. Establishes a connection between two elements.
  940. Parameters:
  941. params - Object containing setup for the connection. see documentation.
  942. Returns:
  943. The newly created Connection.
  944. */
  945. connect : function(params) {
  946. if (params.sourceEndpoint && params.sourceEndpoint.isFull()) {
  947. _log("could not add connection; source endpoint is full");
  948. return;
  949. }
  950. if (params.targetEndpoint && params.targetEndpoint.isFull()) {
  951. _log("could not add connection; target endpoint is full");
  952. return;
  953. }
  954. var jpc = new Connection(params);
  955. // register endpoints for the element. todo: is the test below sufficient? or should we test if the endpoint is already in the list,
  956. // and add it only then? perhaps _addToList could be overloaded with a a 'test for existence first' parameter?
  957. //_addToList(endpointsByElement, jpc.sourceId, jpc.endpoints[0]);
  958. //_addToList(endpointsByElement, jpc.targetId, jpc.endpoints[1]);
  959. if (!params.sourceEndpoint) _addToList(endpointsByElement, jpc.sourceId, jpc.endpoints[0]);
  960. if (!params.targetEndpoint) _addToList(endpointsByElement, jpc.targetId, jpc.endpoints[1]);
  961. jpc.endpoints[0].addConnection(jpc);
  962. jpc.endpoints[1].addConnection(jpc);
  963. // force a paint
  964. _draw(jpc.source);
  965. return jpc;
  966. },
  967. /**
  968. * not implemented yet. params object will have sourceEndpoint and targetEndpoint members; these will be Endpoints.
  969. connectEndpoints : function(params) {
  970. var jpc = Connection(params);
  971. },*/
  972. /*
  973. Function: detach
  974. Removes a connection.
  975. Parameters:
  976. sourceId - Id of the first element in the connection. A String.
  977. targetId - iI of the second element in the connection. A String.
  978. Returns:
  979. true if successful, false if not.
  980. */
  981. detach : function(sourceId, targetId) {
  982. var f = function(jpc) {
  983. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  984. _removeElement(jpc.canvas);
  985. jpc.endpoints[0].removeConnection(jpc);
  986. jpc.endpoints[1].removeConnection(jpc);
  987. return true;
  988. }
  989. };
  990. // todo: how to cleanup the actual storage? a third arg to _operation?
  991. _operation(sourceId, f);
  992. },
  993. /*
  994. Function: detachAll
  995. Removes all an element's connections.
  996. Parameters:
  997. el - either the id of the element, or a jQuery object for the element.
  998. Returns:
  999. void
  1000. */
  1001. detachAll : function(el) {
  1002. var id = _getAttribute(el, "id");
  1003. var endpoints = endpointsByElement[id];
  1004. if (endpoints && endpoints.length) {
  1005. for (var i = 0; i < endpoints.length; i++) {
  1006. var c = endpoints[i].connections.length;
  1007. if (c > 0) {
  1008. for (var j = 0; j < c; j++) {
  1009. var jpc = endpoints[i].connections[0];
  1010. _removeElement(jpc.canvas);
  1011. jpc.endpoints[0].removeConnection(jpc);
  1012. jpc.endpoints[1].removeConnection(jpc);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. },
  1018. /*
  1019. Function: detachEverything
  1020. Remove all Connections from all elements, but leaves Endpoints in place.
  1021. Returns:
  1022. void
  1023. See Also:
  1024. <removeAllEndpoints>
  1025. */
  1026. detachEverything : function() {
  1027. for(var id in endpointsByElement) {
  1028. var endpoints = endpointsByElement[id];
  1029. if (endpoints && endpoints.length) {
  1030. for (var i = 0; i < endpoints.length; i++) {
  1031. var c = endpoints[i].connections.length;
  1032. if (c > 0) {
  1033. for (var j = 0; j < c; j++) {
  1034. var jpc = endpoints[i].connections[0];
  1035. _removeElement(jpc.canvas);
  1036. jpc.endpoints[0].removeConnection(jpc);
  1037. jpc.endpoints[1].removeConnection(jpc);
  1038. }
  1039. }
  1040. }
  1041. }
  1042. }
  1043. },
  1044. extend : function(o1, o2) {
  1045. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1046. },
  1047. /*
  1048. Function: hide
  1049. Sets an element's connections to be hidden.
  1050. Parameters:
  1051. el - either the id of the element, or a jQuery object for the element.
  1052. Returns:
  1053. void
  1054. */
  1055. hide : function(el) {
  1056. _setVisible(el, "none");
  1057. },
  1058. /*
  1059. Function: makeAnchor
  1060. Creates an anchor with the given params.
  1061. Parameters:
  1062. x - the x location of the anchor as a fraction of the total width.
  1063. y - the y location of the anchor as a fraction of the total height.
  1064. xOrientation - value indicating the general direction a connection from the anchor should go in, in the x direction.
  1065. yOrientation - value indicating the general direction a connection from the anchor should go in, in the y direction.
  1066. xOffset - a fixed offset that should be applied in the x direction that should be applied after the x position has been figured out. optional. defaults to 0.
  1067. yOffset - a fixed offset that should be applied in the y direction that should be applied after the y position has been figured out. optional. defaults to 0.
  1068. Returns:
  1069. The newly created Anchor.
  1070. */
  1071. makeAnchor : function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1072. // backwards compatibility here. we used to require an object passed in but that makes the call very verbose. easier to use
  1073. // by just passing in four/six values. but for backwards compatibility if we are given only one value we assume it's a call in the old form.
  1074. var params = {};
  1075. if (arguments.length == 1) jsPlumb.extend(params, x);
  1076. else {
  1077. params = {x:x, y:y};
  1078. if (arguments.length >= 4) {
  1079. params.orientation = [arguments[2], arguments[3]];
  1080. }
  1081. if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
  1082. }
  1083. return new Anchor(params);
  1084. },
  1085. /*
  1086. Function: repaint
  1087. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1088. Parameters:
  1089. el - either the id of the element or a jQuery object representing the element.
  1090. Returns:
  1091. void
  1092. See Also:
  1093. <repaintEverything>
  1094. */
  1095. repaint : function(el) {
  1096. var _processElement = function(el) {
  1097. var ele = _getElementObject(el);
  1098. _draw(ele);
  1099. };
  1100. // TODO: support a jQuery result object too!
  1101. // support both lists...
  1102. if (typeof el =='object') {
  1103. for (var i = 0; i < el.length; i++)
  1104. _processElement(el[i]);
  1105. } // ...and single strings.
  1106. else _processElement(el);
  1107. },
  1108. /*
  1109. Function: repaintEverything
  1110. Repaints all connections.
  1111. Returns:
  1112. void
  1113. See Also:
  1114. <repaint>
  1115. */
  1116. repaintEverything : function() {
  1117. for (var elId in endpointsByElement) {
  1118. _draw(_getElementObject(elId));
  1119. }
  1120. },
  1121. /*
  1122. Function: removeAllEndpoints
  1123. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1124. Parameters:
  1125. el - either an element id, or a jQuery object for an element.
  1126. Returns:
  1127. void
  1128. See Also:
  1129. <removeEndpoint>
  1130. */
  1131. removeAllEndpoints : function(el) {
  1132. var elId = _getAttribute(el, "id");
  1133. // first remove all Connections.
  1134. jsPlumb.detachAll(elId);
  1135. var ebe = endpointsByElement[elId];
  1136. for (var i in ebe) {
  1137. _removeElement(ebe[i].canvas);
  1138. }
  1139. endpointsByElement[elId] = [];
  1140. },
  1141. /*
  1142. Function: removeEndpoint
  1143. Removes the given Endpoint from the given element.
  1144. Parameters:
  1145. el - either an element id, or a jQuery object for an element.
  1146. endpoint - Endpoint to remove. this is an Endpoint object, such as would have been returned from a call to addEndpoint.
  1147. Returns:
  1148. void
  1149. See Also:
  1150. <removeAllEndpoints>
  1151. */
  1152. removeEndpoint : function(el, endpoint) {
  1153. var elId = _getAttribute(el, "id");
  1154. var ebe = endpointsByElement[elId];
  1155. if (ebe) {
  1156. if(_removeFromList(endpointsByElement, elId, endpoint))
  1157. _removeElement(endpoint.canvas);
  1158. }
  1159. },
  1160. /*
  1161. Function: setAutomaticRepaint
  1162. Sets/unsets automatic repaint on window resize.
  1163. Parameters:
  1164. value - whether or not to automatically repaint when the window is resized.
  1165. Returns:
  1166. void
  1167. */
  1168. setAutomaticRepaint : function(value) {
  1169. automaticRepaint = value;
  1170. },
  1171. /*
  1172. Function: setDefaultNewCanvasSize
  1173. Sets the default size jsPlumb will use for a new canvas (we create a square canvas so one value is all that is required).
  1174. This is a hack for IE, because ExplorerCanvas seems to need for a canvas to be larger than what you are going to draw on
  1175. it at initialisation time. The default value of this is 1200 pixels, which is quite large, but if for some reason you're
  1176. drawing connectors that are bigger, you should adjust this value appropriately.
  1177. Parameters:
  1178. size - The default size to use. jsPlumb will use a square canvas so you need only supply one value.
  1179. Returns:
  1180. void
  1181. */
  1182. setDefaultNewCanvasSize : function(size) {
  1183. DEFAULT_NEW_CANVAS_SIZE = size;
  1184. },
  1185. /*
  1186. Function: setDraggable
  1187. Sets whether or not a given element is draggable, regardless of what any plumb command may request.
  1188. Parameters:
  1189. el - either the id for the element, or a jQuery object representing the element.
  1190. Returns:
  1191. void
  1192. */
  1193. setDraggable: _setDraggable,
  1194. /*
  1195. Function: setDraggableByDefault
  1196. Sets whether or not elements are draggable by default. Default for this is true.
  1197. Parameters:
  1198. draggable - value to set
  1199. Returns:
  1200. void
  1201. */
  1202. setDraggableByDefault: function(draggable) {
  1203. _draggableByDefault = draggable;
  1204. },
  1205. setDebugLog: function(debugLog) {
  1206. log = debugLog;
  1207. },
  1208. /*
  1209. Function: setRepaintFunction
  1210. Sets the function to fire when the window size has changed and a repaint was fired.
  1211. Parameters:
  1212. f - Function to execute.
  1213. Returns:
  1214. void
  1215. */
  1216. setRepaintFunction : function(f) {
  1217. repaintFunction = f;
  1218. },
  1219. /*
  1220. Function: show
  1221. Sets an element's connections to be visible.
  1222. Parameters:
  1223. el - either the id of the element, or a jQuery object for the element.
  1224. Returns:
  1225. void
  1226. */
  1227. show : function(el) {
  1228. _setVisible(el, "block");
  1229. },
  1230. /*
  1231. Function: sizeCanvas
  1232. Helper to size a canvas. You would typically use this when writing your own Connector or Endpoint implementation.
  1233. Parameters:
  1234. x - [int] x position for the Canvas origin
  1235. y - [int] y position for the Canvas origin
  1236. w - [int] width of the canvas
  1237. h - [int] height of the canvas
  1238. Returns:
  1239. void
  1240. */
  1241. sizeCanvas : function(canvas, x, y, w, h) {
  1242. if (canvas) {
  1243. canvas.style.height = h + "px"; canvas.height = h;
  1244. canvas.style.width = w + "px"; canvas.width = w;
  1245. canvas.style.left = x + "px"; canvas.style.top = y + "px";
  1246. }
  1247. },
  1248. /**
  1249. * gets some test hooks. nothing writable.
  1250. */
  1251. getTestHarness : function() {
  1252. return {
  1253. endpointCount : function(elId) {
  1254. var e = endpointsByElement[elId];
  1255. return e ? e.length : 0;
  1256. },
  1257. findIndex : _findIndex
  1258. };
  1259. },
  1260. /**
  1261. * Toggles visibility of an element's connections. kept for backwards compatibility
  1262. */
  1263. toggle : _toggleVisible,
  1264. /*
  1265. Function: toggleVisible
  1266. Toggles visibility of an element's connections.
  1267. Parameters:
  1268. el - either the element's id, or a jQuery object representing the element.
  1269. Returns:
  1270. void, but should be updated to return the current state
  1271. */
  1272. //TODO: update this method to return the current state.
  1273. toggleVisible : _toggleVisible,
  1274. /*
  1275. Function: toggleDraggable
  1276. Toggles draggability (sic) of an element's connections.
  1277. Parameters:
  1278. el - either the element's id, or a jQuery object representing the element.
  1279. Returns:
  1280. The current draggable state.
  1281. */
  1282. toggleDraggable : _toggleDraggable,
  1283. /*
  1284. Function: unload
  1285. Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element
  1286. Returns:
  1287. void
  1288. */
  1289. unload : function() {
  1290. delete endpointsByElement;
  1291. delete offsets;
  1292. delete sizes;
  1293. delete floatingConnections;
  1294. delete draggableStates;
  1295. },
  1296. /*
  1297. Function: wrap
  1298. Helper method to wrap an existing function with one of your own. This is used by the various
  1299. implementations to wrap event callbacks for drag/drop etc; it allows jsPlumb to be
  1300. transparent in its handling of these things. If a user supplies their own event callback,
  1301. for anything, it will always be called.
  1302. Parameters:
  1303. */
  1304. wrap : _wrap
  1305. };
  1306. })();