jquery.jsPlumb-all-1.1.1.js 78 KB

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