jquery.jsPlumb-1.2.1-all.js 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  1. /*
  2. * jsPlumb 1.2.1
  3. *
  4. * Provides a way to visually connect elements on an HTML page.
  5. *
  6. * Several enhancements were added in 1.2.1
  7. *
  8. * - supports multiple jsplumb instances on the same page.
  9. * - added getConnections() method; you can see what's connected to what.
  10. * - supports containers; jsplumb adds elements to a container rather than the window.
  11. * - various convenience methods added - removeEveryEndpoint, reset, etc. see docs.
  12. *
  13. * http://morrisonpitt.com/jsPlumb/demo.html
  14. * http://code.google.com/p/jsPlumb
  15. *
  16. */
  17. (function() {
  18. /*
  19. Class: jsPlumb
  20. This is the main entry point to jsPlumb. There are a bunch of static methods you can
  21. use to connect/disconnect etc. Some methods are also added to jQuery's "$.fn" object itself, but
  22. in general jsPlumb is moving away from that model, preferring instead the static class
  23. approach. One of the reasons for this is that with no methods added to the jQuery $.fn object,
  24. it will be easier to provide support for other libraries such as MooTools.
  25. */
  26. var jsPlumbInstance = function() {
  27. var _currentInstance = this;
  28. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  29. var log = null;
  30. var repaintFunction = function() { jsPlumb.repaintEverything(); };
  31. var automaticRepaint = true;
  32. function repaintEverything() {
  33. if (automaticRepaint)
  34. repaintFunction();
  35. };
  36. var resizeTimer = null;
  37. /**
  38. * map of element id -> endpoint lists. an element can have an arbitrary number of endpoints on it,
  39. * and not all of them have to be connected to anything.
  40. */
  41. var endpointsByElement = {};
  42. var connectionsByScope = {};
  43. var offsets = [];
  44. var floatingConnections = {};
  45. var draggableStates = {};
  46. var _draggableByDefault = true;
  47. var sizes = [];
  48. var DEFAULT_SCOPE = 'DEFAULT';
  49. 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.)
  50. var traced = {};
  51. var _trace = function(category, event) {
  52. var e = traced[category];
  53. if (!e) {
  54. e = {};
  55. traced[category] = e;
  56. }
  57. event = event || 'DEFAULT';
  58. var ee = e[event];
  59. if (!ee) {
  60. ee = 0;
  61. e[event] = ee;
  62. }
  63. e[event]++;
  64. };
  65. var _clearAllTraces = function() {
  66. delete traced;
  67. traced = {};
  68. };
  69. var _clearTrace = function(category, event) {
  70. var c = traced[category];
  71. if (!c) return;
  72. if (event) {
  73. c[event] = 0;
  74. }
  75. else c['DEFAULT'] = 0;
  76. };
  77. var _getTrace = function(category) {
  78. return traced[category] || {'DEFAULT' : 0 };
  79. };
  80. var _findIndex = function( a, v, b, s ) {
  81. var _eq = function(o1, o2) {
  82. if (o1 === o2) return true;
  83. else if (typeof o1 == 'object' && typeof o2 == 'object') {
  84. var same = true;
  85. for(var propertyName in o1) {
  86. if(!_eq(o1[propertyName], o2[propertyName])) {
  87. same = false;
  88. break;
  89. }
  90. }
  91. for(var propertyName in o2) {
  92. if(!_eq(o2[propertyName], o1[propertyName])) {
  93. same = false;
  94. break;
  95. }
  96. }
  97. return same;
  98. }
  99. };
  100. for( var i = +b || 0, l = a.length; i < l; i++ ) {
  101. if( _eq(a[i], v)) return i;
  102. }
  103. return -1;
  104. };
  105. /**
  106. * helper method to add an item to a list, creating the list if it does not yet exist.
  107. */
  108. var _addToList = function(map, key, value) {
  109. var l = map[key];
  110. if (l == null) {
  111. l = [];
  112. map[key] = l;
  113. }
  114. l.push(value);
  115. return l;
  116. };
  117. /**
  118. * Handles the dragging of an element.
  119. * @param element jQuery element
  120. * @param ui UI object from current library's event system
  121. */
  122. var _draw = function(element, ui) {
  123. var id = _getAttribute(element, "id");
  124. var endpoints = endpointsByElement[id];
  125. if (endpoints) {
  126. var timestamp = '' + (new Date().getTime());
  127. _trace('draw');
  128. _updateOffset(id, ui);
  129. var myOffset = offsets[id];
  130. var myWH = sizes[id];
  131. // loop through endpoints for this element
  132. for (var i = 0; i < endpoints.length; i++) {
  133. var e = endpoints[i];
  134. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH, e);
  135. e.paint(anchorLoc);
  136. var l = e.connections;
  137. for (var j = 0; j < l.length; j++)
  138. l[j].paint(id, ui, false, timestamp); // ...and paint them.
  139. }
  140. }
  141. };
  142. /**
  143. * helper function: the second argument is a function taking two args - the first is an id
  144. * ui element from the current library (or list of them), and the second is the function
  145. * to run.
  146. */
  147. var _elementProxy = function(element, fn) {
  148. var retVal = null;
  149. // TODO this might be jquery specific. in fact it probably is.
  150. if (typeof element == 'object' && element.length) {
  151. retVal = [];
  152. for (var i = 0; i < element.length; i++) {
  153. var el = _getElementObject(element[i]);
  154. var id = _getAttribute(el, "id");
  155. retVal.push(fn(el, id)); // append return values to what we will return
  156. }
  157. }
  158. else {
  159. var el = _getElementObject(element);
  160. var id = _getAttribute(el, "id");
  161. retVal = fn(el, id);
  162. }
  163. return retVal;
  164. };
  165. var _log = function(msg) {
  166. //if (console) console.log(msg);
  167. };
  168. var _logFnCall = function(fn, args) {
  169. /*if (console) {
  170. var c = args.callee.caller.toString();
  171. var i = c.indexOf("{");
  172. var msg = fn + ' : ' + c.substring(0, i);
  173. console.log(msg);
  174. }*/
  175. };
  176. var cached = {};
  177. var __getElementObject = function(el) {
  178. if (typeof(el)=='string') {
  179. var e = cached[el];
  180. if (!e) {
  181. e = jsPlumb.CurrentLibrary.getElementObject(el);
  182. cached[el] = e;
  183. }
  184. return e;
  185. }
  186. else {
  187. return jsPlumb.CurrentLibrary.getElementObject(el);
  188. }
  189. };
  190. /**
  191. * gets the named attribute from the given element (id or element object)
  192. */
  193. var _getAttribute = function(el, attName) {
  194. var ele = __getElementObject(el);
  195. return jsPlumb.CurrentLibrary.getAttribute(ele, attName);
  196. };
  197. var _setAttribute = function(el, attName, attValue) {
  198. var ele = __getElementObject(el);
  199. jsPlumb.CurrentLibrary.setAttribute(ele, attName, attValue);
  200. };
  201. var _addClass = function(el, clazz) {
  202. var ele = __getElementObject(el);
  203. jsPlumb.CurrentLibrary.addClass(ele, clazz);
  204. };
  205. var _getElementObject = function(elId) {
  206. return __getElementObject(elId);
  207. };
  208. var _getOffset = function(el) {
  209. var ele = __getElementObject(el);
  210. return jsPlumb.CurrentLibrary.getOffset(ele);
  211. };
  212. var _getSize = function(el) {
  213. var ele = __getElementObject(el);
  214. return jsPlumb.CurrentLibrary.getSize(ele);
  215. };
  216. var _appendElement = function(canvas, parent) {
  217. if (!parent) document.body.appendChild(canvas);
  218. else jsPlumb.CurrentLibrary.appendElement(canvas, parent);
  219. };
  220. /**
  221. * gets an id for the given element, creating and setting one if necessary.
  222. */
  223. var _getId = function(element) {
  224. var ele = _getElementObject(element);
  225. var id = _getAttribute(ele, "id");
  226. if (!id) {
  227. id = "_jsPlumb_" + new String((new Date()).getTime());
  228. _setAttribute(ele, "id", id);
  229. }
  230. return id;
  231. };
  232. /**
  233. * inits a draggable if it's not already initialised.
  234. *
  235. * TODO: we need to hook in each library to this method. they need to be given the opportunity to
  236. * wrap/insert lifecycle functions, because each library does different things. for instance, jQuery
  237. * supports the notion of 'revert', which will clean up a dragged endpoint; MooTools does not. jQuery
  238. * also supports 'opacity' and MooTools does not; jQuery supports z-index of the draggable; MooTools
  239. * does not. i could go on. the point is...oh. initDraggable can do this. ok.
  240. */
  241. var _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  242. // dragging
  243. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  244. if (draggable) {
  245. if (jsPlumb.CurrentLibrary.isDragSupported(element)) {
  246. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  247. options = jsPlumb.extend({}, options); // make a copy.
  248. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  249. options[dragEvent] = _wrap(options[dragEvent], function() {
  250. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  251. _draw(element, ui);
  252. _addClass(element, "jsPlumb_dragged");
  253. });
  254. var draggable = draggableStates[_getId(element)];
  255. options.disabled = draggable == null ? false : !draggable;
  256. jsPlumb.CurrentLibrary.initDraggable(element, options);
  257. }
  258. }
  259. };
  260. /**
  261. * helper to create a canvas.
  262. * @param clazz optional class name for the canvas.
  263. */
  264. var _newCanvas = function(clazz, parent) {
  265. var canvas = document.createElement("canvas");
  266. _appendElement(canvas, parent);
  267. canvas.style.position="absolute";
  268. if (clazz) { canvas.className=clazz; }
  269. _getId(canvas); // set an id.
  270. if (ie) {
  271. // for IE we have to set a big canvas size. actually you can override this, too, if 1200 pixels
  272. // is not big enough for the biggest connector/endpoint canvas you have at startup.
  273. jsPlumb.sizeCanvas(canvas, 0, 0, DEFAULT_NEW_CANVAS_SIZE, DEFAULT_NEW_CANVAS_SIZE);
  274. canvas = G_vmlCanvasManager.initElement(canvas);
  275. }
  276. return canvas;
  277. };
  278. /**
  279. * performs the given function operation on all the connections found for the given element
  280. * id; this means we find all the endpoints for the given element, and then for each endpoint
  281. * find the connectors connected to it. then we pass each connection in to the given
  282. * function.
  283. */
  284. var _operation = function(elId, func) {
  285. var endpoints = endpointsByElement[elId];
  286. if (endpoints && endpoints.length) {
  287. for (var i = 0; i < endpoints.length; i++) {
  288. for (var j = 0; j < endpoints[i].connections.length; j++) {
  289. var retVal = func(endpoints[i].connections[j]);
  290. // if the function passed in returns true, we exit.
  291. // most functions return false.
  292. if (retVal) return;
  293. }
  294. }
  295. }
  296. };
  297. /**
  298. * perform an operation on all elements.
  299. */
  300. var _operationOnAll = function(func) {
  301. for (var elId in endpointsByElement) {
  302. _operation(elId, func);
  303. }
  304. };
  305. /**
  306. * helper to remove an element from the DOM.
  307. */
  308. var _removeElement = function(element, parent) {
  309. if (element != null) {
  310. if (!parent) {
  311. try { document.body.removeChild(element); }
  312. catch (e) { }
  313. } else {
  314. jsPlumb.CurrentLibrary.removeElement(element, parent);
  315. }
  316. }
  317. };
  318. /**
  319. * helper to remove a list of elements from the DOM.
  320. */
  321. var _removeElements = function(elements, parent) {
  322. for (var i in elements)
  323. _removeElement(elements[i], parent);
  324. };
  325. /**
  326. * helper method to remove an item from a list.
  327. */
  328. var _removeFromList = function(map, key, value) {
  329. var l = map[key];
  330. if (l != null) {
  331. var i = _findIndex(l, value);
  332. if (i >= 0) {
  333. delete( l[i] );
  334. l.splice( i, 1 );
  335. return true;
  336. }
  337. }
  338. return false;
  339. };
  340. /**
  341. * Sets whether or not the given element(s) should be draggable, regardless of what a particular
  342. * plumb command may request.
  343. *
  344. * @param element May be a string, a jQuery elements, or a list of strings/jquery elements.
  345. * @param draggable Whether or not the given element(s) should be draggable.
  346. */
  347. var _setDraggable = function(element, draggable) {
  348. var _helper = function(el, id) {
  349. draggableStates[id] = draggable;
  350. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  351. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  352. }
  353. };
  354. return _elementProxy(element, _helper);
  355. };
  356. /**
  357. * private method to do the business of hiding/showing.
  358. * @param el either Id of the element in question or a jquery object for the element.
  359. * @param state String specifying a value for the css 'display' property ('block' or 'none').
  360. */
  361. var _setVisible = function(el, state) {
  362. var elId = _getAttribute(el, "id");
  363. var f = function(jpc) {
  364. jpc.canvas.style.display = state;
  365. };
  366. _operation(elId, f);
  367. };
  368. /**
  369. * toggles the draggable state of the given element(s).
  370. * @param el either an id, or a jquery object, or a list of ids/jquery objects.
  371. */
  372. var _toggleDraggable = function(el) {
  373. var fn = function(el, elId) {
  374. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  375. state = !state;
  376. draggableStates[elId] = state;
  377. jsPlumb.CurrentLibrary.setDraggable(el, state);
  378. return state;
  379. };
  380. return _elementProxy(el, fn);
  381. };
  382. /**
  383. * private method to do the business of toggling hiding/showing.
  384. * @param elId Id of the element in question
  385. */
  386. var _toggleVisible = function(elId) {
  387. var f = function(jpc) {
  388. var state = ('none' == jpc.canvas.style.display);
  389. jpc.canvas.style.display = state ? "block" : "none";
  390. };
  391. _operation(elId, f);
  392. //todo this should call _elementProxy, and pass in the _operation(elId, f) call as a function. cos _toggleDraggable does that.
  393. };
  394. /**
  395. * updates the offset and size for a given element, and stores the values.
  396. * 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,
  397. * or if 'recalc' is true in order to force a recalculation, we use the offset, outerWidth and outerHeight methods to get
  398. * the current values.
  399. */
  400. var _updateOffset = function(elId, offset, recalc) {
  401. if (recalc || offset == null) { // if forced repaint or no offset available, we recalculate.
  402. // get the current size and offset, and store them
  403. var s = _getElementObject(elId);
  404. sizes[elId] = _getSize(s);
  405. offsets[elId] = _getOffset(s);
  406. } else {
  407. offsets[elId] = offset;
  408. }
  409. };
  410. /**
  411. * wraps one function with another, creating a placeholder for the wrapped function
  412. * if it was null. this is used to wrap the various drag/drop event functions - to allow
  413. * jsPlumb to be notified of important lifecycle events without imposing itself on the user's
  414. * drap/drop functionality.
  415. * TODO: determine whether or not we should support an error handler concept, if one of the functions fails.
  416. */
  417. var _wrap = function(wrappedFunction, newFunction) {
  418. wrappedFunction = wrappedFunction || function() { };
  419. newFunction = newFunction || function() { };
  420. return function() {
  421. try { newFunction.apply(this, arguments); }
  422. catch (e) {
  423. _log('jsPlumb function failed : ' + e);
  424. }
  425. try { wrappedFunction.apply(this, arguments); }
  426. catch (e) {
  427. _log('wrapped function failed : ' + e);
  428. }
  429. };
  430. };
  431. /*
  432. Class: Anchor
  433. Models a position relative to the origin of some element that an Endpoint can be located.
  434. */
  435. /*
  436. Function: Anchor
  437. Constructor for the Anchor class
  438. Parameters:
  439. params - Anchor parameters. This should contain three values, and may optionally have an 'offsets' argument:
  440. - x : the x location of the anchor as a fraction of the total width.
  441. - y : the y location of the anchor as a fraction of the total height.
  442. - 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.
  443. - offsets : an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out. may be null.
  444. */
  445. var Anchor = function(params) {
  446. var self = this;
  447. this.x = params.x || 0; this.y = params.y || 0;
  448. var orientation = params.orientation || [0,0];
  449. var lastTimestamp = null;
  450. var lastReturnValue = null;
  451. this.offsets = params.offsets || [0,0];
  452. //TODO: fix this properly. since Anchors are often static, this timestamping business
  453. // does not work at all well. the timestamp should be inside the Endpoint, because they
  454. // are _never_ static. the method that Connection uses to find an anchor location should
  455. // be done through the Endpoint class, which can then deal with the timestamp.
  456. // and, in fact, we should find out whether or not we even get a speed enhancement from doing
  457. // this.
  458. this.compute = function(xy, wh, element) {
  459. _trace('anchor compute');
  460. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1]];
  461. var container = element? element.container : null;
  462. var containerAdjustment = {left:0, top:0 };
  463. if (container != null) {
  464. var eo = _getElementObject(container);
  465. var o = _getOffset(eo);
  466. var sl = jsPlumb.CurrentLibrary.getScrollLeft(eo);
  467. var st = jsPlumb.CurrentLibrary.getScrollTop(eo);
  468. containerAdjustment.left = o.left - sl;
  469. containerAdjustment.top = o.top - st;
  470. lastReturnValue[0] = lastReturnValue[0] - containerAdjustment.left;
  471. lastReturnValue[1] = lastReturnValue[1] - containerAdjustment.top;
  472. }
  473. return lastReturnValue;
  474. };
  475. this.getOrientation = function() { return orientation; };
  476. this.equals = function(anchor) {
  477. if (!anchor) return false;
  478. var ao = anchor.getOrientation();
  479. var o = this.getOrientation();
  480. return this.x == anchor.x && this.y == anchor.y && this.offsets[0] == anchor.offsets[0] && this.offsets[1] == anchor.offsets[1] && o[0] == ao[0] && o[1] == ao[1];
  481. };
  482. };
  483. /**
  484. * An Anchor that floats. its orientation is computed dynamically from its position relative to the anchor it is floating relative to.
  485. *
  486. */
  487. var FloatingAnchor = function(params) {
  488. // this is the anchor that this floating anchor is referenced to for purposes of calculating the orientation.
  489. var ref = params.reference;
  490. // the canvas this refers to.
  491. var refCanvas = params.referenceCanvas;
  492. var size = _getSize(_getElementObject(refCanvas));
  493. // these are used to store the current relative position of our anchor wrt the reference anchor. they only indicate
  494. // direction, so have a value of 1 or -1 (or, very rarely, 0). these values are written by the compute method, and read
  495. // by the getOrientation method.
  496. var xDir = 0, yDir = 0;
  497. // temporary member used to store an orientation when the floating anchor is hovering over another anchor.
  498. var orientation = null;
  499. this.compute = function(xy, wh, txy, twh) {
  500. // set these for the getOrientation method to use.
  501. xDir = 0;//xy[0] < txy[0] ? -1 : xy[0] == txy[0] ? 0 : 1;
  502. yDir = 0;//xy[1] < txy[1] ? -1 : xy[1] == txy[1] ? 0 : 1;
  503. 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.
  504. };
  505. this.getOrientation = function() {
  506. if (orientation) return orientation;
  507. else {
  508. var o = ref.getOrientation();
  509. // here we take into account the orientation of the other anchor: if it declares zero for some direction, we declare zero too.
  510. // 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
  511. // like it makes sense. maybe this wont make sense.
  512. return [Math.abs(o[0]) * xDir * -1, Math.abs(o[1]) * yDir * -1];
  513. }
  514. };
  515. /**
  516. * notification the endpoint associated with this anchor is hovering over another anchor;
  517. * we want to assume that anchor's orientation for the duration of the hover.
  518. */
  519. this.over = function(anchor) {
  520. orientation = anchor.getOrientation();
  521. };
  522. /**
  523. * notification the endpoint associated with this anchor is no longer hovering
  524. * over another anchor; we should resume calculating orientation as we normally do.
  525. */
  526. this.out = function() {
  527. orientation = null;
  528. };
  529. };
  530. // ************** connection
  531. // ****************************************
  532. /**
  533. * allowed params:
  534. * source: source element (string or a jQuery element) (required)
  535. * target: target element (string or a jQuery element) (required)
  536. *
  537. * anchors: optional array of anchor placements. defaults to BottomCenter for source
  538. * and TopCenter for target.
  539. */
  540. var Connection = function(params) {
  541. // ************** get the source and target and register the connection. *******************
  542. var self = this;
  543. var id = new String('_jsplumb_c_' + (new Date()).getTime());
  544. this.getId = function() { return id; };
  545. this.container = params.container || _currentInstance.Defaults.Container; // may be null; we will append to the body if so.
  546. // get source and target as jQuery objects
  547. this.source = _getElementObject(params.source);
  548. this.target = _getElementObject(params.target);
  549. this.sourceId = _getAttribute(this.source, "id");
  550. this.targetId = _getAttribute(this.target, "id");
  551. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  552. this.scope = params.scope; // scope may have been passed in to the connect call.
  553. // if it wasn't, we will pull it from the source endpoint,
  554. // after having initialised the endpoints.
  555. // init endpoints
  556. this.endpoints = [];
  557. this.endpointStyles = [];
  558. var prepareEndpoint = function(existing, index, params, element) {
  559. if (existing) {
  560. self.endpoints[index] = existing;
  561. existing.addConnection(self);
  562. }
  563. else {
  564. if(!params.endpoints) params.endpoints = [null,null];
  565. var ep = params.endpoints[index] || params.endpoint || _currentInstance.Defaults.Endpoints[index] || jsPlumb.Defaults.Endpoints[index] || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || new jsPlumb.Endpoints.Dot();
  566. if (!params.endpointStyles) params.endpointStyles = [null,null];
  567. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  568. var a = params.anchors ? params.anchors[index] : _currentInstance.Defaults.Anchors[index] || jsPlumb.Defaults.Anchors[index] || _currentInstance.Defaults.Anchor || jsPlumb.Defaults.Anchor || jsPlumb.Anchors.BottomCenter;
  569. var e = new Endpoint({style:es, endpoint:ep, connections:[self], anchor:a, source:element, container:self.container });
  570. self.endpoints[index] = e;
  571. return e;
  572. }
  573. };
  574. var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source);
  575. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  576. var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target);
  577. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  578. // if scope not set, set it to be the scope for the source endpoint.
  579. if (!this.scope) this.scope = this.endpoints[0].scope;
  580. this.connector = this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _currentInstance.Defaults.Connector || jsPlumb.Defaults.Connector || new jsPlumb.Connectors.Bezier();
  581. this.paintStyle = this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _currentInstance.Defaults.PaintStyle || jsPlumb.Defaults.PaintStyle;
  582. _updateOffset(this.sourceId);
  583. _updateOffset(this.targetId);
  584. // paint the endpoints
  585. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  586. var anchorLoc = this.endpoints[0].anchor.compute([myOffset.left, myOffset.top], myWH, this.endpoints[0]);
  587. this.endpoints[0].paint(anchorLoc);
  588. myOffset = offsets[this.targetId]; myWH = sizes[this.targetId];
  589. anchorLoc = this.endpoints[1].anchor.compute([myOffset.left, myOffset.top], myWH, this.endpoints[1]);
  590. this.endpoints[1].paint(anchorLoc);
  591. // *************** create canvas on which the connection will be drawn ************
  592. var canvas = _newCanvas(jsPlumb.connectorClass, self.container);
  593. this.canvas = canvas;
  594. /**
  595. * paints the connection.
  596. * @param elId Id of the element that is in motion
  597. * @param ui current library's event system ui object (present if we came from a drag to get here)
  598. * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
  599. */
  600. this.paint = function(elId, ui, recalc, timestamp) {
  601. if (log) log.debug("Painting Connection; element in motion is " + elId + "; ui is [" + ui + "]; recalc is [" + recalc + "]");
  602. var fai = self.floatingAnchorIndex;
  603. // if the moving object is not the source we must transpose the two references.
  604. var swap = !(elId == this.sourceId);
  605. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  606. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  607. var el = swap ? this.target : this.source;
  608. if (this.canvas.getContext) {
  609. //if (recalc) {
  610. _updateOffset(elId, ui, recalc);
  611. _updateOffset(tId); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  612. //}
  613. var myOffset = offsets[elId];
  614. var otherOffset = offsets[tId];
  615. var myWH = sizes[elId];
  616. var otherWH = sizes[tId];
  617. var ctx = canvas.getContext('2d');
  618. //TODO: why are these calculated again? they were calculated in the _draw function.
  619. var sAnchorP = this.endpoints[sIdx].anchor.compute([myOffset.left, myOffset.top], myWH, this.endpoints[sIdx]);
  620. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  621. var tAnchorP = this.endpoints[tIdx].anchor.compute([otherOffset.left, otherOffset.top], otherWH, this.endpoints[tIdx]);
  622. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  623. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, this.paintStyle.lineWidth);
  624. jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
  625. jsPlumb.extend(ctx, this.paintStyle);
  626. if (this.paintStyle.gradient && !ie) {
  627. var g = swap ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  628. for (var i = 0; i < this.paintStyle.gradient.stops.length; i++)
  629. g.addColorStop(this.paintStyle.gradient.stops[i][0],this.paintStyle.gradient.stops[i][1]);
  630. ctx.strokeStyle = g;
  631. }
  632. this.connector.paint(dim, ctx);
  633. }
  634. };
  635. //TODO: should this take a timestamp? probably. it reduces the amount of time
  636. // spent figuring out anchor locations.
  637. this.repaint = function() {
  638. this.paint(this.sourceId, null, true);
  639. };
  640. _initDraggableIfNecessary(self.source, params.draggable, params.dragOptions);
  641. _initDraggableIfNecessary(self.target, params.draggable, params.dragOptions);
  642. // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
  643. if (this.source.resize) {
  644. this.source.resize(function(e) {
  645. jsPlumb.repaint(self.sourceId);
  646. });
  647. }
  648. };
  649. /*
  650. Class: Endpoint
  651. Models an endpoint. Can have one to N connections emanating from it (although how to handle that in the UI is
  652. a very good question). also has a Canvas and paint style.
  653. */
  654. /*
  655. Function: Endpoint
  656. This is the Endpoint class constructor.
  657. Parameters:
  658. anchor - anchor for the endpoint, of type jsPlumb.Anchor. may be null.
  659. endpoint - endpoint object, of type jsPlumb.Endpoint. may be null.
  660. style - endpoint style, a js object. may be null.
  661. source - element the endpoint is attached to, of type jquery object. Required.
  662. canvas - canvas element to use. may be, and most often is, null.
  663. connections - optional list of connections to configure the endpoint with.
  664. isSource - boolean. indicates the endpoint can act as a source of new connections. optional.
  665. dragOptions - if isSource is set to true, you can supply arguments for the jquery draggable method. optional.
  666. connectionStyle - if isSource is set to true, this is the paint style for connections from this endpoint. optional.
  667. connector - optional connector type to use.
  668. isTarget - boolean. indicates the endpoint can act as a target of new connections. optional.
  669. dropOptions - if isTarget is set to true, you can supply arguments for the jquery droppable method. optional.
  670. reattach - optional boolean that determines whether or not the connections reattach after they
  671. have been dragged off an endpoint and left floating. defaults to false: connections
  672. dropped in this way will just be deleted.
  673. */
  674. var Endpoint = function(params) {
  675. params = params || {};
  676. // make a copy. then we can use the wrapper function.
  677. jsPlumb.extend({}, params);
  678. var self = this;
  679. var id = new String('_jsplumb_e_' + (new Date()).getTime());
  680. this.getId = function() { return id; };
  681. self.anchor = params.anchor || jsPlumb.Anchors.TopCenter;
  682. var _endpoint = params.endpoint || new jsPlumb.Endpoints.Dot();
  683. var _style = params.style || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  684. this.connectorStyle = params.connectorStyle;
  685. this.connector = params.connector;
  686. var _element = params.source;
  687. this.container = params.container || jsPlumb.Defaults.Container;
  688. var _elementId = _getAttribute(_element, "id");
  689. var _maxConnections = params.maxConnections || 1; // maximum number of connections this endpoint can be the source of.
  690. this.canvas = params.canvas || _newCanvas(jsPlumb.endpointClass, this.container);
  691. this.connections = params.connections || [];
  692. this.scope = params.scope || DEFAULT_SCOPE;
  693. var _reattach = params.reattach || false;
  694. var floatingEndpoint = null;
  695. var inPlaceCopy = null;
  696. this.addConnection = function(connection) {
  697. self.connections.push(connection);
  698. };
  699. this.removeConnection = function(connection) {
  700. var idx = _findIndex(self.connections, connection);
  701. if (idx >= 0)
  702. self.connections.splice(idx, 1);
  703. };
  704. this.makeInPlaceCopy = function() {
  705. var e = new Endpoint({anchor:self.anchor, source:_element, style:_style, endpoint:_endpoint});
  706. return e;
  707. };
  708. /**
  709. * returns whether or not this endpoint is connected to the given endpoint.
  710. * @param endpoint Endpoint to test.
  711. * @since 1.1.1
  712. *
  713. * todo: needs testing. will this work if the endpoint passed in is the source?
  714. */
  715. this.isConnectedTo = function(endpoint) {
  716. var found = false;
  717. if (endpoint) {
  718. for (var i = 0; i < self.connections.length; i++) {
  719. if (self.connections[i].endpoints[1] == endpoint) {
  720. found = true;
  721. break;
  722. }
  723. }
  724. }
  725. return found;
  726. };
  727. this.isFloating = function() { return floatingEndpoint != null; };
  728. /**
  729. * first pass at default ConnectorSelector: returns the first connection, if we have any.
  730. * modified a little, 5/10/2010: now it only returns a connector if we have not got equal to or more than _maxConnector connectors
  731. * 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
  732. * one. what if this could return a list? that implies everything should work with a list - dragging etc. could be nasty. could also
  733. * be cool.
  734. */
  735. var connectorSelector = function() {
  736. return self.connections.length == 0 || self.connections.length < _maxConnections ? null : self.connections[0];
  737. };
  738. this.isFull = function() { return _maxConnections < 1 ? false : (self.connections.length >= _maxConnections); };
  739. /**
  740. * a deep equals check. everything must match, including the anchor, styles, everything.
  741. * TODO: finish Endpoint.equals
  742. */
  743. this.equals = function(endpoint) {
  744. return this.anchor.equals(endpoint.anchor) &&
  745. true;
  746. };
  747. /**
  748. * paints the Endpoint, recalculating offset and anchor positions if necessary.
  749. */
  750. this.paint = function(anchorPoint, connectorPaintStyle, canvas) {
  751. if (log) log.debug("Painting Endpoint with elementId [" + _elementId + "]; anchorPoint is [" + anchorPoint + "]");
  752. if (anchorPoint == null) {
  753. // do we always want to force a repaint here? i dont think so!
  754. var xy = offsets[_elementId];
  755. var wh = sizes[_elementId];
  756. if (xy == null || wh == null) {
  757. _updateOffset(_elementId);
  758. xy = offsets[_elementId];
  759. wh = sizes[_elementId];
  760. }
  761. anchorPoint = self.anchor.compute([xy.left, xy.top], wh, self);
  762. }
  763. _endpoint.paint(anchorPoint, self.anchor.getOrientation(), canvas || self.canvas, _style, connectorPaintStyle || _style);
  764. };
  765. // is this a connection source? we make it draggable and have the drag listener
  766. // maintain a connection with a floating endpoint.
  767. if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  768. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  769. // 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
  770. // to select one connection from the list, or drag them all. if we had a pluggable 'ConnectorSelector' interface we could probably
  771. // 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
  772. // information the interface needs from jsPlumb at execution time. if, however, we leave out the connector selection, and drag them all,
  773. // that wouldn't be too hard to organise. perhaps that behaviour would be on a switch for the endpoint, or perhaps the ConnectorSelector
  774. // interface returns a List, with the default implementation just returning everything. i think i like that.
  775. //
  776. // 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.
  777. // the major difference between that case and the case of a new endpoint is actually quite small - it's a question of where the
  778. // Connection comes from. for a new one, we create a new one. obviously. otherwise we just get the jpc from the Endpoint
  779. // (remember we're only assuming one connection right now). so all of the UI stuff we do to create the floating endpoint etc
  780. // 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
  781. // 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.
  782. var start = function() {
  783. inPlaceCopy = self.makeInPlaceCopy();
  784. inPlaceCopy.paint();
  785. n = document.createElement("div");
  786. var nE = _getElementObject(n);
  787. _appendElement(n); //
  788. // create and assign an id, and initialize the offset.
  789. //TODO can't this be replaced with a _getId call?
  790. var id = "" + new String(new Date().getTime());
  791. _setAttribute(nE, "id", id);
  792. _updateOffset(id);
  793. // store the id of the dragging div and the source element. the drop function
  794. // will pick these up.
  795. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  796. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  797. // create a floating anchor
  798. var floatingAnchor = new FloatingAnchor({reference:self.anchor, referenceCanvas:self.canvas});
  799. floatingEndpoint = new Endpoint({ style:{fillStyle:'rgba(0,0,0,0)'}, endpoint:_endpoint, anchor:floatingAnchor, source:nE });
  800. jpc = connectorSelector();
  801. if (jpc == null) {
  802. // create a connection. one end is this endpoint, the other is a floating endpoint.
  803. jpc = new Connection({
  804. sourceEndpoint:self,
  805. targetEndpoint:floatingEndpoint,
  806. source:_getElementObject(_element),
  807. target:_getElementObject(n),
  808. anchors:[self.anchor, floatingAnchor],
  809. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  810. connector: params.connector
  811. });
  812. } else {
  813. existingJpc = true;
  814. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1;
  815. jpc.floatingAnchorIndex = anchorIdx;
  816. // probably we should remove the connection? and add it back if the user
  817. // does not drop it somewhere proper.
  818. self.removeConnection(jpc);
  819. if (anchorIdx == 0){
  820. existingJpcParams = [jpc.source, jpc.sourceId];
  821. jpc.source = _getElementObject(n);
  822. jpc.sourceId = id;
  823. }else {
  824. existingJpcParams = [jpc.target, jpc.targetId];
  825. jpc.target = _getElementObject(n);
  826. jpc.targetId = id;
  827. }
  828. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  829. jpc.endpoints[anchorIdx] = floatingEndpoint;
  830. }
  831. // register it.
  832. floatingConnections[id] = jpc;
  833. // todo unregister on stop
  834. floatingEndpoint.addConnection(jpc);
  835. // only register for the target endpoint; we will not be dragging the source at any time
  836. // before this connection is either discarded or made into a permanent connection.
  837. _addToList(endpointsByElement, id, floatingEndpoint);
  838. };
  839. var dragOptions = params.dragOptions || { };
  840. var defaultOpts = jsPlumb.extend({}, jsPlumb.CurrentLibrary.defaultDragOptions);
  841. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  842. dragOptions.scope = dragOptions.scope || self.scope;
  843. var startEvent = jsPlumb.CurrentLibrary.dragEvents['start'];
  844. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  845. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  846. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  847. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() {
  848. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  849. _draw(_getElementObject(n), _ui);
  850. });
  851. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  852. function() {
  853. _removeFromList(endpointsByElement, id, floatingEndpoint);
  854. _removeElements([n, floatingEndpoint.canvas]); // TODO: clean up the connection canvas (if the user aborted)
  855. _removeElement(inPlaceCopy.canvas, _element);
  856. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  857. if (jpc.endpoints[idx] == floatingEndpoint) {
  858. // if the connection was an existing one:
  859. if (existingJpc && jpc.suspendedEndpoint) {
  860. if (_reattach) {
  861. jpc.floatingAnchorIndex = null;
  862. if (idx == 0) {
  863. jpc.source = existingJpcParams[0];
  864. jpc.sourceId = existingJpcParams[1];
  865. } else {
  866. jpc.target = existingJpcParams[0];
  867. jpc.targetId = existingJpcParams[1];
  868. }
  869. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  870. jpc.suspendedEndpoint.addConnection(jpc);
  871. jsPlumb.repaint(existingJpcParams[1]);
  872. }
  873. else {
  874. jpc.endpoints[0].removeConnection(jpc);
  875. jpc.endpoints[1].removeConnection(jpc);
  876. _removeElement(jpc.canvas);
  877. _removeFromList(connectionsByScope, jpc.scope, jpc);
  878. }
  879. } else {
  880. _removeElement(jpc.canvas);
  881. self.removeConnection(jpc);
  882. }
  883. }
  884. jpc = null;
  885. delete floatingEndpoint;
  886. delete inPlaceCopy;
  887. self.paint();
  888. }
  889. );
  890. var i = _getElementObject(self.canvas);
  891. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
  892. };
  893. // connector target
  894. if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  895. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  896. dropOptions = jsPlumb.extend({}, dropOptions);
  897. dropOptions.scope = dropOptions.scope || self.scope;
  898. var originalAnchor = null;
  899. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
  900. var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
  901. var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
  902. dropOptions[dropEvent]= _wrap(dropOptions[dropEvent], function() {
  903. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  904. var id = _getAttribute(_getElementObject(draggable), "dragId");
  905. var elId = _getAttribute(_getElementObject(draggable),"elId");
  906. var jpc = floatingConnections[id];
  907. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  908. if (idx == 0) {
  909. jpc.source = _element;
  910. jpc.sourceId = _elementId;
  911. } else {
  912. jpc.target = _element;
  913. jpc.targetId = _elementId;
  914. }
  915. // remove this jpc from the current endpoint
  916. jpc.endpoints[idx].removeConnection(jpc);
  917. if (jpc.suspendedEndpoint)
  918. jpc.suspendedEndpoint.removeConnection(jpc);
  919. jpc.endpoints[idx] = self;
  920. self.addConnection(jpc);
  921. _addToList(connectionsByScope, jpc.scope, jpc);
  922. _initDraggableIfNecessary(_element, params.draggable, {});
  923. jsPlumb.repaint(elId);
  924. delete floatingConnections[id];
  925. });
  926. dropOptions[overEvent]= _wrap(dropOptions[overEvent], function() {
  927. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  928. var id = _getAttribute(_getElementObject(draggable),"dragId");
  929. var jpc = floatingConnections[id];
  930. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  931. jpc.endpoints[idx].anchor.over(self.anchor);
  932. });
  933. dropOptions[outEvent] = _wrap(dropOptions[outEvent], function() {
  934. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  935. var id = _getAttribute(_getElementObject(draggable),"dragId");
  936. var jpc = floatingConnections[id];
  937. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  938. jpc.endpoints[idx].anchor.out();
  939. });
  940. jsPlumb.CurrentLibrary.initDroppable(_getElementObject(self.canvas), dropOptions);
  941. }
  942. return self;
  943. };
  944. /*
  945. Property: Defaults
  946. These are the default settings for jsPlumb, that is what will be used if you do not supply specific pieces of information
  947. 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
  948. somewhere after the jsPlumb include, but before you make any calls to jsPlumb, for instance in this example we set the PaintStyle to be
  949. a blue line of 27 pixels:
  950. > jsPlumb.Defaults.PaintStyle = { lineWidth:27, strokeStyle:'blue' }
  951. */
  952. this.Defaults = {
  953. Anchor : null,
  954. Anchors : [ null, null ],
  955. Connector : null,
  956. Container : null,
  957. DragOptions: { },
  958. DropOptions: { },
  959. Endpoint : null,
  960. Endpoints : [ null, null ],
  961. EndpointStyle : { fillStyle : null },
  962. EndpointStyles : [ null, null ],
  963. MaxConnections : null,
  964. PaintStyle : { lineWidth : 10, strokeStyle : 'red' },
  965. Scope : "_jsPlumb_DefaultScope"
  966. };
  967. /*
  968. Property: connectorClass
  969. 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.
  970. */
  971. this.connectorClass = '_jsPlumb_connector';
  972. /*
  973. Property: endpointClass
  974. 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.
  975. */
  976. this.endpointClass = '_jsPlumb_endpoint';
  977. /*
  978. Property: Anchors
  979. Default jsPlumb Anchors. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  980. to form <library>.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:
  981. > jsPlumb.Anchors.MyAnchor = { ....anchor code here. see the documentation. }
  982. */
  983. this.Anchors = {};
  984. /*
  985. Property: Connectors
  986. Default jsPlumb Connectors. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  987. to form <library>.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:
  988. > jsPlumb.Connectors.MyConnector = { ....connector code here. see the documentation. }
  989. */
  990. this.Connectors = {};
  991. /*
  992. Property: Endpoints
  993. Default jsPlumb Endpoints. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  994. to form <library>.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:
  995. > jsPlumb.Endpoints.MyEndpoint = { ....endpoint code here. see the documentation. }
  996. */
  997. this.Endpoints = {};
  998. /*
  999. Function: addEndpoint
  1000. Adds an Endpoint to a given element.
  1001. Parameters:
  1002. target - Element to add the endpoint to. either an element id, or a selector representing some element.
  1003. params - Object containing Endpoint options (more info required)
  1004. Returns:
  1005. The newly created Endpoint.
  1006. See Also:
  1007. <addEndpoints>
  1008. */
  1009. this.addEndpoint = function(target, params) {
  1010. params = jsPlumb.extend({}, params);
  1011. var el = _getElementObject(target);
  1012. var id = _getAttribute(el,"id");
  1013. params.source = el;
  1014. _updateOffset(id);
  1015. var e = new Endpoint(params);
  1016. _addToList(endpointsByElement, id, e);
  1017. var myOffset = offsets[id];
  1018. var myWH = sizes[id];
  1019. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH, e);
  1020. e.paint(anchorLoc);
  1021. return e;
  1022. };
  1023. /*
  1024. Function: addEndpoint
  1025. Adds a list of Endpoints to a given element.
  1026. Parameters:
  1027. target - element to add the endpoint to. either an element id, or a selector representing some element.
  1028. endpoints - List of objects containing Endpoint options. one Endpoint is created for each entry in this list.
  1029. Returns:
  1030. List of newly created Endpoints, one for each entry in the 'endpoints' argument.
  1031. See Also:
  1032. <addEndpoint>
  1033. */
  1034. this.addEndpoints = function(target, endpoints) {
  1035. var results = [];
  1036. for (var i = 0; i < endpoints.length; i++) {
  1037. results.push(jsPlumb.addEndpoint(target, endpoints[i]));
  1038. }
  1039. return results;
  1040. };
  1041. /*
  1042. Function: animate
  1043. Wrapper around supporting library's animate function; injects a call to jsPlumb in the 'step' function (creating it if necessary).
  1044. This only supports the two-arg version of the animate call in jQuery - the one that takes an 'options' object as the second arg.
  1045. MooTools has only one method - a two arg one. Which is handy.
  1046. Parameters:
  1047. el - Element to animate. Either an id, or a selector representing the element.
  1048. properties - The 'properties' argument you want passed to the standard jQuery animate call.
  1049. options - The 'options' argument you want passed to the standard jQuery animate call.
  1050. Returns:
  1051. void
  1052. */
  1053. this.animate = function(el, properties, options) {
  1054. var ele = _getElementObject(el);
  1055. var id = _getAttribute(el,"id");
  1056. //TODO this is not agnostic yet.
  1057. options = options || {};
  1058. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  1059. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  1060. options[stepFunction] = _wrap(options[stepFunction], function()
  1061. {
  1062. _currentInstance.repaint(id);
  1063. });
  1064. // you know, probably onComplete should repaint too. that will help keep up
  1065. // with fast animations.
  1066. options[completeFunction] = _wrap(options[completeFunction], function()
  1067. {
  1068. _currentInstance.repaint(id);
  1069. });
  1070. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  1071. };
  1072. /**
  1073. * clears the cache used to lookup elements by their id. if you remove any elements
  1074. * from the DOM you should call this to ensure that if you add them back in jsPlumb does not
  1075. * have a stale handle.
  1076. */
  1077. this.clearCache = function() {
  1078. delete cached;
  1079. cached = {};
  1080. };
  1081. /*
  1082. Function: connect
  1083. Establishes a connection between two elements.
  1084. Parameters:
  1085. params - Object containing setup for the connection. see documentation.
  1086. Returns:
  1087. The newly created Connection.
  1088. */
  1089. this.connect = function(params) {
  1090. if (params.sourceEndpoint && params.sourceEndpoint.isFull()) {
  1091. _log("could not add connection; source endpoint is full");
  1092. return;
  1093. }
  1094. if (params.targetEndpoint && params.targetEndpoint.isFull()) {
  1095. _log("could not add connection; target endpoint is full");
  1096. return;
  1097. }
  1098. var jpc = new Connection(params);
  1099. // add to list of connections (by scope).
  1100. _addToList(connectionsByScope, jpc.scope, jpc);
  1101. // force a paint
  1102. _draw(jpc.source);
  1103. return jpc;
  1104. };
  1105. /**
  1106. * not implemented yet. params object will have sourceEndpoint and targetEndpoint members; these will be Endpoints.
  1107. connectEndpoints : function(params) {
  1108. var jpc = Connection(params);
  1109. },*/
  1110. /*
  1111. Function: detach
  1112. Removes a connection.
  1113. Parameters:
  1114. sourceId - Id of the first element in the connection. A String.
  1115. targetId - iI of the second element in the connection. A String.
  1116. Returns:
  1117. true if successful, false if not.
  1118. */
  1119. this.detach = function(sourceId, targetId) {
  1120. var f = function(jpc) {
  1121. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  1122. _removeElement(jpc.canvas, jpc.container);
  1123. jpc.endpoints[0].removeConnection(jpc);
  1124. jpc.endpoints[1].removeConnection(jpc);
  1125. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1126. return true;
  1127. }
  1128. };
  1129. // todo: how to cleanup the actual storage? a third arg to _operation?
  1130. _operation(sourceId, f);
  1131. };
  1132. /*
  1133. Function: detachAll
  1134. Removes all an element's connections.
  1135. Parameters:
  1136. el - either the id of the element, or a selector for the element.
  1137. Returns:
  1138. void
  1139. */
  1140. this.detachAll = function(el) {
  1141. var id = _getAttribute(el, "id");
  1142. var endpoints = endpointsByElement[id];
  1143. if (endpoints && endpoints.length) {
  1144. for (var i = 0; i < endpoints.length; i++) {
  1145. var c = endpoints[i].connections.length;
  1146. if (c > 0) {
  1147. for (var j = 0; j < c; j++) {
  1148. var jpc = endpoints[i].connections[0];
  1149. _removeElement(jpc.canvas, jpc.container);
  1150. jpc.endpoints[0].removeConnection(jpc);
  1151. jpc.endpoints[1].removeConnection(jpc);
  1152. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1153. }
  1154. }
  1155. }
  1156. }
  1157. };
  1158. /*
  1159. Function: detachEverything
  1160. Remove all Connections from all elements, but leaves Endpoints in place.
  1161. Returns:
  1162. void
  1163. See Also:
  1164. <removeEveryEndpoint>
  1165. */
  1166. this.detachEverything = function() {
  1167. for(var id in endpointsByElement) {
  1168. var endpoints = endpointsByElement[id];
  1169. if (endpoints && endpoints.length) {
  1170. for (var i = 0; i < endpoints.length; i++) {
  1171. var c = endpoints[i].connections.length;
  1172. if (c > 0) {
  1173. for (var j = 0; j < c; j++) {
  1174. var jpc = endpoints[i].connections[0];
  1175. _removeElement(jpc.canvas, jpc.container);
  1176. jpc.endpoints[0].removeConnection(jpc);
  1177. jpc.endpoints[1].removeConnection(jpc);
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. delete connectionsByScope;
  1184. connectionsByScope = {};
  1185. };
  1186. /*
  1187. Function: draggable
  1188. initialises the draggability of some element or elements.
  1189. Parameters:
  1190. el - either an element id, a list of element ids, or a selector.
  1191. options - options to pass through to the underlying library
  1192. Returns:
  1193. void
  1194. */
  1195. this.draggable = function(el, options) {
  1196. if (typeof el == 'object' && el.length) {
  1197. for (var i = 0; i < el.length; i++)
  1198. {
  1199. var ele = _getElementObject(el[i]);
  1200. if (ele) _initDraggableIfNecessary(ele, true, options);
  1201. }
  1202. }
  1203. else {
  1204. var ele = _getElementObject(el);
  1205. if (ele)
  1206. _initDraggableIfNecessary(ele, true, options);
  1207. }
  1208. };
  1209. /*
  1210. Function: extend
  1211. Wraps the underlying library's extend functionality.
  1212. Parameters:
  1213. o1 - object to extend
  1214. o2 - object to extend o1 with
  1215. Returns:
  1216. o1, extended with all properties from o2.
  1217. */
  1218. this.extend = function(o1, o2) {
  1219. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1220. };
  1221. /*
  1222. Function: getConnections
  1223. Gets all or a subset of connections currently managed by this jsPlumb instance.
  1224. Parameters:
  1225. options - a JS object that holds options defining what sort of connections you're looking for. Valid values are:
  1226. scope this may be a String or a list of Strings. jsPlumb will only return Connections whose scope matches what this option
  1227. defines. If you omit it, you will be given Connections of every scope.
  1228. source may be a string or a list of strings; constraints results to have only Connections whose source is this object.
  1229. target may be a string or a list of strings; constraints results to have only Connections whose target is this object.
  1230. The return value is a dictionary in this format:
  1231. {
  1232. 'scope1': [
  1233. {sourceId:'window1', targetId:'window2'},
  1234. {sourceId:'window3', targetId:'window4'},
  1235. {sourceId:'window1', targetId:'window3'}
  1236. ],
  1237. 'scope2': [
  1238. {sourceId:'window1', targetId:'window3'}
  1239. ]
  1240. }
  1241. */
  1242. this.getConnections = function(options) {
  1243. var r = {};
  1244. options = options || {};
  1245. var prepareList = function(input) {
  1246. var r = [];
  1247. if (input) {
  1248. if (typeof input == 'string') r.push(input);
  1249. else r = input;
  1250. }
  1251. return r;
  1252. };
  1253. var scopes = prepareList(options.scope);
  1254. var sources = prepareList(options.source);
  1255. var targets = prepareList(options.target);
  1256. var filter = function(list, value) {
  1257. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1258. };
  1259. for (var i in connectionsByScope) {
  1260. if (filter(scopes, i)) {
  1261. r[i] = [];
  1262. for (var j = 0; j < connectionsByScope[i].length; j++) {
  1263. var c = connectionsByScope[i][j];
  1264. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1265. r[i].push({sourceId:c.sourceId, targetId:c.targetId});
  1266. }
  1267. }
  1268. }
  1269. return r;
  1270. };
  1271. /*
  1272. Function: getDefaultScope
  1273. Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a scope to an endpoint
  1274. or connection allows you to support different types of connections in the same UI. but if you're only interested in one type of connection,
  1275. you don't need to supply a scope. this method will probably be used by very few people; it's good for testing though.
  1276. */
  1277. this.getDefaultScope = function() {
  1278. return DEFAULT_SCOPE;
  1279. };
  1280. /*
  1281. Function: hide
  1282. Sets an element's connections to be hidden.
  1283. Parameters:
  1284. el - either the id of the element, or a selector for the element.
  1285. Returns:
  1286. void
  1287. */
  1288. this.hide = function(el) {
  1289. _setVisible(el, "none");
  1290. };
  1291. /*
  1292. Function: makeAnchor
  1293. Creates an anchor with the given params.
  1294. Parameters:
  1295. x - the x location of the anchor as a fraction of the total width.
  1296. y - the y location of the anchor as a fraction of the total height.
  1297. xOrientation - value indicating the general direction a connection from the anchor should go in, in the x direction.
  1298. yOrientation - value indicating the general direction a connection from the anchor should go in, in the y direction.
  1299. 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.
  1300. 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.
  1301. Returns:
  1302. The newly created Anchor.
  1303. */
  1304. this.makeAnchor = function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1305. // backwards compatibility here. we used to require an object passed in but that makes the call very verbose. easier to use
  1306. // 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.
  1307. var params = {};
  1308. if (arguments.length == 1) jsPlumb.extend(params, x);
  1309. else {
  1310. params = {x:x, y:y};
  1311. if (arguments.length >= 4) {
  1312. params.orientation = [arguments[2], arguments[3]];
  1313. }
  1314. if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
  1315. }
  1316. var a = new Anchor(params);
  1317. a.clone = function() { return new Anchor(params); };
  1318. return a;
  1319. };
  1320. /*
  1321. Function: repaint
  1322. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1323. Parameters:
  1324. el - either the id of the element or a selector representing the element.
  1325. Returns:
  1326. void
  1327. See Also:
  1328. <repaintEverything>
  1329. */
  1330. this.repaint = function(el) {
  1331. var _processElement = function(el) {
  1332. var ele = _getElementObject(el);
  1333. _draw(ele);
  1334. };
  1335. // TODO: support a jQuery result object too!
  1336. // support both lists...
  1337. if (typeof el =='object') {
  1338. for (var i = 0; i < el.length; i++)
  1339. _processElement(el[i]);
  1340. } // ...and single strings.
  1341. else _processElement(el);
  1342. };
  1343. /*
  1344. Function: repaintEverything
  1345. Repaints all connections.
  1346. Returns:
  1347. void
  1348. See Also:
  1349. <repaint>
  1350. */
  1351. this.repaintEverything = function() {
  1352. for (var elId in endpointsByElement) {
  1353. _draw(_getElementObject(elId));
  1354. }
  1355. };
  1356. /*
  1357. Function: removeAllEndpoints
  1358. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1359. Parameters:
  1360. el - either an element id, or a selector for an element.
  1361. Returns:
  1362. void
  1363. See Also:
  1364. <removeEndpoint>
  1365. */
  1366. this.removeAllEndpoints = function(el) {
  1367. var elId = _getAttribute(el, "id");
  1368. // first remove all Connections.
  1369. jsPlumb.detachAll(elId);
  1370. var ebe = endpointsByElement[elId];
  1371. for (var i in ebe) {
  1372. _removeElement(ebe[i].canvas);
  1373. }
  1374. endpointsByElement[elId] = [];
  1375. };
  1376. /*
  1377. Function: removeEveryEndpoint
  1378. Removes every Endpoint in this instance of jsPlumb.
  1379. Returns:
  1380. void
  1381. See Also:
  1382. <removeAllEndpoints> <removeEndpoint>
  1383. */
  1384. this.removeEveryEndpoint = function() {
  1385. for(var id in endpointsByElement) {
  1386. var endpoints = endpointsByElement[id];
  1387. if (endpoints && endpoints.length) {
  1388. for (var i = 0; i < endpoints.length; i++) {
  1389. _removeElement(endpoints[i].canvas, endpoints[i].container);
  1390. }
  1391. }
  1392. }
  1393. delete endpointsByElement;
  1394. endpointsByElement = {};
  1395. };
  1396. /*
  1397. Function: removeEndpoint
  1398. Removes the given Endpoint from the given element.
  1399. Parameters:
  1400. el - either an element id, or a selector for an element.
  1401. endpoint - Endpoint to remove. this is an Endpoint object, such as would have been returned from a call to addEndpoint.
  1402. Returns:
  1403. void
  1404. See Also:
  1405. <removeAllEndpoints> <removeEveryEndpoint>
  1406. */
  1407. this.removeEndpoint = function(el, endpoint) {
  1408. var elId = _getAttribute(el, "id");
  1409. var ebe = endpointsByElement[elId];
  1410. if (ebe) {
  1411. if(_removeFromList(endpointsByElement, elId, endpoint))
  1412. _removeElement(endpoint.canvas);
  1413. }
  1414. };
  1415. /*
  1416. Function:reset
  1417. removes all endpoints and connections and clears the element cache.
  1418. */
  1419. this.reset = function() {
  1420. this.detachEverything();
  1421. this.removeEveryEndpoint();
  1422. this.clearCache();
  1423. };
  1424. /*
  1425. Function: setAutomaticRepaint
  1426. Sets/unsets automatic repaint on window resize.
  1427. Parameters:
  1428. value - whether or not to automatically repaint when the window is resized.
  1429. Returns:
  1430. void
  1431. */
  1432. this.setAutomaticRepaint = function(value) {
  1433. automaticRepaint = value;
  1434. };
  1435. /*
  1436. Function: setDefaultNewCanvasSize
  1437. Sets the default size jsPlumb will use for a new canvas (we create a square canvas so one value is all that is required).
  1438. 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
  1439. it at initialisation time. The default value of this is 1200 pixels, which is quite large, but if for some reason you're
  1440. drawing connectors that are bigger, you should adjust this value appropriately.
  1441. Parameters:
  1442. size - The default size to use. jsPlumb will use a square canvas so you need only supply one value.
  1443. Returns:
  1444. void
  1445. */
  1446. this.setDefaultNewCanvasSize = function(size) {
  1447. DEFAULT_NEW_CANVAS_SIZE = size;
  1448. };
  1449. /*
  1450. Function: setDefaultScope
  1451. Sets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a scope to an endpoint
  1452. or connection allows you to support different types of connections in the same UI. but if you're only interested in one type of connection,
  1453. you don't need to supply a scope. this method will probably be used by very few people; it just instructs jsPlumb to use a different key
  1454. for the default scope.
  1455. */
  1456. this.setDefaultScope = function(scope) {
  1457. DEFAULT_SCOPE = scope;
  1458. };
  1459. /*
  1460. Function: setDraggable
  1461. Sets whether or not a given element is draggable, regardless of what any plumb command may request.
  1462. Parameters:
  1463. el - either the id for the element, or a selector representing the element.
  1464. Returns:
  1465. void
  1466. */
  1467. this.setDraggable = _setDraggable;
  1468. /*
  1469. Function: setDraggableByDefault
  1470. Sets whether or not elements are draggable by default. Default for this is true.
  1471. Parameters:
  1472. draggable - value to set
  1473. Returns:
  1474. void
  1475. */
  1476. this.setDraggableByDefault = function(draggable) {
  1477. _draggableByDefault = draggable;
  1478. };
  1479. this.setDebugLog = function(debugLog) {
  1480. log = debugLog;
  1481. };
  1482. /*
  1483. Function: setRepaintFunction
  1484. Sets the function to fire when the window size has changed and a repaint was fired.
  1485. Parameters:
  1486. f - Function to execute.
  1487. Returns:
  1488. void
  1489. */
  1490. this.setRepaintFunction = function(f) {
  1491. repaintFunction = f;
  1492. };
  1493. /*
  1494. Function: show
  1495. Sets an element's connections to be visible.
  1496. Parameters:
  1497. el - either the id of the element, or a selector for the element.
  1498. Returns:
  1499. void
  1500. */
  1501. this.show = function(el) {
  1502. _setVisible(el, "block");
  1503. };
  1504. /*
  1505. Function: sizeCanvas
  1506. Helper to size a canvas. You would typically use this when writing your own Connector or Endpoint implementation.
  1507. Parameters:
  1508. x - [int] x position for the Canvas origin
  1509. y - [int] y position for the Canvas origin
  1510. w - [int] width of the canvas
  1511. h - [int] height of the canvas
  1512. Returns:
  1513. void
  1514. */
  1515. this.sizeCanvas = function(canvas, x, y, w, h) {
  1516. if (canvas) {
  1517. canvas.style.height = h + "px"; canvas.height = h;
  1518. canvas.style.width = w + "px"; canvas.width = w;
  1519. canvas.style.left = x + "px"; canvas.style.top = y + "px";
  1520. // _currentInstance.CurrentLibrary.setPosition(canvas, x, y);
  1521. }
  1522. };
  1523. /**
  1524. * gets some test hooks. nothing writable.
  1525. */
  1526. this.getTestHarness = function() {
  1527. return {
  1528. endpointCount : function(elId) {
  1529. var e = endpointsByElement[elId];
  1530. return e ? e.length : 0;
  1531. },
  1532. connectionCount : function(scope) {
  1533. scope = scope || DEFAULT_SCOPE;
  1534. var c = connectionsByScope[scope];
  1535. return c ? c.length : 0;
  1536. },
  1537. findIndex : _findIndex,
  1538. getId : _getId
  1539. };
  1540. };
  1541. /**
  1542. * Toggles visibility of an element's connections. kept for backwards compatibility
  1543. */
  1544. this.toggle = _toggleVisible;
  1545. /*
  1546. Function: toggleVisible
  1547. Toggles visibility of an element's connections.
  1548. Parameters:
  1549. el - either the element's id, or a selector representing the element.
  1550. Returns:
  1551. void, but should be updated to return the current state
  1552. */
  1553. //TODO: update this method to return the current state.
  1554. this.toggleVisible = _toggleVisible;
  1555. /*
  1556. Function: toggleDraggable
  1557. Toggles draggability (sic) of an element's connections.
  1558. Parameters:
  1559. el - either the element's id, or a selector representing the element.
  1560. Returns:
  1561. The current draggable state.
  1562. */
  1563. this.toggleDraggable = _toggleDraggable;
  1564. /*
  1565. Function: unload
  1566. Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element
  1567. Returns:
  1568. void
  1569. */
  1570. this.unload = function() {
  1571. delete endpointsByElement;
  1572. delete offsets;
  1573. delete sizes;
  1574. delete floatingConnections;
  1575. delete draggableStates;
  1576. };
  1577. /*
  1578. Function: wrap
  1579. Helper method to wrap an existing function with one of your own. This is used by the various
  1580. implementations to wrap event callbacks for drag/drop etc; it allows jsPlumb to be
  1581. transparent in its handling of these things. If a user supplies their own event callback,
  1582. for anything, it will always be called.
  1583. Parameters:
  1584. */
  1585. this.wrap = _wrap;
  1586. this.trace = _trace;
  1587. this.clearTrace = _clearTrace;
  1588. this.clearAllTraces = _clearAllTraces;
  1589. this.getTrace = _getTrace;
  1590. };
  1591. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  1592. jsPlumb.getInstance = function(_defaults) {
  1593. var j = new jsPlumbInstance();
  1594. if (_defaults)
  1595. jsPlumb.extend(j.Defaults, _defaults);
  1596. return j;
  1597. };
  1598. })();
  1599. /**
  1600. * jsPlumb-defaults-1.2-RC1
  1601. *
  1602. * This script contains the default Anchors, Endpoints and Connectors for jsPlumb. It should be used with jsPlumb 1.1.0 and above;
  1603. * prior to version 1.1.0 of jsPlumb the defaults were included inside the main script.
  1604. *
  1605. * Version 1.1.1 of this script adds the Triangle Endpoint, written by __________ and featured on this demo:
  1606. *
  1607. * http://www.mintdesign.ru/blog/javascript-jsplumb-making-graph
  1608. * http://www.mintdesign.ru/site/samples/jsplumb/jsPlumb-graph-sample.htm
  1609. *
  1610. * NOTE: for production usage you should use jsPlumb-all-1.1.1-min.js, which contains the main jsPlumb script and this script together,
  1611. * in a minified file.
  1612. */
  1613. (function() {
  1614. /**
  1615. * Places you can anchor a connection to. These are helpers for common locations; they all just return an instance
  1616. * of Anchor that has been configured appropriately.
  1617. *
  1618. * You can write your own one of these; you
  1619. * just need to provide a 'compute' method and an 'orientation'. so you'd say something like this:
  1620. *
  1621. * jsPlumb.Anchors.MY_ANCHOR = {
  1622. * compute : function(xy, wh, txy, twh) { return some mathematics on those variables; },
  1623. * getOrientation : function() { return [ox, oy]; }
  1624. * };
  1625. *
  1626. * compute takes the [x,y] position of the top left corner of the anchored element,
  1627. * and the element's [width,height] (all in pixels), as well as the location and dimension of the element it's plumbed to,
  1628. * and returns where the anchor should be located.
  1629. *
  1630. * the 'orientation' array (returned here as [ox,oy]) indicates the general direction a connection from the anchor
  1631. * should go in, if possible. it is an [x,y] matrix where a value of 0 means no preference,
  1632. * -1 means go in a negative direction for the given axis, and 1 means go in a positive
  1633. * direction. so consider a TopCenter anchor: the orientation matrix for it is [0,-1],
  1634. * meaning connections naturally want to go upwards on screen. in a Bezier implementation, for example,
  1635. * the curve would start out going in that direction, before bending towards the target anchor.
  1636. */
  1637. jsPlumb.Anchors.TopCenter = jsPlumb.makeAnchor(0.5, 0, 0,-1);
  1638. jsPlumb.Anchors.BottomCenter = jsPlumb.makeAnchor(0.5, 1, 0, 1);
  1639. jsPlumb.Anchors.LeftMiddle = jsPlumb.makeAnchor(0, 0.5, -1, 0);
  1640. jsPlumb.Anchors.RightMiddle = jsPlumb.makeAnchor(1, 0.5, 1, 0);
  1641. jsPlumb.Anchors.Center = jsPlumb.makeAnchor(0.5, 0.5, 0, 0);
  1642. jsPlumb.Anchors.TopRight = jsPlumb.makeAnchor(1, 0, 0,-1);
  1643. jsPlumb.Anchors.BottomRight = jsPlumb.makeAnchor(1, 1, 0, 1);
  1644. jsPlumb.Anchors.TopLeft = jsPlumb.makeAnchor(0, 0, 0, -1);
  1645. jsPlumb.Anchors.BottomLeft = jsPlumb.makeAnchor(0, 1, 0, 1);
  1646. /**
  1647. * The Straight connector draws a simple straight line between the two anchor points.
  1648. */
  1649. jsPlumb.Connectors.Straight = function() {
  1650. var self = this;
  1651. /**
  1652. * Computes the new size and position of the canvas.
  1653. * @param sourceAnchor Absolute position on screen of the source object's anchor.
  1654. * @param targetAnchor Absolute position on screen of the target object's anchor.
  1655. * @param positionMatrix Indicates the relative positions of the left,top of the
  1656. * two plumbed objects. so [0,0] indicates that the source is to the left of, and
  1657. * above, the target. [1,0] means the source is to the right and above. [0,1] means
  1658. * the source is to the left and below. [1,1] means the source is to the right
  1659. * and below. this is used to figure out which direction to draw the connector in.
  1660. * @returns an array of positioning information. the first two values are
  1661. * the [left, top] absolute position the canvas should be placed on screen. the
  1662. * next two values are the [width,height] the canvas should be. after that each
  1663. * Connector can put whatever it likes into the array:it will be passed back in
  1664. * to the paint call. This particular function stores the origin and destination of
  1665. * the line it is going to draw. a more involved implementation, like a Bezier curve,
  1666. * would store the control point info in this array too.
  1667. */
  1668. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth) {
  1669. var w = Math.abs(sourcePos[0] - targetPos[0]);
  1670. var h = Math.abs(sourcePos[1] - targetPos[1]);
  1671. var widthAdjusted = false, heightAdjusted = false;
  1672. // these are padding to ensure the whole connector line appears
  1673. var xo = 0.45 * w, yo = 0.45 * h;
  1674. // these are padding to ensure the whole connector line appears
  1675. w *= 1.9; h *=1.9;
  1676. var x = Math.min(sourcePos[0], targetPos[0]) - xo;
  1677. var y = Math.min(sourcePos[1], targetPos[1]) - yo;
  1678. if (w < 2 * lineWidth) {
  1679. w = 2 * lineWidth;
  1680. x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - lineWidth;
  1681. xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;
  1682. }
  1683. if (h < 2 * lineWidth) {
  1684. // minimum size is 2 * line Width
  1685. h = 2 * lineWidth;
  1686. y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - lineWidth;
  1687. yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;
  1688. }
  1689. var sx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  1690. var sy = sourcePos[1] < targetPos[1] ? h-yo : yo;
  1691. var tx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  1692. var ty = sourcePos[1] < targetPos[1] ? yo : h-yo;
  1693. var retVal = [ x, y, w, h, sx, sy, tx, ty ];
  1694. return retVal;
  1695. };
  1696. this.paint = function(dimensions, ctx)
  1697. {
  1698. ctx.beginPath();
  1699. ctx.moveTo(dimensions[4], dimensions[5]);
  1700. ctx.lineTo(dimensions[6], dimensions[7]);
  1701. ctx.stroke();
  1702. };
  1703. };
  1704. /**
  1705. * This Connector draws a Bezier curve with two control points.
  1706. * @param curviness How 'curvy' you want the curve to be! This is a directive for the
  1707. * placement of control points, not endpoints of the curve, so your curve does not
  1708. * actually touch the given point, but it has the tendency to lean towards it. the larger
  1709. * this value, the greater the curve is pulled from a straight line.
  1710. *
  1711. * a future implementation of this could take the control points as arguments, rather
  1712. * than fixing the curve to one basic shape.
  1713. */
  1714. jsPlumb.Connectors.Bezier = function(curviness) {
  1715. var self = this;
  1716. this.majorAnchor = curviness || 150;
  1717. this.minorAnchor = 10;
  1718. this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
  1719. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  1720. // points around if so (code could be tightened up)
  1721. var soo = sourceAnchor.getOrientation(), too = targetAnchor.getOrientation();
  1722. var perpendicular = soo[0] != too[0] || soo[1] == too[1];
  1723. var p = [];
  1724. var ma = self.majorAnchor, mi = self.minorAnchor;
  1725. if (!perpendicular) {
  1726. if (soo[0] == 0) // X
  1727. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  1728. else p.push(point[0] - (ma * soo[0]));
  1729. if (soo[1] == 0) // Y
  1730. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  1731. else p.push(point[1] + (ma * too[1]));
  1732. }
  1733. else {
  1734. if (too[0] == 0) // X
  1735. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  1736. else p.push(point[0] + (ma * too[0]));
  1737. if (too[1] == 0) // Y
  1738. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  1739. else p.push(point[1] + (ma * soo[1]));
  1740. }
  1741. return p;
  1742. };
  1743. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth)
  1744. {
  1745. lineWidth = lineWidth || 0;
  1746. var w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth, h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  1747. var canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2), canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  1748. var sx = sourcePos[0] < targetPos[0] ? w - (lineWidth/2): (lineWidth/2), sy = sourcePos[1] < targetPos[1] ? h-(lineWidth/2) : (lineWidth/2);
  1749. var tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : w-(lineWidth/2), ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : h-(lineWidth/2);
  1750. var CP = self._findControlPoint([sx,sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
  1751. var CP2 = self._findControlPoint([tx,ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
  1752. var minx1 = Math.min(sx,tx); var minx2 = Math.min(CP[0], CP2[0]); var minx = Math.min(minx1,minx2);
  1753. var maxx1 = Math.max(sx,tx); var maxx2 = Math.max(CP[0], CP2[0]); var maxx = Math.max(maxx1,maxx2);
  1754. if (maxx > w) w = maxx;
  1755. if (minx < 0) {
  1756. canvasX += minx; var ox = Math.abs(minx);
  1757. w += ox; CP[0] += ox; sx += ox; tx +=ox; CP2[0] += ox;
  1758. }
  1759. var miny1 = Math.min(sy,ty); var miny2 = Math.min(CP[1], CP2[1]); var miny = Math.min(miny1,miny2);
  1760. var maxy1 = Math.max(sy,ty); var maxy2 = Math.max(CP[1], CP2[1]); var maxy = Math.max(maxy1,maxy2);
  1761. if (maxy > h) h = maxy;
  1762. if (miny < 0) {
  1763. canvasY += miny; var oy = Math.abs(miny);
  1764. h += oy; CP[1] += oy; sy += oy; ty +=oy; CP2[1] += oy;
  1765. }
  1766. // return [ canvasx, canvasy, canvasWidth, canvasHeight,
  1767. // sourceX, sourceY, targetX, targetY,
  1768. // controlPoint1_X, controlPoint1_Y, controlPoint2_X, controlPoint2_Y
  1769. return [canvasX, canvasY, w, h, sx, sy, tx, ty, CP[0], CP[1], CP2[0], CP2[1] ];
  1770. };
  1771. this.paint = function(d, ctx) {
  1772. /*var img = new Image();
  1773. img.src = "../img/pattern.jpg";
  1774. ctx.fillStyle = ctx.createPattern(img, 'repeat-y');*/
  1775. ctx.beginPath();
  1776. ctx.moveTo(d[4],d[5]);
  1777. ctx.bezierCurveTo(d[8],d[9],d[10],d[11],d[6],d[7]);
  1778. ctx.stroke();
  1779. //ctx.fill();
  1780. }
  1781. };
  1782. /**
  1783. * Types of endpoint UIs. we supply four - a circle of default radius 10px, a rectangle of
  1784. * default size 20x20, an image (with no default), and a Triangle, of default size 15.
  1785. * you can supply others of these if you want to - see the documentation for a howto.
  1786. */
  1787. /**
  1788. * a round endpoint, with default radius 10 pixels.
  1789. */
  1790. jsPlumb.Endpoints.Dot = function(params) {
  1791. params = params || { radius:10 };
  1792. var self = this;
  1793. this.radius = params.radius;
  1794. var defaultOffset = 0.5 * this.radius;
  1795. var defaultInnerRadius = this.radius / 3;
  1796. var parseValue = function(value) {
  1797. try {
  1798. return parseInt(value);
  1799. }
  1800. catch(e) {
  1801. if (value.substring(value.length - 1) == '%')
  1802. return parseInt(value.substring(0, value - 1));
  1803. }
  1804. }
  1805. var calculateAdjustments = function(gradient) {
  1806. var offsetAdjustment = defaultOffset;
  1807. var innerRadius = defaultInnerRadius;
  1808. if (gradient.offset) offsetAdjustment = parseValue(gradient.offset);
  1809. if(gradient.innerRadius) innerRadius = parseValue(gradient.innerRadius);
  1810. return [offsetAdjustment, innerRadius];
  1811. };
  1812. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  1813. var radius = endpointStyle.radius || self.radius;
  1814. var x = anchorPoint[0] - radius;
  1815. var y = anchorPoint[1] - radius;
  1816. jsPlumb.sizeCanvas(canvas, x, y, radius * 2, radius * 2);
  1817. var ctx = canvas.getContext('2d');
  1818. var style = jsPlumb.extend({}, endpointStyle);
  1819. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  1820. jsPlumb.extend(ctx, style);
  1821. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  1822. if (endpointStyle.gradient && !ie) {
  1823. var adjustments = calculateAdjustments(endpointStyle.gradient);
  1824. var yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0];
  1825. var xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0];
  1826. var g = ctx.createRadialGradient(radius, radius, radius, radius + xAdjust, radius + yAdjust, adjustments[1]);
  1827. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  1828. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  1829. ctx.fillStyle = g;
  1830. }
  1831. ctx.beginPath();
  1832. ctx.arc(radius, radius, radius, 0, Math.PI*2, true);
  1833. ctx.closePath();
  1834. ctx.fill();
  1835. };
  1836. };
  1837. /**
  1838. * A Rectangular endpoint, with default size 20x20.
  1839. */
  1840. jsPlumb.Endpoints.Rectangle = function(params) {
  1841. params = params || { width:20, height:20 };
  1842. var self = this;
  1843. this.width = params.width;
  1844. this.height = params.height;
  1845. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  1846. var width = endpointStyle.width || self.width;
  1847. var height = endpointStyle.height || self.height;
  1848. var x = anchorPoint[0] - (width/2);
  1849. var y = anchorPoint[1] - (height/2);
  1850. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  1851. var ctx = canvas.getContext('2d');
  1852. //todo: the fillStyle needs some thought. we want to support a few options:
  1853. // 1. nothing supplied; use the stroke color or the default if no stroke color.
  1854. // 2. a fill color supplied - use it
  1855. // 3. a gradient supplied - use it
  1856. // 4. setting the endpoint to the same color as the bg of the element it is attached to.
  1857. var style = jsPlumb.extend({}, endpointStyle);
  1858. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  1859. jsPlumb.extend(ctx, style);
  1860. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  1861. if (endpointStyle.gradient && !ie) {
  1862. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  1863. var y1 = orientation[1] == 1 ? height : orientation[1] == 0 ? height / 2 : 0;
  1864. var y2 = orientation[1] == -1 ? height : orientation[1] == 0 ? height / 2 : 0;
  1865. var x1 = orientation[0] == 1 ? width : orientation[0] == 0 ? width / 2 : 0;
  1866. var x2 = orientation[0] == -1 ? width : orientation[0] == 0 ? height / 2 : 0;
  1867. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  1868. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  1869. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  1870. ctx.fillStyle = g;
  1871. }
  1872. ctx.beginPath();
  1873. ctx.rect(0, 0, width, height);
  1874. ctx.closePath();
  1875. ctx.fill();
  1876. };
  1877. };
  1878. jsPlumb.Endpoints.Triangle = function(params) {
  1879. params = params || { width:15, height:15 };
  1880. var self = this;
  1881. this.width = params.width;
  1882. this.height = params.height;
  1883. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
  1884. {
  1885. var width = endpointStyle.width || self.width;
  1886. var height = endpointStyle.height || self.height;
  1887. var x = anchorPoint[0] - width/2;
  1888. var y = anchorPoint[1] - height/2;
  1889. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  1890. var ctx = canvas.getContext('2d');
  1891. var
  1892. offsetX = 0,
  1893. offsetY = 0,
  1894. angle = 0;
  1895. if( orientation[0] == 1 )
  1896. {
  1897. offsetX = width;
  1898. offsetY = height;
  1899. angle = 180;
  1900. }
  1901. if( orientation[1] == -1 )
  1902. {
  1903. offsetX = width;
  1904. angle = 90;
  1905. }
  1906. if( orientation[1] == 1 )
  1907. {
  1908. offsetY = height;
  1909. angle = -90;
  1910. }
  1911. ctx.fillStyle = endpointStyle.fillStyle;
  1912. ctx.translate(offsetX, offsetY);
  1913. ctx.rotate(angle * Math.PI/180);
  1914. ctx.beginPath();
  1915. ctx.moveTo(0, 0);
  1916. ctx.lineTo(width/2, height/2);
  1917. ctx.lineTo(0, height);
  1918. ctx.closePath();
  1919. ctx.fill();
  1920. };
  1921. };
  1922. /**
  1923. * Image endpoint - draws an image as the endpoint. You must provide a 'url' property in the params object..
  1924. */
  1925. jsPlumb.Endpoints.Image = function(params) {
  1926. var self = this;
  1927. this.img = new Image();
  1928. var ready = false;
  1929. this.img.onload = function() {
  1930. self.ready = true;
  1931. };
  1932. this.img.src = params.url;
  1933. var actuallyPaint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  1934. var width = self.img.width || endpointStyle.width;
  1935. var height = self.img.height || endpointStyle.height;
  1936. var x = anchorPoint[0] - (width/2);
  1937. var y = anchorPoint[1] - (height/2);
  1938. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  1939. var ctx = canvas.getContext('2d');
  1940. ctx.drawImage(self.img,0,0);
  1941. };
  1942. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  1943. if (self.ready) {
  1944. actuallyPaint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
  1945. }
  1946. else
  1947. window.setTimeout(function() {
  1948. self.paint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle);
  1949. }, 200);
  1950. };
  1951. };
  1952. })();
  1953. //jQuery plugin code; v 1.2.1-RC1
  1954. (function($){
  1955. /**
  1956. * plumbs the results of the selector to some target, using the given options if supplied,
  1957. * or the defaults otherwise.
  1958. */
  1959. $.fn.plumb = function(options) {
  1960. var options = $.extend({}, options);
  1961. return this.each(function()
  1962. {
  1963. var params = $.extend({source:$(this)}, options);
  1964. jsPlumb.connect(params);
  1965. });
  1966. };
  1967. /**
  1968. * detaches the results of the selector from the given target or list of targets - 'target'
  1969. * may be a String or a List.
  1970. */
  1971. $.fn.detach = function(target) {
  1972. return this.each(function() {
  1973. if (target) {
  1974. var id = $(this).attr("id");
  1975. if (typeof target == 'string') target = [target];
  1976. for (var i = 0; i < target.length; i++)
  1977. jsPlumb.detach(id, target[i]);
  1978. }
  1979. });
  1980. };
  1981. /**
  1982. * detaches the results from the selector from all connections.
  1983. */
  1984. $.fn.detachAll = function() {
  1985. return this.each(function()
  1986. {
  1987. var id = $(this).attr("id");
  1988. jsPlumb.detachAll(id);
  1989. });
  1990. };
  1991. /**
  1992. * adds an endpoint to the elements resulting from the selector. options may be null,
  1993. * in which case jsPlumb will use the default options. see documentation.
  1994. */
  1995. $.fn.addEndpoint = function(options) {
  1996. var addedEndpoints = [];
  1997. this.each(function() {
  1998. addedEndpoints.push(jsPlumb.addEndpoint($(this).attr("id"), options));
  1999. });
  2000. return addedEndpoints[0];
  2001. };
  2002. /**
  2003. * adds a list of endpoints to the elements resulting from the selector. options may be null,
  2004. * in which case jsPlumb will use the default options. see documentation.
  2005. */
  2006. $.fn.addEndpoints = function(endpoints) {
  2007. var addedEndpoints = [];
  2008. return this.each(function() {
  2009. var e = jsPlumb.addEndpoints($(this).attr("id"), endpoints);
  2010. for (var i = 0; i < e.length; i++) addedEndpoints.push(e[i]);
  2011. });
  2012. return addedEndpoints;
  2013. };
  2014. /**
  2015. * remove the endpoint, if it exists, deleting its UI elements etc.
  2016. */
  2017. $.fn.removeEndpoint = function(endpoint) {
  2018. this.each(function() {
  2019. jsPlumb.removeEndpoint($(this).attr("id"), endpoint);
  2020. });
  2021. };
  2022. })(jQuery);
  2023. /*TODO: abstract this out from jQuery too! but how...because jsPlumb is not loaded yet.
  2024. $(window).bind('resize', function() {
  2025. if (resizeTimer) clearTimeout(resizeTimer);
  2026. resizeTimer = setTimeout(repaintEverything, 100);
  2027. });*/
  2028. /*
  2029. * the library agnostic functions, such as find offset, get id, get attribute, extend etc.
  2030. */
  2031. (function() {
  2032. jsPlumb.CurrentLibrary = {
  2033. /**
  2034. * mapping of drag events for jQuery
  2035. */
  2036. dragEvents : {
  2037. 'start':'start', 'stop':'stop', 'drag':'drag', 'step':'step',
  2038. 'over':'over', 'out':'out', 'drop':'drop', 'complete':'complete'
  2039. },
  2040. appendElement : function(child, parent) {
  2041. jsPlumb.CurrentLibrary.getElementObject(parent).append(child);
  2042. },
  2043. /**
  2044. * wrapper around the library's 'extend' functionality (which it hopefully has.
  2045. * otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
  2046. * instead. it's not like its hard.
  2047. */
  2048. extend : function(o1, o2) {
  2049. return $.extend(o1, o2);
  2050. },
  2051. /**
  2052. * gets an "element object" from the given input. this means an object that is used by the
  2053. * underlying library on which jsPlumb is running. 'el' may already be one of these objects,
  2054. * in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
  2055. * function is used to find the element, using the given String as the element's id.
  2056. *
  2057. * since 1.2.1 this method has had a cache applied to it. the cache is a very simple
  2058. * cache - a hashmap - so can grow and grow. this may not be optimum. but it does
  2059. * speed up performance:
  2060. *
  2061. * without cache, 312 connections take 5.22 seconds to create.
  2062. * with cache, 312 connections take 4.57 seconds to create. that's 13% faster.
  2063. */
  2064. getElementObject : function(el) {
  2065. return typeof(el)=='string' ? $("#" + el) : $(el);
  2066. },
  2067. /**
  2068. * gets the offset for the element object. this should return a js object like this:
  2069. *
  2070. * { left:xxx, top: xxx }
  2071. */
  2072. getOffset : function(el) {
  2073. return el.offset();
  2074. },
  2075. /**
  2076. * gets the size for the element object, in an array : [ width, height ].
  2077. */
  2078. getSize : function(el) {
  2079. return [el.outerWidth(), el.outerHeight()];
  2080. },
  2081. /**
  2082. * gets the named attribute from the given element object.
  2083. */
  2084. getAttribute : function(el, attName) {
  2085. return el.attr(attName);
  2086. },
  2087. /**
  2088. * sets the named attribute on the given element object.
  2089. */
  2090. setAttribute : function(el, attName, attValue) {
  2091. el.attr(attName, attValue);
  2092. },
  2093. /**
  2094. * adds the given class to the element object.
  2095. */
  2096. addClass : function(el, clazz) {
  2097. el.addClass(clazz);
  2098. },
  2099. /**
  2100. * initialises the given element to be draggable.
  2101. */
  2102. initDraggable : function(el, options) {
  2103. // remove helper directive if present. we know what's best!
  2104. options.helper = null;
  2105. //TODO: if 'revert' is set on the options it causes end points to animate back to
  2106. // where they came from, if the connection is aborted. do we care? probably not.
  2107. // the todo is to decide whether we care or not.
  2108. options['scope'] = options['scope'] || jsPlumb.Defaults.Scope;
  2109. el.draggable(options);
  2110. },
  2111. /**
  2112. * returns whether or not drag is supported (by the library, not whether or not it is disabled) for the given element.
  2113. */
  2114. isDragSupported : function(el, options) {
  2115. return el.draggable;
  2116. },
  2117. /**
  2118. * sets the draggable state for the given element
  2119. */
  2120. setDraggable : function(el, draggable) {
  2121. el.draggable("option", "disabled", !draggable);
  2122. },
  2123. /**
  2124. * initialises the given element to be droppable.
  2125. */
  2126. initDroppable : function(el, options) {
  2127. options['scope'] = options['scope'] || jsPlumb.Defaults.Scope;
  2128. el.droppable(options);
  2129. },
  2130. /**
  2131. * returns whether or not drop is supported (by the library, not whether or not it is disabled) for the given element.
  2132. */
  2133. isDropSupported : function(el, options) {
  2134. return el.droppable;
  2135. },
  2136. /**
  2137. * animates the given element.
  2138. */
  2139. animate : function(el, properties, options) {
  2140. el.animate(properties, options);
  2141. },
  2142. /**
  2143. * takes the args passed to an event function and returns you an object that gives the
  2144. * position of the object being moved, as a js object with the same params as the result of
  2145. * getOffset, ie: { left: xxx, top: xxx }.
  2146. *
  2147. * different libraries have different signatures for their event callbacks.
  2148. * see getDragObject as well
  2149. */
  2150. getUIPosition : function(eventArgs) {
  2151. var ui = eventArgs[1];
  2152. return ui.absolutePosition || ui.offset;
  2153. },
  2154. /**
  2155. * takes the args passed to an event function and returns you an object representing that which is being dragged.
  2156. */
  2157. getDragObject : function(eventArgs) {
  2158. return eventArgs[1].draggable;
  2159. },
  2160. removeElement : function(element, parent) {
  2161. jsPlumb.CurrentLibrary.getElementObject(element).remove();
  2162. },
  2163. getScrollLeft : function(el) {
  2164. return el.scrollLeft();
  2165. },
  2166. getScrollTop : function(el) {
  2167. return el.scrollTop();
  2168. }
  2169. };
  2170. })();