jsPlumb-1.2.3-RC1.js 82 KB

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