mootools.jsPlumb-1.2.3-all.js 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162
  1. /*
  2. * jsPlumb 1.2.3-RC1
  3. *
  4. * Provides a way to visually connect elements on an HTML page.
  5. *
  6. * additions since 1.2.2:
  7. *
  8. * - labels
  9. * - arrows
  10. *
  11. * http://morrisonpitt.com/jsPlumb/demo.html
  12. * http://code.google.com/p/jsPlumb
  13. *
  14. * Dual licensed under MIT and GPL2.
  15. *
  16. */
  17. (function() {
  18. /*
  19. Class: jsPlumb
  20. This is the main entry point to jsPlumb. There are a bunch of static methods you can
  21. use to connect/disconnect etc. Some methods are also added to jQuery's "$.fn" object itself, but
  22. in general jsPlumb is moving away from that model, preferring instead the static class
  23. approach. One of the reasons for this is that with no methods added to the jQuery $.fn object,
  24. it will be easier to provide support for other libraries such as MooTools.
  25. */
  26. var jsPlumbInstance = function() {
  27. var _currentInstance = this;
  28. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  29. var log = null;
  30. var repaintFunction = function() { jsPlumb.repaintEverything(); };
  31. var automaticRepaint = true;
  32. function repaintEverything() {
  33. if (automaticRepaint)
  34. repaintFunction();
  35. };
  36. var resizeTimer = null;
  37. /**
  38. * helper class for objects that generate events
  39. */
  40. var EventGenerator = function() {
  41. var _listeners = {};
  42. this.bind = function(event, listener) {
  43. var l = _listeners[event];
  44. if (!l) {
  45. l = [];
  46. _listeners[event] = l;
  47. }
  48. l.push(listener);
  49. };
  50. this.fireUpdate = function(event, value) {
  51. if (_listeners[event]) {
  52. for (var i = 0; i < _listeners[event].length; i++) {
  53. try {
  54. _listeners[event][i](value);
  55. }
  56. catch (e) { }
  57. }
  58. }
  59. };
  60. };
  61. /**
  62. * map of element id -> endpoint lists. an element can have an arbitrary number of endpoints on it,
  63. * and not all of them have to be connected to anything.
  64. */
  65. var endpointsByElement = {};
  66. var endpointsByUUID = {};
  67. var connectionsByScope = {};
  68. var offsets = [];
  69. var floatingConnections = {};
  70. var draggableStates = {};
  71. var _draggableByDefault = true;
  72. var sizes = [];
  73. var listeners = {}; // a map: keys are event types, values are lists of listeners.
  74. var DEFAULT_SCOPE = 'DEFAULT';
  75. var DEFAULT_NEW_CANVAS_SIZE = 1200; // only used for IE; a canvas needs a size before the init call to excanvas (for some reason. no idea why.)
  76. var _findIndex = function( a, v, b, s ) {
  77. var _eq = function(o1, o2) {
  78. if (o1 === o2) return true;
  79. else if (typeof o1 == 'object' && typeof o2 == 'object') {
  80. var same = true;
  81. for(var propertyName in o1) {
  82. if(!_eq(o1[propertyName], o2[propertyName])) {
  83. same = false;
  84. break;
  85. }
  86. }
  87. for(var propertyName in o2) {
  88. if(!_eq(o2[propertyName], o1[propertyName])) {
  89. same = false;
  90. break;
  91. }
  92. }
  93. return same;
  94. }
  95. };
  96. for( var i = +b || 0, l = a.length; i < l; i++ ) {
  97. if( _eq(a[i], v)) return i;
  98. }
  99. return -1;
  100. };
  101. /**
  102. * adds a listener for the specified event type.
  103. */
  104. var _addListener = function(eventType, listener) {
  105. var doOne = function(e, l) {
  106. _addToList(listeners, e, l);
  107. };
  108. if (typeof eventType == 'object' && eventType.length) {
  109. for (var i = 0; i < eventType.length; i++) doOne(eventType[i], listener);
  110. } else doOne(eventType, listener);
  111. };
  112. /**
  113. * helper method to add an item to a list, creating the list if it does not yet exist.
  114. */
  115. var _addToList = function(map, key, value) {
  116. var l = map[key];
  117. if (l == null) {
  118. l = [];
  119. map[key] = l;
  120. }
  121. l.push(value);
  122. return l;
  123. };
  124. var _appendElement = function(canvas, parent) {
  125. if (!parent) document.body.appendChild(canvas);
  126. else jsPlumb.CurrentLibrary.appendElement(canvas, parent);
  127. };
  128. /**
  129. * Handles the dragging of an element.
  130. * @param element jQuery element
  131. * @param ui UI object from current library's event system
  132. */
  133. var _draw = function(element, ui) {
  134. var id = _getAttribute(element, "id");
  135. var endpoints = endpointsByElement[id];
  136. if (endpoints) {
  137. var timestamp = '' + (new Date().getTime());
  138. _updateOffset(id, ui);
  139. var myOffset = offsets[id];
  140. var myWH = sizes[id];
  141. // loop through endpoints for this element
  142. for (var i = 0; i < endpoints.length; i++) {
  143. var e = endpoints[i];
  144. var l = e.connections;
  145. // here we have a little quandary. if an endpoint is connected to some other element, and it
  146. // has a selective anchor, then we want to know that element's position when we find our
  147. // anchor. if it has no connections then fine, we use the default anchor in the list we can
  148. // select from. but if it has more than one connection, what then? we need to compute where
  149. // it is best placed relative to all other elements, and we then want to lock that position
  150. // for the rest of this paint cycle. if we do not do that, it's possible that an endpoint will
  151. // be moved by an ensuing connector's paint.
  152. if (e.anchor.isSelective && l.length > 0) {
  153. var c = l[0];
  154. var oIdx = c.endpoints[0] == e ? 1 : 0;
  155. var oId = oIdx == 0 ? c.sourceId : c.targetId;
  156. var oOffset = offsets[oId], oWH = sizes[oId];
  157. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH, e, [oOffset.left, oOffset.top], oWH, c.endpoints[oIdx]);
  158. e.paint(anchorLoc);
  159. }
  160. else {
  161. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH, e);
  162. e.paint(anchorLoc);
  163. }
  164. for (var j = 0; j < l.length; j++) {
  165. l[j].paint(id, ui, false, timestamp); // ...and paint them.
  166. var oIdx = l[j].endpoints[0] == e ? 1 : 0;
  167. // if the other endpoint has a selective anchor then it might need to be repainted, because it may have just moved
  168. // position. it is possible we could cache the knowledge about that and not run this paint code all the time.
  169. if (l[j].endpoints[oIdx].anchor.isSelective) {
  170. var oId = oIdx == 0 ? l[j].sourceId : l[j].targetId;
  171. var oOffset = offsets[oId], oWH = sizes[oId];
  172. var anchorLoc = l[j].endpoints[oIdx].anchor.compute([oOffset.left, oOffset.top], oWH, l[j].endpoints[oIdx], [myOffset.left, myOffset.top], myWH, e);
  173. l[j].endpoints[oIdx].paint(anchorLoc);
  174. }
  175. }
  176. }
  177. }
  178. };
  179. /**
  180. * helper function: the second argument is a function taking two args - the first is an id
  181. * ui element from the current library (or list of them), and the second is the function
  182. * to run.
  183. */
  184. var _elementProxy = function(element, fn) {
  185. var retVal = null;
  186. if (typeof element == 'object' && element.length) {
  187. retVal = [];
  188. for (var i = 0; i < element.length; i++) {
  189. var el = _getElementObject(element[i]);
  190. var id = _getAttribute(el, "id");
  191. retVal.push(fn(el, id)); // append return values to what we will return
  192. }
  193. }
  194. else {
  195. var el = _getElementObject(element);
  196. var id = _getAttribute(el, "id");
  197. retVal = fn(el, id);
  198. }
  199. return retVal;
  200. };
  201. /**
  202. * fires an event of the given type.
  203. */
  204. var _fireEvent = function(eventType, data) {
  205. var l = listeners[eventType];
  206. if (l) {
  207. for (var i in l) {
  208. try {
  209. l[i][eventType](data);
  210. }
  211. catch (e) {
  212. _log("while firing event [" + eventType + "]; listener failed like this: " + e);
  213. }
  214. }
  215. }
  216. };
  217. var _log = function(msg) {
  218. //if (console) console.log(msg);
  219. };
  220. var _logFnCall = function(fn, args) {
  221. /*if (console) {
  222. var c = args.callee.caller.toString();
  223. var i = c.indexOf("{");
  224. var msg = fn + ' : ' + c.substring(0, i);
  225. console.log(msg);
  226. }*/
  227. };
  228. var cached = {};
  229. var __getElementObject = function(el) {
  230. if (typeof(el)=='string') {
  231. var e = cached[el];
  232. if (!e) {
  233. e = jsPlumb.CurrentLibrary.getElementObject(el);
  234. cached[el] = e;
  235. }
  236. return e;
  237. }
  238. else {
  239. return jsPlumb.CurrentLibrary.getElementObject(el);
  240. }
  241. };
  242. /**
  243. * gets the named attribute from the given element (id or element object)
  244. */
  245. var _getAttribute = function(el, attName) {
  246. var ele = __getElementObject(el);
  247. return jsPlumb.CurrentLibrary.getAttribute(ele, attName);
  248. };
  249. var _setAttribute = function(el, attName, attValue) {
  250. var ele = __getElementObject(el);
  251. jsPlumb.CurrentLibrary.setAttribute(ele, attName, attValue);
  252. };
  253. var _addClass = function(el, clazz) {
  254. var ele = __getElementObject(el);
  255. jsPlumb.CurrentLibrary.addClass(ele, clazz);
  256. };
  257. var _getElementObject = function(elId) {
  258. return __getElementObject(elId);
  259. };
  260. var _getOffset = function(el) {
  261. var ele = __getElementObject(el);
  262. return jsPlumb.CurrentLibrary.getOffset(ele);
  263. };
  264. var _getSize = function(el) {
  265. var ele = __getElementObject(el);
  266. return jsPlumb.CurrentLibrary.getSize(ele);
  267. };
  268. /**
  269. * gets an id for the given element, creating and setting one if necessary.
  270. */
  271. var _getId = function(element, uuid) {
  272. var ele = _getElementObject(element);
  273. var id = _getAttribute(ele, "id");
  274. if (!id) {
  275. //check if fixed uuid parameter is given
  276. if(arguments.length == 2)
  277. id = uuid;
  278. else
  279. id = "_jsPlumb_" + new String((new Date()).getTime());
  280. _setAttribute(ele, "id", id);
  281. }
  282. return id;
  283. };
  284. /**
  285. * gets an Endpoint by uuid.
  286. */
  287. var _getEndpoint = function(uuid) {
  288. return endpointsByUUID[uuid];
  289. };
  290. /**
  291. * inits a draggable if it's not already initialised.
  292. */
  293. var _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  294. // dragging
  295. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  296. if (draggable) {
  297. if (jsPlumb.CurrentLibrary.isDragSupported(element)) {
  298. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  299. options = jsPlumb.extend({}, options); // make a copy.
  300. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  301. options[dragEvent] = _wrap(options[dragEvent], function() {
  302. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  303. _draw(element, ui);
  304. _addClass(element, "jsPlumb_dragged");
  305. });
  306. var draggable = draggableStates[_getId(element)];
  307. options.disabled = draggable == null ? false : !draggable;
  308. jsPlumb.CurrentLibrary.initDraggable(element, options);
  309. }
  310. }
  311. };
  312. /**
  313. * helper to create a canvas.
  314. * @param clazz optional class name for the canvas.
  315. */
  316. var _newCanvas = function(clazz, parent, uuid) {
  317. var canvas = document.createElement("canvas");
  318. _appendElement(canvas, parent);
  319. canvas.style.position="absolute";
  320. if (clazz) { canvas.className=clazz; }
  321. // set an id. if no id on the element and if uuid was supplied it will be used, otherwise we'll create one.
  322. _getId(canvas, uuid);
  323. if (ie) {
  324. // for IE we have to set a big canvas size. actually you can override this, too, if 1200 pixels
  325. // is not big enough for the biggest connector/endpoint canvas you have at startup.
  326. jsPlumb.sizeCanvas(canvas, 0, 0, DEFAULT_NEW_CANVAS_SIZE, DEFAULT_NEW_CANVAS_SIZE);
  327. canvas = G_vmlCanvasManager.initElement(canvas);
  328. }
  329. return canvas;
  330. };
  331. /**
  332. * performs the given function operation on all the connections found for the given element
  333. * id; this means we find all the endpoints for the given element, and then for each endpoint
  334. * find the connectors connected to it. then we pass each connection in to the given
  335. * function.
  336. */
  337. var _operation = function(elId, func) {
  338. var endpoints = endpointsByElement[elId];
  339. if (endpoints && endpoints.length) {
  340. for (var i = 0; i < endpoints.length; i++) {
  341. for (var j = 0; j < endpoints[i].connections.length; j++) {
  342. var retVal = func(endpoints[i].connections[j]);
  343. // if the function passed in returns true, we exit.
  344. // most functions return false.
  345. if (retVal) return;
  346. }
  347. }
  348. }
  349. };
  350. /**
  351. * perform an operation on all elements.
  352. */
  353. var _operationOnAll = function(func) {
  354. for (var elId in endpointsByElement) {
  355. _operation(elId, func);
  356. }
  357. };
  358. /**
  359. * helper to remove an element from the DOM.
  360. */
  361. var _removeElement = function(element, parent) {
  362. if (element != null) {
  363. if (!parent) {
  364. try { document.body.removeChild(element); }
  365. catch (e) { }
  366. } else {
  367. jsPlumb.CurrentLibrary.removeElement(element, parent);
  368. }
  369. }
  370. };
  371. /**
  372. * helper to remove a list of elements from the DOM.
  373. */
  374. var _removeElements = function(elements, parent) {
  375. for (var i = 0; i < elements.length; i++)
  376. _removeElement(elements[i], parent);
  377. };
  378. /**
  379. * helper method to remove an item from a list.
  380. */
  381. var _removeFromList = function(map, key, value) {
  382. var l = map[key];
  383. if (l != null) {
  384. var i = _findIndex(l, value);
  385. if (i >= 0) {
  386. delete( l[i] );
  387. l.splice( i, 1 );
  388. return true;
  389. }
  390. }
  391. return false;
  392. };
  393. /**
  394. * Sets whether or not the given element(s) should be draggable, regardless of what a particular
  395. * plumb command may request.
  396. *
  397. * @param element May be a string, a jQuery elements, or a list of strings/jquery elements.
  398. * @param draggable Whether or not the given element(s) should be draggable.
  399. */
  400. var _setDraggable = function(element, draggable) {
  401. var _helper = function(el, id) {
  402. draggableStates[id] = draggable;
  403. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  404. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  405. }
  406. };
  407. return _elementProxy(element, _helper);
  408. };
  409. /**
  410. * private method to do the business of hiding/showing.
  411. * @param el either Id of the element in question or a jquery object for the element.
  412. * @param state String specifying a value for the css 'display' property ('block' or 'none').
  413. */
  414. var _setVisible = function(el, state) {
  415. var elId = _getAttribute(el, "id");
  416. var f = function(jpc) {
  417. jpc.canvas.style.display = state;
  418. };
  419. _operation(elId, f);
  420. };
  421. /**
  422. * toggles the draggable state of the given element(s).
  423. * @param el either an id, or a jquery object, or a list of ids/jquery objects.
  424. */
  425. var _toggleDraggable = function(el) {
  426. var fn = function(el, elId) {
  427. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  428. state = !state;
  429. draggableStates[elId] = state;
  430. jsPlumb.CurrentLibrary.setDraggable(el, state);
  431. return state;
  432. };
  433. return _elementProxy(el, fn);
  434. };
  435. /**
  436. * private method to do the business of toggling hiding/showing.
  437. * @param elId Id of the element in question
  438. */
  439. var _toggleVisible = function(elId) {
  440. var f = function(jpc) {
  441. var state = ('none' == jpc.canvas.style.display);
  442. jpc.canvas.style.display = state ? "block" : "none";
  443. };
  444. _operation(elId, f);
  445. //todo this should call _elementProxy, and pass in the _operation(elId, f) call as a function. cos _toggleDraggable does that.
  446. };
  447. /**
  448. * updates the offset and size for a given element, and stores the values.
  449. * if 'offset' is not null we use that (it would have been passed in from a drag call) because it's faster; but if it is null,
  450. * or if 'recalc' is true in order to force a recalculation, we use the offset, outerWidth and outerHeight methods to get
  451. * the current values.
  452. */
  453. var _updateOffset = function(elId, offset, recalc) {
  454. if (recalc || offset == null) { // if forced repaint or no offset available, we recalculate.
  455. // get the current size and offset, and store them
  456. var s = _getElementObject(elId);
  457. sizes[elId] = _getSize(s);
  458. offsets[elId] = _getOffset(s);
  459. } else {
  460. offsets[elId] = offset;
  461. }
  462. };
  463. /**
  464. * wraps one function with another, creating a placeholder for the wrapped function
  465. * if it was null. this is used to wrap the various drag/drop event functions - to allow
  466. * jsPlumb to be notified of important lifecycle events without imposing itself on the user's
  467. * drag/drop functionality.
  468. * TODO: determine whether or not we should support an error handler concept, if one of the functions fails.
  469. */
  470. var _wrap = function(wrappedFunction, newFunction) {
  471. wrappedFunction = wrappedFunction || function() { };
  472. newFunction = newFunction || function() { };
  473. return function() {
  474. var r = null;
  475. try { r = newFunction.apply(this, arguments); }
  476. catch (e) {
  477. _log('jsPlumb function failed : ' + e);
  478. }
  479. try { wrappedFunction.apply(this, arguments);
  480. }
  481. catch (e) {
  482. _log('wrapped function failed : ' + e);
  483. }
  484. return r;
  485. };
  486. };
  487. /*
  488. Class: Anchor
  489. Models a position relative to the origin of some element that an Endpoint can be located.
  490. */
  491. /*
  492. Function: Anchor
  493. Constructor for the Anchor class
  494. Parameters:
  495. params - Anchor parameters. This should contain three values, and may optionally have an 'offsets' argument:
  496. - x : the x location of the anchor as a fraction of the total width.
  497. - y : the y location of the anchor as a fraction of the total height.
  498. - orientation : an [x,y] array indicating the general direction a connection from the anchor should go in. for more info on this, see the documentation, or the docs in jquery-jsPlumb-defaults-XXX.js for the default Anchors.
  499. - offsets : an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out. may be null.
  500. */
  501. var Anchor = function(params) {
  502. var self = this;
  503. this.x = params.x || 0; this.y = params.y || 0;
  504. var orientation = params.orientation || [0,0];
  505. var lastTimestamp = null;
  506. var lastReturnValue = null;
  507. this.offsets = params.offsets || [0,0];
  508. this.compute = function(xy, wh, element, txy, twh, tElement) {
  509. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1]];
  510. var container = element? element.container : null;
  511. var containerAdjustment = {left:0, top:0 };
  512. if (container != null) {
  513. var eo = _getElementObject(container);
  514. var o = _getOffset(eo);
  515. var sl = jsPlumb.CurrentLibrary.getScrollLeft(eo);
  516. var st = jsPlumb.CurrentLibrary.getScrollTop(eo);
  517. containerAdjustment.left = o.left - sl;
  518. containerAdjustment.top = o.top - st;
  519. lastReturnValue[0] = lastReturnValue[0] - containerAdjustment.left;
  520. lastReturnValue[1] = lastReturnValue[1] - containerAdjustment.top;
  521. }
  522. return lastReturnValue;
  523. };
  524. this.getOrientation = function() { return orientation; };
  525. this.equals = function(anchor) {
  526. if (!anchor) return false;
  527. var ao = anchor.getOrientation();
  528. var o = this.getOrientation();
  529. return this.x == anchor.x && this.y == anchor.y && this.offsets[0] == anchor.offsets[0] && this.offsets[1] == anchor.offsets[1] && o[0] == ao[0] && o[1] == ao[1];
  530. };
  531. };
  532. /**
  533. * An Anchor that floats. its orientation is computed dynamically from its position relative to the anchor it is floating relative to.
  534. *
  535. */
  536. var FloatingAnchor = function(params) {
  537. // this is the anchor that this floating anchor is referenced to for purposes of calculating the orientation.
  538. var ref = params.reference;
  539. // the canvas this refers to.
  540. var refCanvas = params.referenceCanvas;
  541. var size = _getSize(_getElementObject(refCanvas));
  542. // these are used to store the current relative position of our anchor wrt the reference anchor. they only indicate
  543. // direction, so have a value of 1 or -1 (or, very rarely, 0). these values are written by the compute method, and read
  544. // by the getOrientation method.
  545. var xDir = 0, yDir = 0;
  546. // temporary member used to store an orientation when the floating anchor is hovering over another anchor.
  547. var orientation = null;
  548. this.compute = function(xy, wh, txy, twh) {
  549. // set these for the getOrientation method to use.
  550. xDir = 0;//xy[0] < txy[0] ? -1 : xy[0] == txy[0] ? 0 : 1;
  551. yDir = 0;//xy[1] < txy[1] ? -1 : xy[1] == txy[1] ? 0 : 1;
  552. return [xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
  553. };
  554. this.getOrientation = function() {
  555. if (orientation) return orientation;
  556. else {
  557. var o = ref.getOrientation();
  558. // here we take into account the orientation of the other anchor: if it declares zero for some direction, we declare zero too.
  559. // this might not be the most awesome. perhaps we can come up with a better way. it's just so that the line we draw looks
  560. // like it makes sense. maybe this wont make sense.
  561. return [Math.abs(o[0]) * xDir * -1, Math.abs(o[1]) * yDir * -1];
  562. }
  563. };
  564. /**
  565. * notification the endpoint associated with this anchor is hovering over another anchor;
  566. * we want to assume that anchor's orientation for the duration of the hover.
  567. */
  568. this.over = function(anchor) {
  569. orientation = anchor.getOrientation();
  570. };
  571. /**
  572. * notification the endpoint associated with this anchor is no longer hovering
  573. * over another anchor; we should resume calculating orientation as we normally do.
  574. */
  575. this.out = function() {
  576. orientation = null;
  577. };
  578. };
  579. /**
  580. * An Anchor that contains a list of other Anchors, and which it cycles through at compute time and finds the one that is located closest to
  581. * the center of the target element, and returns that Anchor's compute method result. this causes endpoints to follow each other with respect
  582. * to the orientation of their target elements - a useful feature for some applications.
  583. */
  584. var DynamicAnchor = function(anchors) {
  585. this.isSelective = true;
  586. this.isDynamic = true;
  587. var _anchors = anchors || [];
  588. this.addAnchor = function(anchor) { _anchors.push(anchor); };
  589. var _curAnchor = _anchors.length > 0 ? _anchors[0] : null;
  590. var _curIndex = _anchors.length > 0 ? 0 : -1;
  591. this.locked = false;
  592. var self = this;
  593. //todo set a default anchor?
  594. var _distance = function(anchor, cx, cy, xy, wh) {
  595. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
  596. return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
  597. };
  598. this.compute = function(xy, wh, element, txy, twh, tElement) {
  599. // if anchor is locked or an opposite element was not given, we maintain our state. anchor will be locked
  600. // if it is the source of a drag and drop.
  601. if (self.locked || txy == null || twh == null) {
  602. return _curAnchor.compute(xy, wh, element, txy, twh, tElement);
  603. }
  604. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  605. var minIdx = -1, minDist = Infinity;
  606. for (var i = 0; i < _anchors.length; i++) {
  607. var d = _distance(_anchors[i], cx, cy, xy, wh);
  608. if (d < minDist) {
  609. minIdx = i + 0;
  610. minDist = d;
  611. }
  612. }
  613. _curAnchor = _anchors[minIdx];
  614. var pos = _curAnchor.compute(xy, wh, element, txy, twh, tElement);
  615. return pos;
  616. };
  617. this.getOrientation = function() {
  618. return _curAnchor != null ? _curAnchor.getOrientation() : [0,0];
  619. };
  620. this.over = function(anchor) {
  621. if (_curAnchor != null) _curAnchor.over(anchor);
  622. };
  623. this.out = function() {
  624. if (_curAnchor != null) _curAnchor.out();
  625. };
  626. };
  627. // ************** connection
  628. // ****************************************
  629. /**
  630. * allowed params:
  631. * source: source element (string or a jQuery element) (required)
  632. * target: target element (string or a jQuery element) (required)
  633. *
  634. * anchors: optional array of anchor placements. defaults to BottomCenter for source
  635. * and TopCenter for target.
  636. */
  637. var Connection = function(params) {
  638. EventGenerator.apply(this);
  639. // ************** get the source and target and register the connection. *******************
  640. var self = this;
  641. var id = new String('_jsplumb_c_' + (new Date()).getTime());
  642. this.getId = function() { return id; };
  643. this.container = params.container || _currentInstance.Defaults.Container; // may be null; we will append to the body if so.
  644. // get source and target as jQuery objects
  645. this.source = _getElementObject(params.source);
  646. this.target = _getElementObject(params.target);
  647. // sourceEndpoint and targetEndpoint override source/target, if they are present.
  648. if (params.sourceEndpoint)
  649. this.source = params.sourceEndpoint.getElement();
  650. if (params.targetEndpoint)
  651. this.target = params.targetEndpoint.getElement();
  652. this.sourceId = _getAttribute(this.source, "id");
  653. this.targetId = _getAttribute(this.target, "id");
  654. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  655. this.scope = params.scope; // scope may have been passed in to the connect call.
  656. // if it wasn't, we will pull it from the source endpoint,
  657. // after having initialised the endpoints.
  658. // init endpoints
  659. this.endpoints = [];
  660. this.endpointStyles = [];
  661. var prepareEndpoint = function(existing, index, params, element) {
  662. if (existing) {
  663. self.endpoints[index] = existing;
  664. existing.addConnection(self);
  665. }
  666. else {
  667. if(!params.endpoints) params.endpoints = [null,null];
  668. var ep = params.endpoints[index] || params.endpoint || _currentInstance.Defaults.Endpoints[index] || jsPlumb.Defaults.Endpoints[index] || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || new jsPlumb.Endpoints.Dot();
  669. if (!params.endpointStyles) params.endpointStyles = [null,null];
  670. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  671. var a = params.anchors ? params.anchors[index] : _currentInstance.Defaults.Anchors[index] || jsPlumb.Defaults.Anchors[index] || _currentInstance.Defaults.Anchor || jsPlumb.Defaults.Anchor || jsPlumb.Anchors.BottomCenter;
  672. var u = params.uuids ? params.uuids[index] : null;
  673. if(params.uuids)
  674. var e = new Endpoint({style:es, endpoint:ep, connections:[self], uuid:u, anchor:a, source:element, container:self.container });
  675. else
  676. var e = new Endpoint({style:es, endpoint:ep, connections:[self], anchor:a, source:element, container:self.container });
  677. self.endpoints[index] = e;
  678. return e;
  679. }
  680. };
  681. var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source);
  682. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  683. var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target);
  684. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  685. // if scope not set, set it to be the scope for the source endpoint.
  686. if (!this.scope) this.scope = this.endpoints[0].scope;
  687. this.connector = this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _currentInstance.Defaults.Connector || jsPlumb.Defaults.Connector || new jsPlumb.Connectors.Bezier();
  688. this.paintStyle = this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _currentInstance.Defaults.PaintStyle || jsPlumb.Defaults.PaintStyle;
  689. this.backgroundPaintStyle = this.endpoints[0].connectorBackgroundStyle || this.endpoints[1].connectorBackgroundStyle || params.backgroundPaintStyle || _currentInstance.Defaults.BackgroundPaintStyle || jsPlumb.Defaults.BackgroundPaintStyle;
  690. // init overlays
  691. this.overlays = params.overlays || [];
  692. this.addOverlay = function(overlay) {
  693. overlays.push(overlay);
  694. };
  695. // this is a shortcut helper method to let people add a label as overlay.
  696. this.labelStyle = params.labelStyle || _currentInstance.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;;
  697. this.label = params.label;
  698. if (this.label) {
  699. this.overlays.push(new jsPlumb.Overlays.Label({labelStyle:this.labelStyle, label:this.label}));
  700. };
  701. _updateOffset(this.sourceId);
  702. _updateOffset(this.targetId);
  703. // functions for mouse hover/select functionality
  704. this.distanceFrom = function(point) { return self.connector.distanceFrom(point); };
  705. this.setLabel = function(l) {
  706. self.label = l;
  707. _currentInstance.repaint(self.source);
  708. };
  709. // paint the endpoints
  710. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  711. var otherOffset = offsets[this.targetId]; otherWH = sizes[this.targetId];
  712. var anchorLoc = this.endpoints[0].anchor.compute([myOffset.left, myOffset.top], myWH, this.endpoints[0], [otherOffset.left, otherOffset.top], otherWH, this.endpoints[1]);
  713. this.endpoints[0].paint(anchorLoc);
  714. anchorLoc = this.endpoints[1].anchor.compute([otherOffset.left, otherOffset.top], otherWH, this.endpoints[1], [myOffset.left, myOffset.top], myWH, this.endpoints[0]);
  715. this.endpoints[1].paint(anchorLoc);
  716. // *************** create canvas on which the connection will be drawn ************
  717. var canvas = _newCanvas(jsPlumb.connectorClass, self.container);
  718. this.canvas = canvas;
  719. /**
  720. * paints the connection.
  721. * @param elId Id of the element that is in motion
  722. * @param ui current library's event system ui object (present if we came from a drag to get here)
  723. * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
  724. */
  725. this.paint = function(elId, ui, recalc, timestamp) {
  726. var fai = self.floatingAnchorIndex;
  727. // if the moving object is not the source we must transpose the two references.
  728. var swap = false;//!(elId == this.sourceId);
  729. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  730. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  731. var el = swap ? this.target : this.source;
  732. if (this.canvas.getContext) {
  733. _updateOffset(elId, ui, recalc);
  734. _updateOffset(tId); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  735. var myOffset = offsets[sId];
  736. var otherOffset = offsets[tId];
  737. var myWH = sizes[sId];
  738. var otherWH = sizes[tId];
  739. var ctx = canvas.getContext('2d');
  740. //TODO: why are these calculated again? they were calculated in the _draw function.
  741. var sAnchorP = this.endpoints[sIdx].anchor.compute([myOffset.left, myOffset.top], myWH, this.endpoints[sIdx], [otherOffset.left, otherOffset.top], otherWH, this.endpoints[tIdx]);
  742. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  743. var tAnchorP = this.endpoints[tIdx].anchor.compute([otherOffset.left, otherOffset.top], otherWH, this.endpoints[tIdx], [myOffset.left, myOffset.top], myWH, this.endpoints[sIdx]);
  744. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  745. // paint overlays
  746. var maxSize = 0;
  747. for (var i = 0; i < self.overlays.length; i++) {
  748. var o = self.overlays[i];
  749. var s = o.computeMaxSize(self.connector, ctx);
  750. if (s > maxSize) maxSize = s;
  751. }
  752. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, this.paintStyle.lineWidth, maxSize);
  753. jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
  754. var _paintOneStyle = function(ctx, paintStyle) {
  755. ctx.save();
  756. jsPlumb.extend(ctx, paintStyle);
  757. if (paintStyle.gradient && !ie) {
  758. var g = self.connector.createGradient(dim, ctx, (elId == this.sourceId));
  759. for (var i = 0; i < paintStyle.gradient.stops.length; i++)
  760. g.addColorStop(paintStyle.gradient.stops[i][0],paintStyle.gradient.stops[i][1]);
  761. ctx.strokeStyle = g;
  762. }
  763. self.connector.paint(dim, ctx);
  764. ctx.restore();
  765. };
  766. // first check for the background style
  767. if (this.backgroundPaintStyle != null) {
  768. _paintOneStyle(ctx, this.backgroundPaintStyle);
  769. }
  770. _paintOneStyle(ctx, this.paintStyle);
  771. // paint overlays
  772. for (var i = 0; i < self.overlays.length; i++) {
  773. var o = self.overlays[i];
  774. o.draw(self.connector, ctx);
  775. }
  776. }
  777. };
  778. //TODO: should this take a timestamp? probably. it reduces the amount of time
  779. // spent figuring out anchor locations.
  780. this.repaint = function() {
  781. this.paint(this.sourceId, null, true);
  782. };
  783. _initDraggableIfNecessary(self.source, params.draggable, params.dragOptions);
  784. _initDraggableIfNecessary(self.target, params.draggable, params.dragOptions);
  785. // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
  786. if (this.source.resize) {
  787. this.source.resize(function(e) {
  788. jsPlumb.repaint(self.sourceId);
  789. });
  790. }
  791. };
  792. /*
  793. Class: Endpoint
  794. Models an endpoint. Can have one to N connections emanating from it (although how to handle that in the UI is
  795. a very good question). also has a Canvas and paint style.
  796. */
  797. /*
  798. Function: Endpoint
  799. This is the Endpoint class constructor.
  800. Parameters:
  801. anchor - anchor for the endpoint, of type jsPlumb.Anchor. may be null.
  802. endpoint - endpoint object, of type jsPlumb.Endpoint. may be null.
  803. style - endpoint style, a js object. may be null.
  804. source - element the endpoint is attached to, of type jquery object. Required.
  805. canvas - canvas element to use. may be, and most often is, null.
  806. connections - optional list of connections to configure the endpoint with.
  807. isSource - boolean. indicates the endpoint can act as a source of new connections. optional.
  808. dragOptions - if isSource is set to true, you can supply arguments for the jquery draggable method. optional.
  809. connectionStyle - if isSource is set to true, this is the paint style for connections from this endpoint. optional.
  810. connector - optional connector type to use.
  811. isTarget - boolean. indicates the endpoint can act as a target of new connections. optional.
  812. dropOptions - if isTarget is set to true, you can supply arguments for the jquery droppable method. optional.
  813. reattach - optional boolean that determines whether or not the connections reattach after they
  814. have been dragged off an endpoint and left floating. defaults to false: connections
  815. dropped in this way will just be deleted.
  816. */
  817. var Endpoint = function(params) {
  818. params = params || {};
  819. // make a copy. then we can use the wrapper function.
  820. jsPlumb.extend({}, params);
  821. var self = this;
  822. var id = new String('_jsplumb_e_' + (new Date()).getTime());
  823. this.getId = function() { return id; };
  824. self.anchor = params.anchor || jsPlumb.Anchors.TopCenter;
  825. //if (self.anchor.isDynamic) self.anchor.endpoint = self;
  826. var _endpoint = params.endpoint || new jsPlumb.Endpoints.Dot();
  827. var _style = params.style || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  828. this.connectorStyle = params.connectorStyle;
  829. this.connector = params.connector;
  830. this.isSource = params.isSource || false;
  831. this.isTarget = params.isTarget || false;
  832. var _element = params.source;
  833. var _uuid = params.uuid;
  834. if (_uuid) endpointsByUUID[_uuid] = self;
  835. this.container = params.container || _currentInstance.Defaults.Container || jsPlumb.Defaults.Container;
  836. var _elementId = _getAttribute(_element, "id");
  837. var _maxConnections = params.maxConnections || 1; // maximum number of connections this endpoint can be the source of.
  838. this.canvas = params.canvas || _newCanvas(jsPlumb.endpointClass, this.container, params.uuid);
  839. this.connections = params.connections || [];
  840. this.scope = params.scope || DEFAULT_SCOPE;
  841. var _reattach = params.reattach || false;
  842. var floatingEndpoint = null;
  843. var inPlaceCopy = null;
  844. this.dragAllowedWhenFull = params.dragAllowedWhenFull || true;
  845. this.addConnection = function(connection) {
  846. self.connections.push(connection);
  847. };
  848. this.detach = function(connection) {
  849. var idx = _findIndex(self.connections, connection);
  850. if (idx >= 0) {
  851. var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
  852. self.connections.splice(idx, 1);
  853. t.detach(connection);
  854. }
  855. };
  856. /**
  857. * detaches all connections this Endpoint has
  858. */
  859. this.detachAll = function() {
  860. while(self.connections.length > 0) {
  861. self.detach(self.connections[0]);
  862. }
  863. };
  864. /**
  865. * removes any connections from this Endpoint that are
  866. * connected to the given target endpoint.
  867. * @param targetEndpoint
  868. */
  869. this.detachFrom = function(targetEndpoint) {
  870. var c = [];
  871. for (var i = 0; i < self.connections.length; i++) {
  872. if (self.connections[i].endpoints[1] == targetEndpoint || self.connections[i].endpoints[0] == targetEndpoint) {
  873. c.push(self.connections[i]);
  874. }
  875. }
  876. for (var i = 0; i < c.length; i++) {
  877. targetEndpoint.detach(c[i]);
  878. self.detach(c[i]);
  879. }
  880. };
  881. /**
  882. * returns the DOM element this Endpoint is attached to.
  883. */
  884. this.getElement = function() { return _element; };
  885. /**
  886. * returns the UUID for this Endpoint, if there is one.
  887. */
  888. this.getUuid= function() { return _uuid; };
  889. /**
  890. * private but must be exposed.
  891. */
  892. this.makeInPlaceCopy = function() {
  893. var e = new Endpoint({anchor:self.anchor, source:_element, style:_style, endpoint:_endpoint});
  894. return e;
  895. };
  896. /**
  897. * returns whether or not this endpoint is connected to the given endpoint.
  898. * @param endpoint Endpoint to test.
  899. * @since 1.1.1
  900. *
  901. * todo: needs testing. will this work if the endpoint passed in is the source?
  902. */
  903. this.isConnectedTo = function(endpoint) {
  904. var found = false;
  905. if (endpoint) {
  906. for (var i = 0; i < self.connections.length; i++) {
  907. if (self.connections[i].endpoints[1] == endpoint) {
  908. found = true;
  909. break;
  910. }
  911. }
  912. }
  913. return found;
  914. };
  915. /**
  916. * private but needs to be exposed.
  917. * @returns {Boolean}
  918. */
  919. this.isFloating = function() { return floatingEndpoint != null; };
  920. /**
  921. * first pass at default ConnectorSelector: returns the first connection, if we have any.
  922. * modified a little, 5/10/2010: now it only returns a connector if we have not got equal to or more than _maxConnector connectors
  923. * attached. otherwise it is assumed a new connector is ok. but note with this setup we can't select any other connection than the first
  924. * one. what if this could return a list? that implies everything should work with a list - dragging etc. could be nasty. could also
  925. * be cool.
  926. */
  927. var connectorSelector = function() {
  928. //return self.connections.length == 0 || self.connections.length < _maxConnections ? null : self.connections[0];
  929. if (self.connections.length < _maxConnections) return null;
  930. //else if (self.connections.length == _maxConnections) return false;
  931. else return self.connections[0];
  932. };
  933. /**
  934. * @returns whether or not the Endpoint can accept any more Connections.
  935. */
  936. this.isFull = function() { return _maxConnections < 1 ? false : (self.connections.length >= _maxConnections); };
  937. /**
  938. * sets whether or not connnctions can be dragged from this Endpoint once it is full. you would use
  939. * this in a UI in which you're going to provide some other way of breaking connections, if you need
  940. * to break them at all. this property is by default true; use it in conjunction with the 'reattach'
  941. * option on a connect call.
  942. */
  943. this.setDragAllowedWhenFull = function(allowed) {
  944. self.dragAllowedWhenFull = allowed;
  945. };
  946. /**
  947. * a deep equals check. everything must match, including the anchor, styles, everything.
  948. * TODO: finish Endpoint.equals
  949. */
  950. this.equals = function(endpoint) {
  951. return this.anchor.equals(endpoint.anchor) &&
  952. true;
  953. };
  954. /**
  955. * paints the Endpoint, recalculating offset and anchor positions if necessary.
  956. */
  957. this.paint = function(anchorPoint, connectorPaintStyle, canvas) {
  958. if (log) log.debug("Painting Endpoint with elementId [" + _elementId + "]; anchorPoint is [" + anchorPoint + "]");
  959. if (anchorPoint == null) {
  960. // do we always want to force a repaint here? i dont think so!
  961. var xy = offsets[_elementId];
  962. var wh = sizes[_elementId];
  963. if (xy == null || wh == null) {
  964. _updateOffset(_elementId);
  965. xy = offsets[_elementId];
  966. wh = sizes[_elementId];
  967. }
  968. anchorPoint = self.anchor.compute([xy.left, xy.top], wh, self);
  969. }
  970. _endpoint.paint(anchorPoint, self.anchor.getOrientation(), canvas || self.canvas, _style, connectorPaintStyle || _style);
  971. };
  972. /**
  973. * @deprecated
  974. */
  975. this.removeConnection = this.detach; // backwards compatibility
  976. // is this a connection source? we make it draggable and have the drag listener
  977. // maintain a connection with a floating endpoint.
  978. if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  979. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  980. // first the question is, how many connections are on this endpoint? if it's only one, then excellent. otherwise we will either need a way
  981. // to select one connection from the list, or drag them all. if we had a pluggable 'ConnectorSelector' interface we could probably
  982. // provide a way for people to implement their own UI components to do the connector selection. the question in that particular case would be how much
  983. // information the interface needs from jsPlumb at execution time. if, however, we leave out the connector selection, and drag them all,
  984. // that wouldn't be too hard to organise. perhaps that behaviour would be on a switch for the endpoint, or perhaps the ConnectorSelector
  985. // interface returns a List, with the default implementation just returning everything. i think i like that.
  986. //
  987. // let's say for now that there is just one endpoint, cos we need to get this going before we can consider a list of them anyway.
  988. // the major difference between that case and the case of a new endpoint is actually quite small - it's a question of where the
  989. // Connection comes from. for a new one, we create a new one. obviously. otherwise we just get the jpc from the Endpoint
  990. // (remember we're only assuming one connection right now). so all of the UI stuff we do to create the floating endpoint etc
  991. // will still be valid, but when we stop dragging, we'll have to do something different. if we stop with a valid drop i think it will
  992. // be the same process. but if we stop with an invalid drop we have to reset the Connection to how it was when we got it.
  993. var start = function() {
  994. jpc = connectorSelector();
  995. if (self.isFull() && !self.dragAllowedWhenFull) return false;
  996. _updateOffset(_elementId);
  997. inPlaceCopy = self.makeInPlaceCopy();
  998. inPlaceCopy.paint();
  999. n = document.createElement("div");
  1000. var nE = _getElementObject(n);
  1001. _appendElement(n, self.container); //
  1002. // create and assign an id, and initialize the offset.
  1003. //TODO can't this be replaced with a _getId call?
  1004. var id = "" + new String(new Date().getTime());
  1005. _setAttribute(nE, "id", id);
  1006. _updateOffset(id);
  1007. // store the id of the dragging div and the source element. the drop function
  1008. // will pick these up.
  1009. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  1010. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  1011. // create a floating anchor
  1012. var floatingAnchor = new FloatingAnchor({reference:self.anchor, referenceCanvas:self.canvas});
  1013. floatingEndpoint = new Endpoint({ style:{fillStyle:'rgba(0,0,0,0)'}, endpoint:_endpoint, anchor:floatingAnchor, source:nE });
  1014. if (jpc == null) {
  1015. self.anchor.locked = true;
  1016. // create a connection. one end is this endpoint, the other is a floating endpoint.
  1017. jpc = new Connection({
  1018. sourceEndpoint:self,
  1019. targetEndpoint:floatingEndpoint,
  1020. source:_getElementObject(_element),
  1021. target:_getElementObject(n),
  1022. anchors:[self.anchor, floatingAnchor],
  1023. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  1024. connector: params.connector
  1025. });
  1026. } else {
  1027. existingJpc = true;
  1028. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1;
  1029. jpc.floatingAnchorIndex = anchorIdx;
  1030. // probably we should remove the connection? and add it back if the user
  1031. // does not drop it somewhere proper.
  1032. self.removeConnection(jpc);
  1033. if (anchorIdx == 0){
  1034. existingJpcParams = [jpc.source, jpc.sourceId];
  1035. jpc.source = _getElementObject(n);
  1036. jpc.sourceId = id;
  1037. }else {
  1038. existingJpcParams = [jpc.target, jpc.targetId];
  1039. jpc.target = _getElementObject(n);
  1040. jpc.targetId = id;
  1041. }
  1042. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
  1043. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  1044. jpc.endpoints[anchorIdx] = floatingEndpoint;
  1045. }
  1046. // register it.
  1047. floatingConnections[id] = jpc;
  1048. // todo unregister on stop
  1049. floatingEndpoint.addConnection(jpc);
  1050. // only register for the target endpoint; we will not be dragging the source at any time
  1051. // before this connection is either discarded or made into a permanent connection.
  1052. _addToList(endpointsByElement, id, floatingEndpoint);
  1053. };
  1054. var dragOptions = params.dragOptions || { };
  1055. var defaultOpts = jsPlumb.extend({}, jsPlumb.CurrentLibrary.defaultDragOptions);
  1056. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  1057. dragOptions.scope = dragOptions.scope || self.scope;
  1058. var startEvent = jsPlumb.CurrentLibrary.dragEvents['start'];
  1059. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  1060. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  1061. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  1062. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() {
  1063. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  1064. //$(n).offset(_ui);
  1065. jsPlumb.CurrentLibrary.setOffset(n, _ui);
  1066. _draw(_getElementObject(n), _ui);
  1067. });
  1068. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  1069. function() {
  1070. _removeFromList(endpointsByElement, id, floatingEndpoint);
  1071. _removeElements([n, floatingEndpoint.canvas], _element); // TODO: clean up the connection canvas (if the user aborted)
  1072. _removeElement(inPlaceCopy.canvas, _element);
  1073. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  1074. jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
  1075. if (jpc.endpoints[idx] == floatingEndpoint) {
  1076. // if the connection was an existing one:
  1077. if (existingJpc && jpc.suspendedEndpoint) {
  1078. if (_reattach) {
  1079. jpc.floatingAnchorIndex = null;
  1080. if (idx == 0) {
  1081. jpc.source = existingJpcParams[0];
  1082. jpc.sourceId = existingJpcParams[1];
  1083. } else {
  1084. jpc.target = existingJpcParams[0];
  1085. jpc.targetId = existingJpcParams[1];
  1086. }
  1087. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  1088. jpc.suspendedEndpoint.addConnection(jpc);
  1089. jsPlumb.repaint(existingJpcParams[1]);
  1090. }
  1091. else {
  1092. jpc.endpoints[0].removeConnection(jpc);
  1093. jpc.endpoints[1].removeConnection(jpc);
  1094. _removeElement(jpc.canvas, self.container);
  1095. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1096. _fireEvent("jsPlumbConnectionDetached", {
  1097. source:jpc.source,
  1098. target:jpc.target,
  1099. sourceId:jpc.sourceId,
  1100. targetId:jpc.targetId,
  1101. sourceEndpoint:jpc.endpoints[0],
  1102. targetEndpoint:jpc.endpoints[1]
  1103. });
  1104. }
  1105. } else {
  1106. _removeElement(jpc.canvas, self.container);
  1107. //if (jpc.endpoints[1]) alert("target set");
  1108. self.removeConnection(jpc);
  1109. }
  1110. }
  1111. self.anchor.locked = false;
  1112. jpc = null;
  1113. delete floatingEndpoint;
  1114. delete inPlaceCopy;
  1115. self.paint();
  1116. }
  1117. );
  1118. var i = _getElementObject(self.canvas);
  1119. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
  1120. };
  1121. // connector target
  1122. if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  1123. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  1124. dropOptions = jsPlumb.extend({}, dropOptions);
  1125. dropOptions.scope = dropOptions.scope || self.scope;
  1126. var originalAnchor = null;
  1127. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
  1128. var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
  1129. var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
  1130. dropOptions[dropEvent]= _wrap(dropOptions[dropEvent], function() {
  1131. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  1132. var id = _getAttribute(_getElementObject(draggable), "dragId");
  1133. var elId = _getAttribute(_getElementObject(draggable),"elId");
  1134. var jpc = floatingConnections[id];
  1135. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  1136. var oidx = idx == 0 ? 1 : 0;
  1137. if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
  1138. if (idx == 0) {
  1139. jpc.source = _element;
  1140. jpc.sourceId = _elementId;
  1141. } else {
  1142. jpc.target = _element;
  1143. jpc.targetId = _elementId;
  1144. }
  1145. //todo test that the target is not full.
  1146. // remove this jpc from the current endpoint
  1147. jpc.endpoints[idx].removeConnection(jpc);
  1148. if (jpc.suspendedEndpoint)
  1149. jpc.suspendedEndpoint.removeConnection(jpc);
  1150. jpc.endpoints[idx] = self;
  1151. self.addConnection(jpc);
  1152. // add the jpc to the other endpoint too.
  1153. jpc.endpoints[oidx].addConnection(jpc);
  1154. _addToList(connectionsByScope, jpc.scope, jpc);
  1155. _initDraggableIfNecessary(_element, params.draggable, {});
  1156. jsPlumb.repaint(elId);
  1157. _fireEvent("jsPlumbConnection", {
  1158. source:jpc.source,
  1159. target:jpc.target,
  1160. sourceId:jpc.sourceId,
  1161. targetId:jpc.targetId,
  1162. sourceEndpoint:jpc.endpoints[0],
  1163. targetEndpoint:jpc.endpoints[1]
  1164. });
  1165. }
  1166. // else there must be some cleanup required.
  1167. delete floatingConnections[id];
  1168. });
  1169. dropOptions[overEvent]= _wrap(dropOptions[overEvent], function() {
  1170. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  1171. var id = _getAttribute(_getElementObject(draggable),"dragId");
  1172. var jpc = floatingConnections[id];
  1173. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  1174. jpc.endpoints[idx].anchor.over(self.anchor);
  1175. });
  1176. dropOptions[outEvent] = _wrap(dropOptions[outEvent], function() {
  1177. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  1178. var id = _getAttribute(_getElementObject(draggable),"dragId");
  1179. var jpc = floatingConnections[id];
  1180. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  1181. jpc.endpoints[idx].anchor.out();
  1182. });
  1183. jsPlumb.CurrentLibrary.initDroppable(_getElementObject(self.canvas), dropOptions);
  1184. }
  1185. return self;
  1186. };
  1187. /*
  1188. Property: Defaults
  1189. These are the default settings for jsPlumb, that is what will be used if you do not supply specific pieces of information
  1190. to the various API calls. A convenient way to implement your own look and feel can be to override these defaults by including a script
  1191. somewhere after the jsPlumb include, but before you make any calls to jsPlumb, for instance in this example we set the PaintStyle to be
  1192. a blue line of 27 pixels:
  1193. > jsPlumb.Defaults.PaintStyle = { lineWidth:27, strokeStyle:'blue' }
  1194. */
  1195. this.Defaults = {
  1196. Anchor : null,
  1197. Anchors : [ null, null ],
  1198. BackgroundPaintStyle : null ,
  1199. Connector : null,
  1200. Container : null,
  1201. DragOptions: { },
  1202. DropOptions: { },
  1203. Endpoint : null,
  1204. Endpoints : [ null, null ],
  1205. EndpointStyle : { fillStyle : null },
  1206. EndpointStyles : [ null, null ],
  1207. LabelStyle : { fillStyle:"rgba(0,0,0,0)", color:"black" },
  1208. MaxConnections : null,
  1209. // TODO: should we have OverlayStyle too?
  1210. PaintStyle : { lineWidth : 10, strokeStyle : 'red' },
  1211. Scope : "_jsPlumb_DefaultScope"
  1212. };
  1213. /*
  1214. Property: connectorClass
  1215. The CSS class to set on Connection canvas elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  1216. */
  1217. this.connectorClass = '_jsPlumb_connector';
  1218. /*
  1219. Property: endpointClass
  1220. The CSS class to set on Endpoint canvas elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  1221. */
  1222. this.endpointClass = '_jsPlumb_endpoint';
  1223. /*
  1224. Property: Anchors
  1225. Default jsPlumb Anchors. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  1226. to form <library>.jsPlumb-all-x.x.x.js. You can provide your own Anchors by supplying them in a script that is loaded after jsPlumb, for instance:
  1227. > jsPlumb.Anchors.MyAnchor = { ....anchor code here. see the documentation. }
  1228. */
  1229. this.Anchors = {};
  1230. /*
  1231. Property: Connectors
  1232. Default jsPlumb Connectors. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  1233. to form <library>.jsPlumb-all-x.x.x.js. You can provide your own Connectors by supplying them in a script that is loaded after jsPlumb, for instance:
  1234. > jsPlumb.Connectors.MyConnector = { ....connector code here. see the documentation. }
  1235. */
  1236. this.Connectors = {};
  1237. /*
  1238. Property: Endpoints
  1239. Default jsPlumb Endpoints. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  1240. to form <library>.jsPlumb-all-x.x.x.js. You can provide your own Endpoints by supplying them in a script that is loaded after jsPlumb, for instance:
  1241. > jsPlumb.Endpoints.MyEndpoint = { ....endpoint code here. see the documentation. }
  1242. */
  1243. this.Endpoints = {};
  1244. /*
  1245. Property:Overlays
  1246. Default jsPlumb Overlays such as Arrows and Labels. These are supplied in the file jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  1247. to form <library>.jsPlumb-all-x.x.x.js. You can provide your own Overlays by supplying them in a script that is loaded after jsPlumb, for instance:
  1248. > jsPlumb.Overlays.MyOverlay = { ....overlay code here. see the documentation. }
  1249. */
  1250. this.Overlays = {};
  1251. /*
  1252. Function: addEndpoint
  1253. Adds an Endpoint to a given element.
  1254. Parameters:
  1255. target - Element to add the endpoint to. either an element id, or a selector representing some element.
  1256. params - Object containing Endpoint options (more info required)
  1257. Returns:
  1258. The newly created Endpoint.
  1259. See Also:
  1260. <addEndpoints>
  1261. */
  1262. this.addEndpoint = function(target, params) {
  1263. params = jsPlumb.extend({}, params);
  1264. var el = _getElementObject(target);
  1265. var id = _getAttribute(el,"id");
  1266. params.source = el;
  1267. _updateOffset(id);
  1268. var e = new Endpoint(params);
  1269. _addToList(endpointsByElement, id, e);
  1270. var myOffset = offsets[id];
  1271. var myWH = sizes[id];
  1272. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH, e);
  1273. e.paint(anchorLoc);
  1274. return e;
  1275. };
  1276. /*
  1277. Function: addEndpoint
  1278. Adds a list of Endpoints to a given element.
  1279. Parameters:
  1280. target - element to add the endpoint to. either an element id, or a selector representing some element.
  1281. endpoints - List of objects containing Endpoint options. one Endpoint is created for each entry in this list.
  1282. Returns:
  1283. List of newly created Endpoints, one for each entry in the 'endpoints' argument.
  1284. See Also:
  1285. <addEndpoint>
  1286. */
  1287. this.addEndpoints = function(target, endpoints) {
  1288. var results = [];
  1289. for (var i = 0; i < endpoints.length; i++) {
  1290. results.push(_currentInstance.addEndpoint(target, endpoints[i]));
  1291. }
  1292. return results;
  1293. };
  1294. /*
  1295. Function: animate
  1296. Wrapper around supporting library's animate function; injects a call to jsPlumb in the 'step' function (creating it if necessary).
  1297. This only supports the two-arg version of the animate call in jQuery - the one that takes an 'options' object as the second arg.
  1298. MooTools has only one method - a two arg one. Which is handy.
  1299. Parameters:
  1300. el - Element to animate. Either an id, or a selector representing the element.
  1301. properties - The 'properties' argument you want passed to the standard jQuery animate call.
  1302. options - The 'options' argument you want passed to the standard jQuery animate call.
  1303. Returns:
  1304. void
  1305. */
  1306. this.animate = function(el, properties, options) {
  1307. var ele = _getElementObject(el);
  1308. var id = _getAttribute(el,"id");
  1309. //TODO this is not agnostic yet.
  1310. options = options || {};
  1311. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  1312. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  1313. options[stepFunction] = _wrap(options[stepFunction], function()
  1314. {
  1315. _currentInstance.repaint(id);
  1316. });
  1317. // you know, probably onComplete should repaint too. that will help keep up
  1318. // with fast animations.
  1319. options[completeFunction] = _wrap(options[completeFunction], function()
  1320. {
  1321. _currentInstance.repaint(id);
  1322. });
  1323. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  1324. };
  1325. /**
  1326. * clears the cache used to lookup elements by their id. if you remove any elements
  1327. * from the DOM you should call this to ensure that if you add them back in jsPlumb does not
  1328. * have a stale handle.
  1329. */
  1330. this.clearCache = function() {
  1331. delete cached;
  1332. cached = {};
  1333. };
  1334. this.autoConnect = function(params/*source, target, anchors, endpoint*/) {
  1335. var sources = [], targets = [], _endpoint = params.endpoint || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle, _anchors = anchors || _currentInstance.Defaults.DynamicAnchors || jsPlumb.Defaults.DynamicAnchors;
  1336. var _addAll = function(s, t) {
  1337. for (var i = 0 ; i < s.length; i++) t.push(s[i]);
  1338. };
  1339. var source = params.source, target = params.target, anchors = params.anchors;
  1340. if (typeof source == 'string')
  1341. sources.push(_getElementObject(source));
  1342. else
  1343. _addAll(source, sources);
  1344. if (typeof target == 'string')
  1345. targets.push(_getElementObject(target));
  1346. else
  1347. _addAll(target, targets);
  1348. var connectOptions = jsPlumb.extend(params, {source:null,target:null,anchors:null});
  1349. for (var i = 0; i < sources.length; i++) {
  1350. for (var j = 0; j < targets.length; j++) {
  1351. var e1 = jsPlumb.addEndpoint(sources[i], jsPlumb.extend({ anchor:jsPlumb.makeDynamicAnchor(_anchors) }, _endpoint));
  1352. var e2 = jsPlumb.addEndpoint(targets[j], jsPlumb.extend({ anchor:jsPlumb.makeDynamicAnchor(_anchors) }, _endpoint));
  1353. _currentInstance.connect(jsPlumb.extend(connectOptions, { sourceEndpoint:e1, targetEndpoint:e2 }));
  1354. }
  1355. }
  1356. };
  1357. /*
  1358. Function: connect
  1359. Establishes a connection between two elements.
  1360. Parameters:
  1361. params - Object containing setup for the connection. see documentation.
  1362. Returns:
  1363. The newly created Connection.
  1364. */
  1365. this.connect = function(params) {
  1366. var _p = jsPlumb.extend({}, params);
  1367. // test for endpoint uuids to connect
  1368. if (params.uuids) {
  1369. var _resolveByUuid = function(idx) {
  1370. var e = _getEndpoint(params.uuids[idx]);
  1371. if (!e) throw ("Endpoint with UUID " + params.uuids[idx] + " not found.");
  1372. return e;
  1373. };
  1374. _p.sourceEndpoint = _resolveByUuid(0);
  1375. _p.targetEndpoint = _resolveByUuid(1);
  1376. }
  1377. // now ensure that if we do have Endpoints already, they're not full.
  1378. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  1379. _log("could not add connection; source endpoint is full");
  1380. return;
  1381. }
  1382. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  1383. _log("could not add connection; target endpoint is full");
  1384. return;
  1385. }
  1386. var jpc = new Connection(_p);
  1387. // add to list of connections (by scope).
  1388. _addToList(connectionsByScope, jpc.scope, jpc);
  1389. // fire an event
  1390. _fireEvent("jsPlumbConnection", {
  1391. source:jpc.source,
  1392. target:jpc.target,
  1393. sourceId:jpc.sourceId,
  1394. targetId:jpc.targetId,
  1395. sourceEndpoint:jpc.endpoints[0],
  1396. targetEndpoint:jpc.endpoints[1]
  1397. });
  1398. // force a paint
  1399. _draw(jpc.source);
  1400. return jpc;
  1401. };
  1402. var fireDetachEvent = function(jpc) {
  1403. _fireEvent("jsPlumbConnectionDetached", {
  1404. source:jpc.source,
  1405. target:jpc.target,
  1406. sourceId:jpc.sourceId,
  1407. targetId:jpc.targetId,
  1408. sourceEndpoint:jpc.endpoints[0],
  1409. targetEndpoint:jpc.endpoints[1]
  1410. });
  1411. };
  1412. /*
  1413. Function: detach
  1414. Removes a connection.
  1415. Parameters:
  1416. sourceId - Id of the first element in the connection. A String.
  1417. targetId - iI of the second element in the connection. A String.
  1418. Returns:
  1419. true if successful, false if not.
  1420. */
  1421. this.detach = function(sourceId, targetId) {
  1422. if (arguments.length == 2) {
  1423. var f = function(jpc) {
  1424. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  1425. _removeElement(jpc.canvas, jpc.container);
  1426. jpc.endpoints[0].removeConnection(jpc);
  1427. jpc.endpoints[1].removeConnection(jpc);
  1428. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1429. fireDetachEvent(jpc);
  1430. return true;
  1431. }
  1432. };
  1433. // todo: how to cleanup the actual storage? a third arg to _operation?
  1434. _operation(sourceId, f);
  1435. }
  1436. // this is the new version of the method, taking a JS object like the connect method does.
  1437. else if (arguments.length == 1) {
  1438. var _p = jsPlumb.extend({}, sourceId); // a backwards compatibility hack: sourceId should be thought of as 'params' in this case.
  1439. // test for endpoint uuids to detach
  1440. if (_p.uuids) {
  1441. _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]));
  1442. }
  1443. else if (_p.sourceEndpoint && _p.targetEndpoint) {
  1444. _p.sourceEndpoint.detachFrom(_p.targetEndpoint);
  1445. }
  1446. else {
  1447. sourceId = _getId(_p.source);
  1448. targetId = _getId(_p.target);
  1449. var f = function(jpc) {
  1450. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  1451. _removeElement(jpc.canvas, jpc.container);
  1452. jpc.endpoints[0].removeConnection(jpc);
  1453. jpc.endpoints[1].removeConnection(jpc);
  1454. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1455. fireDetachEvent(jpc);
  1456. return true;
  1457. }
  1458. };
  1459. // todo: how to cleanup the actual storage? a third arg to _operation?
  1460. _operation(sourceId, f);
  1461. }
  1462. // fire an event
  1463. /*_fireEvent("jsPlumbDetach", {
  1464. source:jpc.source,
  1465. target:jpc.target,
  1466. sourceId:jpc.sourceId,
  1467. targetId:jpc.targetId,
  1468. sourceEndpoint:jpc.endpoints[0],
  1469. targetEndpoint:jpc.endpoints[1]
  1470. });*/
  1471. /*// force a paint
  1472. _draw(jpc.source);
  1473. return jpc;*/
  1474. }
  1475. };
  1476. /*
  1477. Function: detachAll
  1478. Removes all an element's connections.
  1479. Parameters:
  1480. el - either the id of the element, or a selector for the element.
  1481. Returns:
  1482. void
  1483. */
  1484. this.detachAll = function(el) {
  1485. var id = _getAttribute(el, "id");
  1486. var endpoints = endpointsByElement[id];
  1487. if (endpoints && endpoints.length) {
  1488. for (var i = 0; i < endpoints.length; i++) {
  1489. var c = endpoints[i].connections.length;
  1490. if (c > 0) {
  1491. for (var j = 0; j < c; j++) {
  1492. var jpc = endpoints[i].connections[0];
  1493. _removeElement(jpc.canvas, jpc.container);
  1494. jpc.endpoints[0].removeConnection(jpc);
  1495. jpc.endpoints[1].removeConnection(jpc);
  1496. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1497. fireDetachEvent(jpc);
  1498. }
  1499. }
  1500. }
  1501. }
  1502. };
  1503. /*
  1504. Function: detachEverything
  1505. Remove all Connections from all elements, but leaves Endpoints in place.
  1506. Returns:
  1507. void
  1508. See Also:
  1509. <removeEveryEndpoint>
  1510. */
  1511. this.detachEverything = function() {
  1512. for(var id in endpointsByElement) {
  1513. var endpoints = endpointsByElement[id];
  1514. if (endpoints && endpoints.length) {
  1515. for (var i = 0; i < endpoints.length; i++) {
  1516. var c = endpoints[i].connections.length;
  1517. if (c > 0) {
  1518. for (var j = 0; j < c; j++) {
  1519. var jpc = endpoints[i].connections[0];
  1520. _removeElement(jpc.canvas, jpc.container);
  1521. jpc.endpoints[0].removeConnection(jpc);
  1522. jpc.endpoints[1].removeConnection(jpc);
  1523. fireDetachEvent(jpc);
  1524. }
  1525. }
  1526. }
  1527. }
  1528. }
  1529. delete connectionsByScope;
  1530. connectionsByScope = {};
  1531. };
  1532. /*
  1533. Function: draggable
  1534. initialises the draggability of some element or elements.
  1535. Parameters:
  1536. el - either an element id, a list of element ids, or a selector.
  1537. options - options to pass through to the underlying library
  1538. Returns:
  1539. void
  1540. */
  1541. this.draggable = function(el, options) {
  1542. if (typeof el == 'object' && el.length) {
  1543. for (var i = 0; i < el.length; i++)
  1544. {
  1545. var ele = _getElementObject(el[i]);
  1546. if (ele) _initDraggableIfNecessary(ele, true, options);
  1547. }
  1548. }
  1549. else {
  1550. var ele = _getElementObject(el);
  1551. if (ele)
  1552. _initDraggableIfNecessary(ele, true, options);
  1553. }
  1554. };
  1555. /*
  1556. Function: extend
  1557. Wraps the underlying library's extend functionality.
  1558. Parameters:
  1559. o1 - object to extend
  1560. o2 - object to extend o1 with
  1561. Returns:
  1562. o1, extended with all properties from o2.
  1563. */
  1564. this.extend = function(o1, o2) {
  1565. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1566. };
  1567. /*
  1568. Function: getConnections
  1569. Gets all or a subset of connections currently managed by this jsPlumb instance.
  1570. Parameters:
  1571. options - a JS object that holds options defining what sort of connections you're looking for. Valid values are:
  1572. scope this may be a String or a list of Strings. jsPlumb will only return Connections whose scope matches what this option
  1573. defines. If you omit it, you will be given Connections of every scope.
  1574. source may be a string or a list of strings; constraints results to have only Connections whose source is this object.
  1575. target may be a string or a list of strings; constraints results to have only Connections whose target is this object.
  1576. The return value is a dictionary in this format:
  1577. {
  1578. 'scope1': [
  1579. {sourceId:'window1', targetId:'window2'},
  1580. {sourceId:'window3', targetId:'window4'},
  1581. {sourceId:'window1', targetId:'window3'}
  1582. ],
  1583. 'scope2': [
  1584. {sourceId:'window1', targetId:'window3'}
  1585. ]
  1586. }
  1587. */
  1588. this.getConnections = function(options) {
  1589. var r = {};
  1590. options = options || {};
  1591. var prepareList = function(input) {
  1592. var r = [];
  1593. if (input) {
  1594. if (typeof input == 'string') r.push(input);
  1595. else r = input;
  1596. }
  1597. return r;
  1598. };
  1599. var scopes = prepareList(options.scope);
  1600. var sources = prepareList(options.source);
  1601. var targets = prepareList(options.target);
  1602. var filter = function(list, value) {
  1603. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1604. };
  1605. for (var i in connectionsByScope) {
  1606. if (filter(scopes, i)) {
  1607. r[i] = [];
  1608. for (var j = 0; j < connectionsByScope[i].length; j++) {
  1609. var c = connectionsByScope[i][j];
  1610. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1611. r[i].push({
  1612. sourceId:c.sourceId,
  1613. targetId:c.targetId,
  1614. source:c.source,
  1615. target:c.target,
  1616. sourceEndpoint:c.endpoints[0],
  1617. targetEndpoint:c.endpoints[1]
  1618. });
  1619. }
  1620. }
  1621. }
  1622. return r;
  1623. };
  1624. /*
  1625. Function: getDefaultScope
  1626. Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a scope to an endpoint
  1627. or connection allows you to support different types of connections in the same UI. but if you're only interested in one type of connection,
  1628. you don't need to supply a scope. this method will probably be used by very few people; it's good for testing though.
  1629. */
  1630. this.getDefaultScope = function() {
  1631. return DEFAULT_SCOPE;
  1632. };
  1633. /*
  1634. Function: getEndpoint
  1635. gets an Endpoint by UUID
  1636. Parameters:
  1637. uuid - the UUID for the Endpoint
  1638. Returns:
  1639. Endpoint with the given UUID, null if nothing found.
  1640. */
  1641. this.getEndpoint = _getEndpoint;
  1642. /*
  1643. * gets an element's id, creating one if necessary. really only exposed for the lib-specific
  1644. * functionality to access; would be better to pass the current instance into the lib-specific
  1645. * code (even though this is a static call. i just don't want to expose it to the public API).
  1646. */
  1647. this.getId = _getId;
  1648. /*
  1649. Function: hide
  1650. Sets an element's connections to be hidden.
  1651. Parameters:
  1652. el - either the id of the element, or a selector for the element.
  1653. Returns:
  1654. void
  1655. */
  1656. this.hide = function(el) {
  1657. _setVisible(el, "none");
  1658. };
  1659. /*
  1660. Function: makeAnchor
  1661. Creates an anchor with the given params.
  1662. Parameters:
  1663. x - the x location of the anchor as a fraction of the total width.
  1664. y - the y location of the anchor as a fraction of the total height.
  1665. xOrientation - value indicating the general direction a connection from the anchor should go in, in the x direction.
  1666. yOrientation - value indicating the general direction a connection from the anchor should go in, in the y direction.
  1667. xOffset - a fixed offset that should be applied in the x direction that should be applied after the x position has been figured out. optional. defaults to 0.
  1668. yOffset - a fixed offset that should be applied in the y direction that should be applied after the y position has been figured out. optional. defaults to 0.
  1669. Returns:
  1670. The newly created Anchor.
  1671. */
  1672. this.makeAnchor = function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1673. // backwards compatibility here. we used to require an object passed in but that makes the call very verbose. easier to use
  1674. // by just passing in four/six values. but for backwards compatibility if we are given only one value we assume it's a call in the old form.
  1675. var params = {};
  1676. if (arguments.length == 1) jsPlumb.extend(params, x);
  1677. else {
  1678. params = {x:x, y:y};
  1679. if (arguments.length >= 4) {
  1680. params.orientation = [arguments[2], arguments[3]];
  1681. }
  1682. if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
  1683. }
  1684. var a = new Anchor(params);
  1685. a.clone = function() { return new Anchor(params); };
  1686. return a;
  1687. };
  1688. this.makeDynamicAnchor = function(anchors) {
  1689. return new DynamicAnchor(anchors);
  1690. };
  1691. /*
  1692. Function: repaint
  1693. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1694. Parameters:
  1695. el - either the id of the element or a selector representing the element.
  1696. Returns:
  1697. void
  1698. See Also:
  1699. <repaintEverything>
  1700. */
  1701. this.repaint = function(el) {
  1702. var _processElement = function(el) {
  1703. var ele = _getElementObject(el);
  1704. _draw(ele);
  1705. };
  1706. // TODO: support a jQuery result object too!
  1707. // support both lists...
  1708. if (typeof el =='object') {
  1709. for (var i = 0; i < el.length; i++)
  1710. _processElement(el[i]);
  1711. } // ...and single strings.
  1712. else _processElement(el);
  1713. };
  1714. /*
  1715. Function: repaintEverything
  1716. Repaints all connections.
  1717. Returns:
  1718. void
  1719. See Also:
  1720. <repaint>
  1721. */
  1722. this.repaintEverything = function() {
  1723. for (var elId in endpointsByElement) {
  1724. _draw(_getElementObject(elId));
  1725. }
  1726. };
  1727. /*
  1728. Function: removeAllEndpoints
  1729. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1730. Parameters:
  1731. el - either an element id, or a selector for an element.
  1732. Returns:
  1733. void
  1734. See Also:
  1735. <removeEndpoint>
  1736. */
  1737. this.removeAllEndpoints = function(el) {
  1738. var elId = _getAttribute(el, "id");
  1739. // first remove all Connections.
  1740. jsPlumb.detachAll(elId);
  1741. var ebe = endpointsByElement[elId];
  1742. for (var i in ebe) {
  1743. _removeElement(ebe[i].canvas, ebe[i].getElement());
  1744. }
  1745. endpointsByElement[elId] = [];
  1746. };
  1747. /*
  1748. Function: removeEveryEndpoint
  1749. Removes every Endpoint in this instance of jsPlumb.
  1750. Returns:
  1751. void
  1752. See Also:
  1753. <removeAllEndpoints> <removeEndpoint>
  1754. */
  1755. this.removeEveryEndpoint = function() {
  1756. for(var id in endpointsByElement) {
  1757. var endpoints = endpointsByElement[id];
  1758. if (endpoints && endpoints.length) {
  1759. for (var i = 0; i < endpoints.length; i++) {
  1760. _removeElement(endpoints[i].canvas, endpoints[i].container);
  1761. }
  1762. }
  1763. }
  1764. delete endpointsByElement;
  1765. endpointsByElement = {};
  1766. };
  1767. /*
  1768. Function: removeEndpoint
  1769. Removes the given Endpoint from the given element.
  1770. Parameters:
  1771. el - either an element id, or a selector for an element.
  1772. endpoint - Endpoint to remove. this is an Endpoint object, such as would have been returned from a call to addEndpoint.
  1773. Returns:
  1774. void
  1775. See Also:
  1776. <removeAllEndpoints> <removeEveryEndpoint>
  1777. */
  1778. this.removeEndpoint = function(el, endpoint) {
  1779. var elId = _getAttribute(el, "id");
  1780. var ebe = endpointsByElement[elId];
  1781. if (ebe) {
  1782. if(_removeFromList(endpointsByElement, elId, endpoint))
  1783. _removeElement(endpoint.canvas, endpoint.getElement());
  1784. }
  1785. };
  1786. /*
  1787. Function:reset
  1788. removes all endpoints and connections and clears the element cache.
  1789. */
  1790. this.reset = function() {
  1791. this.detachEverything();
  1792. this.removeEveryEndpoint();
  1793. this.clearCache();
  1794. };
  1795. /*
  1796. Function: setAutomaticRepaint
  1797. Sets/unsets automatic repaint on window resize.
  1798. Parameters:
  1799. value - whether or not to automatically repaint when the window is resized.
  1800. Returns:
  1801. void
  1802. */
  1803. this.setAutomaticRepaint = function(value) {
  1804. automaticRepaint = value;
  1805. };
  1806. /*
  1807. Function: setDefaultNewCanvasSize
  1808. Sets the default size jsPlumb will use for a new canvas (we create a square canvas so one value is all that is required).
  1809. This is a hack for IE, because ExplorerCanvas seems to need for a canvas to be larger than what you are going to draw on
  1810. it at initialisation time. The default value of this is 1200 pixels, which is quite large, but if for some reason you're
  1811. drawing connectors that are bigger, you should adjust this value appropriately.
  1812. Parameters:
  1813. size - The default size to use. jsPlumb will use a square canvas so you need only supply one value.
  1814. Returns:
  1815. void
  1816. */
  1817. this.setDefaultNewCanvasSize = function(size) {
  1818. DEFAULT_NEW_CANVAS_SIZE = size;
  1819. };
  1820. /*
  1821. Function: setDefaultScope
  1822. Sets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a scope to an endpoint
  1823. or connection allows you to support different types of connections in the same UI. but if you're only interested in one type of connection,
  1824. you don't need to supply a scope. this method will probably be used by very few people; it just instructs jsPlumb to use a different key
  1825. for the default scope.
  1826. */
  1827. this.setDefaultScope = function(scope) {
  1828. DEFAULT_SCOPE = scope;
  1829. };
  1830. /*
  1831. Function: setDraggable
  1832. Sets whether or not a given element is draggable, regardless of what any plumb command may request.
  1833. Parameters:
  1834. el - either the id for the element, or a selector representing the element.
  1835. Returns:
  1836. void
  1837. */
  1838. this.setDraggable = _setDraggable;
  1839. /*
  1840. Function: setDraggableByDefault
  1841. Sets whether or not elements are draggable by default. Default for this is true.
  1842. Parameters:
  1843. draggable - value to set
  1844. Returns:
  1845. void
  1846. */
  1847. this.setDraggableByDefault = function(draggable) {
  1848. _draggableByDefault = draggable;
  1849. };
  1850. this.setDebugLog = function(debugLog) {
  1851. log = debugLog;
  1852. };
  1853. /*
  1854. Function: setRepaintFunction
  1855. Sets the function to fire when the window size has changed and a repaint was fired.
  1856. Parameters:
  1857. f - Function to execute.
  1858. Returns:
  1859. void
  1860. */
  1861. this.setRepaintFunction = function(f) {
  1862. repaintFunction = f;
  1863. };
  1864. /*
  1865. Function: show
  1866. Sets an element's connections to be visible.
  1867. Parameters:
  1868. el - either the id of the element, or a selector for the element.
  1869. Returns:
  1870. void
  1871. */
  1872. this.show = function(el) {
  1873. _setVisible(el, "block");
  1874. };
  1875. /*
  1876. Function: sizeCanvas
  1877. Helper to size a canvas. You would typically use this when writing your own Connector or Endpoint implementation.
  1878. Parameters:
  1879. x - [int] x position for the Canvas origin
  1880. y - [int] y position for the Canvas origin
  1881. w - [int] width of the canvas
  1882. h - [int] height of the canvas
  1883. Returns:
  1884. void
  1885. */
  1886. this.sizeCanvas = function(canvas, x, y, w, h) {
  1887. if (canvas) {
  1888. canvas.style.height = h + "px"; canvas.height = h;
  1889. canvas.style.width = w + "px"; canvas.width = w;
  1890. canvas.style.left = x + "px"; canvas.style.top = y + "px";
  1891. // _currentInstance.CurrentLibrary.setPosition(canvas, x, y);
  1892. }
  1893. };
  1894. /**
  1895. * gets some test hooks. nothing writable.
  1896. */
  1897. this.getTestHarness = function() {
  1898. return {
  1899. endpointCount : function(elId) {
  1900. var e = endpointsByElement[elId];
  1901. return e ? e.length : 0;
  1902. },
  1903. connectionCount : function(scope) {
  1904. scope = scope || DEFAULT_SCOPE;
  1905. var c = connectionsByScope[scope];
  1906. return c ? c.length : 0;
  1907. },
  1908. findIndex : _findIndex,
  1909. getId : _getId
  1910. };
  1911. };
  1912. /**
  1913. * Toggles visibility of an element's connections. kept for backwards compatibility
  1914. */
  1915. this.toggle = _toggleVisible;
  1916. /*
  1917. Function: toggleVisible
  1918. Toggles visibility of an element's connections.
  1919. Parameters:
  1920. el - either the element's id, or a selector representing the element.
  1921. Returns:
  1922. void, but should be updated to return the current state
  1923. */
  1924. //TODO: update this method to return the current state.
  1925. this.toggleVisible = _toggleVisible;
  1926. /*
  1927. Function: toggleDraggable
  1928. Toggles draggability (sic) of an element's connections.
  1929. Parameters:
  1930. el - either the element's id, or a selector representing the element.
  1931. Returns:
  1932. The current draggable state.
  1933. */
  1934. this.toggleDraggable = _toggleDraggable;
  1935. /*
  1936. Function: unload
  1937. Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element
  1938. Returns:
  1939. void
  1940. */
  1941. this.unload = function() {
  1942. delete endpointsByElement;
  1943. delete offsets;
  1944. delete sizes;
  1945. delete floatingConnections;
  1946. delete draggableStates;
  1947. };
  1948. /*
  1949. Function: wrap
  1950. Helper method to wrap an existing function with one of your own. This is used by the various
  1951. implementations to wrap event callbacks for drag/drop etc; it allows jsPlumb to be
  1952. transparent in its handling of these things. If a user supplies their own event callback,
  1953. for anything, it will always be called.
  1954. Parameters:
  1955. */
  1956. this.wrap = _wrap;
  1957. this.addListener = _addListener;
  1958. };
  1959. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  1960. jsPlumb.getInstance = function(_defaults) {
  1961. var j = new jsPlumbInstance();
  1962. if (_defaults)
  1963. jsPlumb.extend(j.Defaults, _defaults);
  1964. return j;
  1965. };
  1966. })();
  1967. /*
  1968. * jsPlumb-defaults-1.2.3-RC1
  1969. *
  1970. * This script contains the default Anchors, Endpoints, Connectors and Overlays for jsPlumb. It should be used with jsPlumb 1.1.0 and above;
  1971. * prior to version 1.1.0 of jsPlumb the defaults were included inside the main script.
  1972. *
  1973. * NOTE: for production usage you should use jsPlumb-all-x.x.x-min.js, which contains the main jsPlumb script and this script together,
  1974. * in a minified file.
  1975. *
  1976. * Dual licensed under MIT and GPL2.
  1977. */
  1978. (function() {
  1979. /**
  1980. * Places you can anchor a connection to. These are helpers for common locations; they all just return an instance
  1981. * of Anchor that has been configured appropriately.
  1982. *
  1983. * You can write your own one of these; you
  1984. * just need to provide a 'compute' method and an 'orientation'. so you'd say something like this:
  1985. *
  1986. * jsPlumb.Anchors.MY_ANCHOR = {
  1987. * compute : function(xy, wh, txy, twh) { return some mathematics on those variables; },
  1988. * getOrientation : function() { return [ox, oy]; }
  1989. * };
  1990. *
  1991. * compute takes the [x,y] position of the top left corner of the anchored element,
  1992. * and the element's [width,height] (all in pixels), as well as the location and dimension of the element it's plumbed to,
  1993. * and returns where the anchor should be located.
  1994. *
  1995. * the 'orientation' array (returned here as [ox,oy]) indicates the general direction a connection from the anchor
  1996. * should go in, if possible. it is an [x,y] matrix where a value of 0 means no preference,
  1997. * -1 means go in a negative direction for the given axis, and 1 means go in a positive
  1998. * direction. so consider a TopCenter anchor: the orientation matrix for it is [0,-1],
  1999. * meaning connections naturally want to go upwards on screen. in a Bezier implementation, for example,
  2000. * the curve would start out going in that direction, before bending towards the target anchor.
  2001. */
  2002. jsPlumb.Anchors.TopCenter = jsPlumb.makeAnchor(0.5, 0, 0,-1);
  2003. jsPlumb.Anchors.BottomCenter = jsPlumb.makeAnchor(0.5, 1, 0, 1);
  2004. jsPlumb.Anchors.LeftMiddle = jsPlumb.makeAnchor(0, 0.5, -1, 0);
  2005. jsPlumb.Anchors.RightMiddle = jsPlumb.makeAnchor(1, 0.5, 1, 0);
  2006. jsPlumb.Anchors.Center = jsPlumb.makeAnchor(0.5, 0.5, 0, 0);
  2007. jsPlumb.Anchors.TopRight = jsPlumb.makeAnchor(1, 0, 0,-1);
  2008. jsPlumb.Anchors.BottomRight = jsPlumb.makeAnchor(1, 1, 0, 1);
  2009. jsPlumb.Anchors.TopLeft = jsPlumb.makeAnchor(0, 0, 0, -1);
  2010. jsPlumb.Anchors.BottomLeft = jsPlumb.makeAnchor(0, 1, 0, 1);
  2011. jsPlumb.Anchors.AutoDefault = function() { return jsPlumb.makeDynamicAnchor([jsPlumb.Anchors.TopCenter, jsPlumb.Anchors.RightMiddle, jsPlumb.Anchors.BottomCenter, jsPlumb.Anchors.LeftMiddle]); };
  2012. jsPlumb.Defaults.DynamicAnchors = [jsPlumb.Anchors.TopCenter, jsPlumb.Anchors.RightMiddle, jsPlumb.Anchors.BottomCenter, jsPlumb.Anchors.LeftMiddle];
  2013. /**
  2014. * The Straight connector draws a simple straight line between the two anchor points.
  2015. */
  2016. jsPlumb.Connectors.Straight = function() {
  2017. var self = this;
  2018. var currentPoints = null;
  2019. var _m, _m2, _b, _dx, _dy, _theta, _theta2, _sx, _sy, _tx, _ty;
  2020. /**
  2021. * Computes the new size and position of the canvas.
  2022. * @param sourceAnchor Absolute position on screen of the source object's anchor.
  2023. * @param targetAnchor Absolute position on screen of the target object's anchor.
  2024. * @param positionMatrix Indicates the relative positions of the left,top of the
  2025. * two plumbed objects. so [0,0] indicates that the source is to the left of, and
  2026. * above, the target. [1,0] means the source is to the right and above. [0,1] means
  2027. * the source is to the left and below. [1,1] means the source is to the right
  2028. * and below. this is used to figure out which direction to draw the connector in.
  2029. * @returns an array of positioning information. the first two values are
  2030. * the [left, top] absolute position the canvas should be placed on screen. the
  2031. * next two values are the [width,height] the canvas should be. after that each
  2032. * Connector can put whatever it likes into the array:it will be passed back in
  2033. * to the paint call. This particular function stores the origin and destination of
  2034. * the line it is going to draw. a more involved implementation, like a Bezier curve,
  2035. * would store the control point info in this array too.
  2036. */
  2037. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  2038. var w = Math.abs(sourcePos[0] - targetPos[0]);
  2039. var h = Math.abs(sourcePos[1] - targetPos[1]);
  2040. var widthAdjusted = false, heightAdjusted = false;
  2041. // these are padding to ensure the whole connector line appears
  2042. var xo = 0.45 * w, yo = 0.45 * h;
  2043. // these are padding to ensure the whole connector line appears
  2044. w *= 1.9; h *=1.9;
  2045. var x = Math.min(sourcePos[0], targetPos[0]) - xo;
  2046. var y = Math.min(sourcePos[1], targetPos[1]) - yo;
  2047. // minimum size is 2 * line Width if minWidth was not given.
  2048. var calculatedMinWidth = Math.max(2 * lineWidth, minWidth);
  2049. if (w < calculatedMinWidth) {
  2050. w = calculatedMinWidth;
  2051. x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - (calculatedMinWidth / 2);
  2052. xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;
  2053. }
  2054. if (h < calculatedMinWidth) {
  2055. h = calculatedMinWidth;
  2056. y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - (calculatedMinWidth / 2);
  2057. yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;
  2058. }
  2059. _sx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  2060. _sy = sourcePos[1] < targetPos[1] ? yo:h-yo;
  2061. _tx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  2062. _ty = sourcePos[1] < targetPos[1] ? h-yo : yo;
  2063. currentPoints = [ x, y, w, h, _sx, _sy, _tx, _ty ];
  2064. _dx = _tx - _sx, _dy = (_ty - _sy);
  2065. _m = _dy / _dx, _m2 = -1 / _m;
  2066. _b = -1 * ((_m * _sx) - _sy);
  2067. _theta = Math.atan(_m); _theta2 = Math.atan(_m2);
  2068. return currentPoints;
  2069. };
  2070. this.paint = function(dimensions, ctx)
  2071. {
  2072. ctx.beginPath();
  2073. ctx.moveTo(dimensions[4], dimensions[5]);
  2074. ctx.lineTo(dimensions[6], dimensions[7]);
  2075. ctx.stroke();
  2076. };
  2077. /**
  2078. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  2079. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  2080. */
  2081. this.pointOnPath = function(location) {
  2082. var xp = _sx + (location * _dx);
  2083. var yp = _m == Infinity ? xp + _b : (_m * xp) + _b;
  2084. return [xp, yp];
  2085. };
  2086. /**
  2087. * returns the gradient of the connector at the given point - which for us is constant.
  2088. */
  2089. this.gradientAtPoint = function(location) { return _m; };
  2090. /**
  2091. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  2092. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
  2093. */
  2094. this.pointAlongPathFrom = function(location, distance) {
  2095. var p = self.pointOnPath(location);
  2096. var orientation = distance > 0 ? 1 : -1;
  2097. var y = Math.abs(distance * Math.sin(_theta));
  2098. if (_sy > _ty) y = y * -1;
  2099. var x = Math.abs(distance * Math.cos(_theta));
  2100. if (_sx > _tx) x = x * -1;
  2101. return [p[0] + (orientation * x), p[1] + (orientation * y)];
  2102. };
  2103. /**
  2104. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  2105. * the line is 'length' pixels long.
  2106. */
  2107. this.perpendicularToPathAt = function(location, distance, length) {
  2108. var p = self.pointAlongPathFrom(location, distance);
  2109. var m = self.gradientAtPoint(p.location);
  2110. var _theta2 = Math.atan(-1 / m);
  2111. var y = length / 2 * Math.sin(_theta2);
  2112. var x = length / 2 * Math.cos(_theta2);
  2113. return [[p[0] + x, p[1] + y], [p[0] - x, p[1] - y]];
  2114. };
  2115. this.createGradient = function(dim, ctx) {
  2116. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  2117. };
  2118. };
  2119. /**
  2120. * This Connector draws a Bezier curve with two control points.
  2121. * @param curviness How 'curvy' you want the curve to be! This is a directive for the
  2122. * placement of control points, not endpoints of the curve, so your curve does not
  2123. * actually touch the given point, but it has the tendency to lean towards it. the larger
  2124. * this value, the greater the curve is pulled from a straight line.
  2125. *
  2126. * a future implementation of this could take the control points as arguments, rather
  2127. * than fixing the curve to one basic shape.
  2128. */
  2129. jsPlumb.Connectors.Bezier = function(curviness) {
  2130. var self = this;
  2131. this.majorAnchor = curviness || 150;
  2132. this.minorAnchor = 10;
  2133. var currentPoints = null;
  2134. this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
  2135. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  2136. // points around if so (code could be tightened up)
  2137. var soo = sourceAnchor.getOrientation(), too = targetAnchor.getOrientation();
  2138. var perpendicular = soo[0] != too[0] || soo[1] == too[1];
  2139. var p = [];
  2140. var ma = self.majorAnchor, mi = self.minorAnchor;
  2141. if (!perpendicular) {
  2142. if (soo[0] == 0) // X
  2143. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  2144. else p.push(point[0] - (ma * soo[0]));
  2145. if (soo[1] == 0) // Y
  2146. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  2147. else p.push(point[1] + (ma * too[1]));
  2148. }
  2149. else {
  2150. if (too[0] == 0) // X
  2151. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  2152. else p.push(point[0] + (ma * too[0]));
  2153. if (too[1] == 0) // Y
  2154. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  2155. else p.push(point[1] + (ma * soo[1]));
  2156. }
  2157. return p;
  2158. };
  2159. var _CP, _CP2, _sx, _tx, _sx, _sy, _canvasX, _canvasY, _w, _h;
  2160. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth)
  2161. {
  2162. lineWidth = lineWidth || 0;
  2163. _w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth;
  2164. _h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  2165. _canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2);
  2166. _canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  2167. _sx = sourcePos[0] < targetPos[0] ? _w - (lineWidth/2): (lineWidth/2);
  2168. _sy = sourcePos[1] < targetPos[1] ? _h - (lineWidth/2) : (lineWidth/2);
  2169. _tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : _w - (lineWidth/2);
  2170. _ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : _h - (lineWidth/2);
  2171. _CP = self._findControlPoint([_sx,_sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
  2172. _CP2 = self._findControlPoint([_tx,_ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
  2173. var minx1 = Math.min(_sx,_tx); var minx2 = Math.min(_CP[0], _CP2[0]); var minx = Math.min(minx1,minx2);
  2174. var maxx1 = Math.max(_sx,_tx); var maxx2 = Math.max(_CP[0], _CP2[0]); var maxx = Math.max(maxx1,maxx2);
  2175. if (maxx > _w) _w = maxx;
  2176. if (minx < 0) {
  2177. _canvasX += minx; var ox = Math.abs(minx);
  2178. _w += ox; _CP[0] += ox; _sx += ox; _tx +=ox; _CP2[0] += ox;
  2179. }
  2180. var miny1 = Math.min(_sy,_ty); var miny2 = Math.min(_CP[1], _CP2[1]); var miny = Math.min(miny1,miny2);
  2181. var maxy1 = Math.max(_sy,_ty); var maxy2 = Math.max(_CP[1], _CP2[1]); var maxy = Math.max(maxy1,maxy2);
  2182. if (maxy > _h) _h = maxy;
  2183. if (miny < 0) {
  2184. _canvasY += miny; var oy = Math.abs(miny);
  2185. _h += oy; _CP[1] += oy; _sy += oy; _ty +=oy; _CP2[1] += oy;
  2186. }
  2187. if (minWidth && _w < minWidth) {
  2188. var posAdjust = (minWidth - _w) / 2;
  2189. _w = minWidth;
  2190. _canvasX -= posAdjust; _sx = _sx + posAdjust ; _tx = _tx + posAdjust; _CP[0] = _CP[0] + posAdjust; _CP2[0] = _CP2[0] + posAdjust;
  2191. }
  2192. currentPoints = [_canvasX, _canvasY, _w, _h, _sx, _sy, _tx, _ty, _CP[0], _CP[1], _CP2[0], _CP2[1] ];
  2193. return currentPoints;
  2194. };
  2195. this.paint = function(d, ctx) {
  2196. ctx.beginPath();
  2197. ctx.moveTo(d[4],d[5]);
  2198. ctx.bezierCurveTo(d[8],d[9],d[10],d[11],d[6],d[7]);
  2199. ctx.stroke();
  2200. };
  2201. /**
  2202. * returns the distance the given point is from the curve. not enabled for 1.2.3. didnt make the cut. next time.
  2203. *
  2204. this.distanceFrom = function(point) {
  2205. var curve = [ {x:currentPoints[4], y:currentPoints[5]},
  2206. {x:currentPoints[8], y:currentPoints[9]},
  2207. {x:currentPoints[10], y:currentPoints[11]},
  2208. {x:currentPoints[6], y:currentPoints[7]}];
  2209. return (jsPlumb.DistanceFromCurve(point, curve));
  2210. };*/
  2211. var _quadraticPointOnPath = function(location) {
  2212. function B1(t) { return t*t; };
  2213. function B2(t) { return 2*t*(1-t); };
  2214. function B3(t) { return (1-t)*(1-t); };
  2215. var x = _sx*B1(location) + _CP[0]*B2(location) + _CP2[0]*B3(location);
  2216. var y = _sy*B1(location) + _CP[1]*B2(location) + _CP2[1]*B3(location);
  2217. return [x,y];
  2218. };
  2219. /**
  2220. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  2221. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  2222. */
  2223. this.pointOnPath = function(location) {
  2224. // from http://13thparallel.com/archive/bezier-curves/
  2225. function B1(t) { return t*t*t };
  2226. function B2(t) { return 3*t*t*(1-t) };
  2227. function B3(t) { return 3*t*(1-t)*(1-t) };
  2228. function B4(t) { return (1-t)*(1-t)*(1-t) };
  2229. var x = _sx*B1(location) + _CP[0]*B2(location) + _CP2[0]*B3(location) + _tx*B4(location);
  2230. var y = _sy*B1(location) + _CP[1]*B2(location) + _CP2[1]*B3(location) + _ty*B4(location);
  2231. return [x,y];
  2232. };
  2233. /**
  2234. * returns the gradient of the connector at the given point.
  2235. */
  2236. this.gradientAtPoint = function(location) {
  2237. var p1 = self.pointOnPath(location);
  2238. var p2 = _quadraticPointOnPath(location);
  2239. var dy = p2[1] - p1[1], dx = p2[0] - p1[0];
  2240. var rtn = Math.atan(dy / dx) ;
  2241. // http://bimixual.org/AnimationLibrary/beziertangents.html
  2242. return rtn;
  2243. };
  2244. /**
  2245. * finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also
  2246. * its 'location' (proportion of travel along the path).
  2247. */
  2248. var _pointAlongPath = function(location, distance) {
  2249. var _dist = function(p1,p2) { return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2)); };
  2250. var prev = self.pointOnPath(location), tally = 0, curLoc = location, direction = distance > 0 ? 1 : -1, cur = null;
  2251. while (tally < Math.abs(distance)) {
  2252. curLoc += (0.005 * direction);
  2253. cur = self.pointOnPath(curLoc);
  2254. tally += _dist(cur, prev);
  2255. prev = cur;
  2256. }
  2257. return {point:cur, location:curLoc};
  2258. };
  2259. /**
  2260. * for Bezier curves this method is a little tricky, cos calculating path distance algebraically is notoriously difficult.
  2261. * this method is iterative, jumping forward .05% of the path at a time and summing the distance between this point and the previous
  2262. * one, until the sum reaches 'distance'. the method may turn out to be computationally expensive; we'll see.
  2263. * another drawback of this method is that if the connector gets quite long, .05% of the length of it is not necessarily smaller
  2264. * than the desired distance, in which case the loop returns immediately and the arrow is mis-shapen. so a better strategy might be to
  2265. * calculate the step as a function of distance/distance between endpoints.
  2266. */
  2267. this.pointAlongPathFrom = function(location, distance) {
  2268. return _pointAlongPath(location, distance).point;
  2269. };
  2270. /**
  2271. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  2272. * the line is 'length' pixels long.
  2273. */
  2274. this.perpendicularToPathAt = function(location, distance, length) {
  2275. var p = _pointAlongPath(location, distance);
  2276. var m = self.gradientAtPoint(p.location);
  2277. var _theta2 = Math.atan(-1 / m);
  2278. var y = length / 2 * Math.sin(_theta2);
  2279. var x = length / 2 * Math.cos(_theta2);
  2280. return [[p.point[0] + x, p.point[1] + y], [p.point[0] - x, p.point[1] - y]];
  2281. };
  2282. this.createGradient = function(dim, ctx, swap) {
  2283. return (swap) ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  2284. };
  2285. };
  2286. /**
  2287. * Types of endpoint UIs. we supply four - a circle of default radius 10px, a rectangle of
  2288. * default size 20x20, an image (with no default), and a Triangle, of default size 15.
  2289. * you can supply others of these if you want to - see the documentation for a howto.
  2290. */
  2291. /**
  2292. * a round endpoint, with default radius 10 pixels.
  2293. */
  2294. jsPlumb.Endpoints.Dot = function(params) {
  2295. params = params || { radius:10 };
  2296. var self = this;
  2297. this.radius = params.radius;
  2298. var defaultOffset = 0.5 * this.radius;
  2299. var defaultInnerRadius = this.radius / 3;
  2300. var parseValue = function(value) {
  2301. try {
  2302. return parseInt(value);
  2303. }
  2304. catch(e) {
  2305. if (value.substring(value.length - 1) == '%')
  2306. return parseInt(value.substring(0, value - 1));
  2307. }
  2308. }
  2309. var calculateAdjustments = function(gradient) {
  2310. var offsetAdjustment = defaultOffset;
  2311. var innerRadius = defaultInnerRadius;
  2312. if (gradient.offset) offsetAdjustment = parseValue(gradient.offset);
  2313. if(gradient.innerRadius) innerRadius = parseValue(gradient.innerRadius);
  2314. return [offsetAdjustment, innerRadius];
  2315. };
  2316. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  2317. var radius = endpointStyle.radius || self.radius;
  2318. var x = anchorPoint[0] - radius;
  2319. var y = anchorPoint[1] - radius;
  2320. jsPlumb.sizeCanvas(canvas, x, y, radius * 2, radius * 2);
  2321. var ctx = canvas.getContext('2d');
  2322. var style = jsPlumb.extend({}, endpointStyle);
  2323. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  2324. jsPlumb.extend(ctx, style);
  2325. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  2326. if (endpointStyle.gradient && !ie) {
  2327. var adjustments = calculateAdjustments(endpointStyle.gradient);
  2328. var yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0];
  2329. var xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0];
  2330. var g = ctx.createRadialGradient(radius, radius, radius, radius + xAdjust, radius + yAdjust, adjustments[1]);
  2331. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  2332. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  2333. ctx.fillStyle = g;
  2334. }
  2335. ctx.beginPath();
  2336. ctx.arc(radius, radius, radius, 0, Math.PI*2, true);
  2337. ctx.closePath();
  2338. ctx.fill();
  2339. };
  2340. };
  2341. /**
  2342. * A Rectangular endpoint, with default size 20x20.
  2343. */
  2344. jsPlumb.Endpoints.Rectangle = function(params) {
  2345. params = params || { width:20, height:20 };
  2346. var self = this;
  2347. this.width = params.width;
  2348. this.height = params.height;
  2349. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  2350. var width = endpointStyle.width || self.width;
  2351. var height = endpointStyle.height || self.height;
  2352. var x = anchorPoint[0] - (width/2);
  2353. var y = anchorPoint[1] - (height/2);
  2354. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  2355. var ctx = canvas.getContext('2d');
  2356. var style = jsPlumb.extend({}, endpointStyle);
  2357. if (style.fillStyle == null) style.fillStyle = connectorPaintStyle.strokeStyle;
  2358. jsPlumb.extend(ctx, style);
  2359. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  2360. if (endpointStyle.gradient && !ie) {
  2361. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  2362. var y1 = orientation[1] == 1 ? height : orientation[1] == 0 ? height / 2 : 0;
  2363. var y2 = orientation[1] == -1 ? height : orientation[1] == 0 ? height / 2 : 0;
  2364. var x1 = orientation[0] == 1 ? width : orientation[0] == 0 ? width / 2 : 0;
  2365. var x2 = orientation[0] == -1 ? width : orientation[0] == 0 ? height / 2 : 0;
  2366. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  2367. for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
  2368. g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
  2369. ctx.fillStyle = g;
  2370. }
  2371. ctx.beginPath();
  2372. ctx.rect(0, 0, width, height);
  2373. ctx.closePath();
  2374. ctx.fill();
  2375. };
  2376. };
  2377. jsPlumb.Endpoints.Triangle = function(params) {
  2378. params = params || { width:15, height:15 };
  2379. var self = this;
  2380. this.width = params.width;
  2381. this.height = params.height;
  2382. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
  2383. {
  2384. var width = endpointStyle.width || self.width;
  2385. var height = endpointStyle.height || self.height;
  2386. var x = anchorPoint[0] - width/2;
  2387. var y = anchorPoint[1] - height/2;
  2388. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  2389. var ctx = canvas.getContext('2d');
  2390. var offsetX = 0, offsetY = 0, angle = 0;
  2391. if( orientation[0] == 1 )
  2392. {
  2393. offsetX = width;
  2394. offsetY = height;
  2395. angle = 180;
  2396. }
  2397. if( orientation[1] == -1 )
  2398. {
  2399. offsetX = width;
  2400. angle = 90;
  2401. }
  2402. if( orientation[1] == 1 )
  2403. {
  2404. offsetY = height;
  2405. angle = -90;
  2406. }
  2407. ctx.fillStyle = endpointStyle.fillStyle;
  2408. ctx.translate(offsetX, offsetY);
  2409. ctx.rotate(angle * Math.PI/180);
  2410. ctx.beginPath();
  2411. ctx.moveTo(0, 0);
  2412. ctx.lineTo(width/2, height/2);
  2413. ctx.lineTo(0, height);
  2414. ctx.closePath();
  2415. ctx.fill();
  2416. };
  2417. };
  2418. /**
  2419. * Image endpoint - draws an image as the endpoint. You must provide a 'url' property in the params object..
  2420. */
  2421. jsPlumb.Endpoints.Image = function(params) {
  2422. var self = this;
  2423. this.img = new Image();
  2424. var ready = false;
  2425. this.img.onload = function() {
  2426. self.ready = true;
  2427. };
  2428. this.img.src = params.url;
  2429. var actuallyPaint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  2430. var width = self.img.width || endpointStyle.width;
  2431. var height = self.img.height || endpointStyle.height;
  2432. var x = anchorPoint[0] - (width/2);
  2433. var y = anchorPoint[1] - (height/2);
  2434. jsPlumb.sizeCanvas(canvas, x, y, width, height);
  2435. var ctx = canvas.getContext('2d');
  2436. ctx.drawImage(self.img,0,0);
  2437. };
  2438. this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
  2439. if (self.ready) {
  2440. actuallyPaint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
  2441. }
  2442. else
  2443. window.setTimeout(function() {
  2444. self.paint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle);
  2445. }, 200);
  2446. };
  2447. };
  2448. /**
  2449. * An arrow overlay. you can provide:
  2450. *
  2451. * length - distance in pixels from head to tail baseline. default 20.
  2452. * width - width in pixels of the tail baseline. default 20.
  2453. * fillStyle - style to use when filling the arrow. defaults to "black".
  2454. * strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
  2455. * lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null.
  2456. * foldback - distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
  2457. * location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
  2458. */
  2459. jsPlumb.Overlays.Arrow = function(params) {
  2460. params = params || {};
  2461. var self = this;
  2462. var length = params.length || 20;
  2463. var width = params.width || 20;
  2464. var fillStyle = params.fillStyle || "black";
  2465. var strokeStyle = params.strokeStyle;
  2466. var lineWidth = params.lineWidth || 1;
  2467. this.loc = params.location || 0.5;
  2468. // how far along the arrow the lines folding back in come to. default is 62.3%.
  2469. var foldback = params.foldback || 0.623;
  2470. var _getFoldBackPoint = function(connector, loc) {
  2471. if (foldback == 0.5) return connector.pointOnPath(loc);
  2472. else {
  2473. var adj = 0.5 - foldback; // we calculate relative to the center
  2474. return connector.pointAlongPathFrom(loc, length * adj);
  2475. }
  2476. };
  2477. this.computeMaxSize = function() { return width * 1.5; }
  2478. this.draw = function(connector, ctx) {
  2479. // this is the arrow head position
  2480. var hxy = connector.pointAlongPathFrom(self.loc, length / 2);
  2481. // this is the center of the tail
  2482. var txy = connector.pointAlongPathFrom(self.loc, -length / 2), tx = txy[0], ty = txy[1];
  2483. // this is the tail vector
  2484. var tail = connector.perpendicularToPathAt(self.loc, -length / 2, width);
  2485. // this is the point the tail goes in to
  2486. var cxy = _getFoldBackPoint(connector, self.loc);
  2487. ctx.lineWidth = lineWidth;
  2488. ctx.beginPath();
  2489. ctx.moveTo(hxy[0], hxy[1]);
  2490. ctx.lineTo(tail[0][0], tail[0][1]);
  2491. ctx.lineTo(cxy[0], cxy[1]);
  2492. ctx.lineTo(tail[1][0], tail[1][1]);
  2493. ctx.lineTo(hxy[0], hxy[1]);
  2494. ctx.closePath();
  2495. if (strokeStyle) {
  2496. ctx.strokeStyle = strokeStyle;
  2497. ctx.stroke();
  2498. }
  2499. ctx.fillStyle = fillStyle;
  2500. ctx.fill();
  2501. }
  2502. };
  2503. /**
  2504. * a basic arrow. this is in fact just one instance of the more generic case in which the tail folds back on itself to some
  2505. * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
  2506. * a 'call' to Arrow with foldback set appropriately. See Arrow for params.
  2507. */
  2508. jsPlumb.Overlays.PlainArrow = function(params) {
  2509. params = params || {};
  2510. var p = jsPlumb.extend(params, {foldback:1});
  2511. jsPlumb.Overlays.Arrow.call(this, p);
  2512. };
  2513. /**
  2514. * a diamond. like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
  2515. * happens that in this case, that point is greater than the length of the the arrow. See Arrow for params.
  2516. *
  2517. * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
  2518. * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
  2519. * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
  2520. * would be -l/4 in this case - move along one quarter of the total length.
  2521. */
  2522. jsPlumb.Overlays.Diamond = function(params) {
  2523. params = params || {};
  2524. var l = params.length || 40;
  2525. var p = jsPlumb.extend(params, {length:l/2, foldback:2});
  2526. jsPlumb.Overlays.Arrow.call(this, p);
  2527. };
  2528. /**
  2529. * A Label overlay. Params you can provide:
  2530. *
  2531. * labelStyle - js object containing style instructions for the label. defaults to jsPlumb.Defaults.LabelStyle.
  2532. * label - the label to paint. may be a string or a function that returns a string. nothing will be painted if your label is null or your
  2533. * label function returns null. empty strings _will_ be painted.
  2534. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  2535. * borderWidth - width of a border to paint. defaults to zero.
  2536. * borderStyle - strokeStyle to use when painting the border, if necessary.
  2537. */
  2538. jsPlumb.Overlays.Label = function(params) {
  2539. this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle;
  2540. this.label = params.label;
  2541. var self = this;
  2542. var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
  2543. this.location = params.location || 0.5;
  2544. this.computeMaxSize = function(connector, ctx) {
  2545. if (labelText) {
  2546. ctx.save();
  2547. if (self.labelStyle.font) ctx.font = self.labelStyle.font;
  2548. var t = ctx.measureText(labelText).width;
  2549. // a fake text height measurement: use the width of upper case M
  2550. var h = ctx.measureText("M").width;
  2551. labelPadding = self.labelStyle.padding || 0.25;
  2552. labelWidth = t + (2 * t * labelPadding);
  2553. labelHeight = h + (2 * h * labelPadding);
  2554. ctx.restore();
  2555. return Math.max(labelWidth, labelHeight) * 1.5;
  2556. }
  2557. return 0;
  2558. };
  2559. this.draw = function(connector, ctx) {
  2560. // we allow label generation by a function here. you get given the Connection object as an argument.
  2561. labelText = typeof self.label == 'function' ? self.label(self) : self.label;
  2562. if (labelText) {
  2563. if (self.labelStyle.font) ctx.font = self.labelStyle.font;
  2564. var t = ctx.measureText(labelText).width;
  2565. // a fake text height measurement: use the width of upper case M
  2566. var h = ctx.measureText("M").width;
  2567. labelPadding = self.labelStyle.padding || 0.25;
  2568. labelWidth = t + (2 * t * labelPadding);
  2569. labelHeight = h + (2 * h * labelPadding);
  2570. var cxy = connector.pointOnPath(self.location);
  2571. if (self.labelStyle.font) ctx.font = self.labelStyle.font;
  2572. if (self.labelStyle.fillStyle)
  2573. ctx.fillStyle = self.labelStyle.fillStyle;
  2574. else
  2575. ctx.fillStyle = "rgba(0,0,0,0)";
  2576. ctx.fillRect(cxy[0] - (labelWidth / 2), cxy[1] - (labelHeight / 2) , labelWidth , labelHeight );
  2577. if (self.labelStyle.color) ctx.fillStyle = self.labelStyle.color;
  2578. ctx.textBaseline = "middle";
  2579. ctx.textAlign = "center";
  2580. ctx.fillText(labelText, cxy[0], cxy[1]);
  2581. // border
  2582. if (self.labelStyle.borderWidth > 0) {
  2583. ctx.strokeStyle = self.labelStyle.borderStyle || "black";
  2584. ctx.strokeRect(cxy[0] - (labelWidth / 2), cxy[1] - (labelHeight / 2) , labelWidth , labelHeight );
  2585. }
  2586. }
  2587. };
  2588. };
  2589. })();/*
  2590. * mootools.jsPlumb 1.2.3-RC1
  2591. *
  2592. * MooTools specific functionality for jsPlumb.
  2593. *
  2594. * http://morrisonpitt.com/jsPlumb/demo.html
  2595. * http://code.google.com/p/jsPlumb
  2596. *
  2597. * NOTE: for production usage you should use mootools.jsPlumb-all-x.x.x-min.js, which contains the main jsPlumb script and this script together,
  2598. * in a minified file.
  2599. *
  2600. * Dual licensed under MIT and GPL2.
  2601. *
  2602. */
  2603. (function() {
  2604. /*
  2605. * overrides the FX class to inject 'step' functionality, which MooTools does not
  2606. * offer, and which makes me sad. they don't seem keen to add it, either, despite
  2607. * the fact that it could be useful:
  2608. *
  2609. * https://mootools.lighthouseapp.com/projects/2706/tickets/668
  2610. *
  2611. */
  2612. var jsPlumbMorph = new Class({
  2613. Extends:Fx.Morph,
  2614. onStep : null,
  2615. initialize : function(el, options) {
  2616. this.parent(el, options);
  2617. if (options['onStep']) {
  2618. this.onStep = options['onStep'];
  2619. }
  2620. },
  2621. step : function() {
  2622. this.parent();
  2623. if (this.onStep) {
  2624. try { this.onStep(); }
  2625. catch(e) { }
  2626. }
  2627. }
  2628. });
  2629. var _droppables = {};
  2630. var _droppableOptions = {};
  2631. var _draggablesByScope = {};
  2632. var _draggablesById = {};
  2633. /*
  2634. *
  2635. */
  2636. var _executeDroppableOption = function(el, dr, event) {
  2637. if (dr) {
  2638. var id = dr.get("id");
  2639. if (id) {
  2640. var options = _droppableOptions[id];
  2641. if (options) {
  2642. if (options[event]) {
  2643. options[event](el, dr);
  2644. }
  2645. }
  2646. }
  2647. }
  2648. };
  2649. var _checkHover = function(el, entering) {
  2650. if (el) {
  2651. var id = el.get("id");
  2652. if (id) {
  2653. var options = _droppableOptions[id];
  2654. if (options) {
  2655. if (options['hoverClass']) {
  2656. if (entering) el.addClass(options['hoverClass']);
  2657. else el.removeClass(options['hoverClass']);
  2658. }
  2659. }
  2660. }
  2661. }
  2662. };
  2663. /**
  2664. * adds the given value to the given list, with the given scope. creates the scoped list
  2665. * if necessary.
  2666. * used by initDraggable and initDroppable.
  2667. */
  2668. var _add = function(list, scope, value) {
  2669. var l = list[scope];
  2670. if (!l) {
  2671. l = [];
  2672. list[scope] = l;
  2673. }
  2674. l.push(value);
  2675. };
  2676. jsPlumb.CurrentLibrary = {
  2677. dragEvents : {
  2678. 'start':'onStart', 'stop':'onComplete', 'drag':'onDrag', 'step':'onStep',
  2679. 'over':'onEnter', 'out':'onLeave','drop':'onDrop', 'complete':'onComplete'
  2680. },
  2681. appendElement : function(child, parent) {
  2682. jsPlumb.CurrentLibrary.getElementObject(parent).grab(child);
  2683. },
  2684. bind : function(el, event, callback) {
  2685. el = jsPlumb.CurrentLibrary.getElementObject(el);
  2686. el.addEvent(event, callback);
  2687. },
  2688. /*
  2689. * wrapper around the library's 'extend' functionality (which it hopefully has.
  2690. * otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
  2691. * instead. it's not like its hard.
  2692. */
  2693. extend : function(o1, o2) {
  2694. return $extend(o1, o2);
  2695. },
  2696. /*
  2697. * gets an "element object" from the given input. this means an object that is used by the
  2698. * underlying library on which jsPlumb is running. 'el' may already be one of these objects,
  2699. * in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
  2700. * function is used to find the element, using the given String as the element's id.
  2701. */
  2702. getElementObject : function(el) {
  2703. return $(el);
  2704. },
  2705. /*
  2706. gets the offset for the element object. this should return a js object like this:
  2707. { left:xxx, top: xxx}
  2708. */
  2709. getOffset : function(el) {
  2710. var p = el.getPosition();
  2711. return { left:p.x, top:p.y };
  2712. },
  2713. setOffset : function(el, o) {
  2714. jsPlumb.CurrentLibrary.getElementObject(el).setPosition({x:o.left, y:o.top});
  2715. },
  2716. getSize : function(el) {
  2717. var s = el.getSize();
  2718. return [s.x, s.y];
  2719. },
  2720. /**
  2721. * gets the named attribute from the given element object.
  2722. */
  2723. getAttribute : function(el, attName) {
  2724. return el.get(attName);
  2725. },
  2726. /**
  2727. * sets the named attribute on the given element object.
  2728. */
  2729. setAttribute : function(el, attName, attValue) {
  2730. el.set(attName, attValue);
  2731. },
  2732. /**
  2733. * adds the given class to the element object.
  2734. */
  2735. addClass : function(el, clazz) {
  2736. el.addClass(clazz);
  2737. },
  2738. initDraggable : function(el, options) {
  2739. var id = jsPlumb.getId(el);
  2740. var drag = _draggablesById[id];
  2741. if (!drag) {
  2742. var originalZIndex = 0, originalCursor = null;
  2743. var dragZIndex = jsPlumb.Defaults.DragOptions.zIndex || 2000;
  2744. options['onStart'] = jsPlumb.wrap(options['onStart'], function()
  2745. {
  2746. originalZIndex = this.element.getStyle('z-index');
  2747. this.element.setStyle('z-index', dragZIndex);
  2748. if (jsPlumb.Defaults.DragOptions.cursor) {
  2749. originalCursor = this.element.getStyle('cursor');
  2750. this.element.setStyle('cursor', jsPlumb.Defaults.DragOptions.cursor);
  2751. }
  2752. });
  2753. options['onComplete'] = jsPlumb.wrap(options['onComplete'], function()
  2754. {
  2755. this.element.setStyle('z-index', originalZIndex);
  2756. if (originalCursor) {
  2757. this.element.setStyle('cursor', originalCursor);
  2758. }
  2759. });
  2760. // DROPPABLES:
  2761. var scope = options['scope'] || jsPlumb.Defaults.Scope;
  2762. var filterFunc = function(entry) {
  2763. return entry.get("id") != el.get("id");
  2764. };
  2765. var droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
  2766. options['droppables'] = droppables;
  2767. options['onLeave'] = jsPlumb.wrap(options['onLeave'], function(el, dr) {
  2768. if (dr) {
  2769. _checkHover(dr, false);
  2770. _executeDroppableOption(el, dr, 'onLeave');
  2771. }
  2772. });
  2773. options['onEnter'] = jsPlumb.wrap(options['onEnter'], function(el, dr) {
  2774. if (dr) {
  2775. _checkHover(dr, true);
  2776. _executeDroppableOption(el, dr, 'onEnter');
  2777. }
  2778. });
  2779. options['onDrop'] = function(el, dr) {
  2780. if (dr) {
  2781. _checkHover(dr, false);
  2782. _executeDroppableOption(el, dr, 'onDrop');
  2783. }
  2784. };
  2785. drag = new Drag.Move(el, options);
  2786. _add(_draggablesByScope, scope, drag);
  2787. _add(_draggablesById, el.get("id"), drag);
  2788. // test for disabled.
  2789. if (options.disabled) drag.detach();
  2790. }
  2791. return drag;
  2792. },
  2793. isDragSupported : function(el, options) {
  2794. return typeof Drag != 'undefined' ;
  2795. },
  2796. setDraggable : function(el, draggable) {
  2797. var draggables = _draggablesById[el.get("id")];
  2798. if (draggables) {
  2799. draggables.each(function(d) {
  2800. if (draggable) d.attach(); else d.detach();
  2801. });
  2802. }
  2803. },
  2804. initDroppable : function(el, options) {
  2805. var scope = options['scope'] || jsPlumb.Defaults.Scope;
  2806. _add(_droppables, scope, el);
  2807. var id = jsPlumb.getId(el);
  2808. _droppableOptions[id] = options;
  2809. var filterFunc = function(entry) {
  2810. return entry.element != el;
  2811. };
  2812. var draggables = _draggablesByScope[scope] ? _draggablesByScope[scope].filter(filterFunc) : [];
  2813. for (var i = 0; i < draggables.length; i++) {
  2814. draggables[i].droppables.push(el);
  2815. }
  2816. },
  2817. /*
  2818. * you need Drag.Move imported to make drop work.
  2819. */
  2820. isDropSupported : function(el, options) {
  2821. if (typeof Drag != undefined)
  2822. return typeof Drag.Move != undefined;
  2823. return false;
  2824. },
  2825. animate : function(el, properties, options) {
  2826. var m = new jsPlumbMorph(el, options);
  2827. m.start(properties);
  2828. },
  2829. /*
  2830. * takes the args passed to an event function and returns you an object that gives the
  2831. * position of the object being moved, as a js object with the same params as the result of
  2832. * getOffset, ie: { left: xxx, top: xxx }.
  2833. */
  2834. getUIPosition : function(eventArgs) {
  2835. var ui = eventArgs[0];
  2836. return { left: ui.offsetLeft, top: ui.offsetTop };
  2837. },
  2838. getDragObject : function(eventArgs) {
  2839. return eventArgs[0];
  2840. },
  2841. removeElement : function(element, parent) {
  2842. jsPlumb.CurrentLibrary.getElementObject(element).dispose(); // ??
  2843. },
  2844. getScrollLeft : function(el) {
  2845. return null;
  2846. },
  2847. getScrollTop : function(el) {
  2848. return null;
  2849. }
  2850. };
  2851. })();