jsPlumb-1.2.5-RC1.js 83 KB

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