jquery.jsPlumb-1.2.6-all.js 164 KB

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