mootools.jsPlumb-1.2-all.js 79 KB

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