yui.jsPlumb-1.2.5-all.js 139 KB

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