jsPlumb-1.3.5-RC1.js 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938
  1. /*
  2. * jsPlumb
  3. *
  4. * Title:jsPlumb 1.3.5
  5. *
  6. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  7. * elements, or VML.
  8. *
  9. * This file contains the jsPlumb core code.
  10. *
  11. * Copyright (c) 2010 - 2012 Simon Porritt (simon.porritt@gmail.com)
  12. *
  13. * http://jsplumb.org
  14. * http://github.com/sporritt/jsplumb
  15. * http://code.google.com/p/jsplumb
  16. *
  17. * Dual licensed under the MIT and GPL2 licenses.
  18. */
  19. ;(function() {
  20. /**
  21. * Class:jsPlumb
  22. * The jsPlumb engine, registered as a static object in the window. This object contains all of the methods you will use to
  23. * create and maintain Connections and Endpoints.
  24. */
  25. var canvasAvailable = !!document.createElement('canvas').getContext,
  26. svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"),
  27. // TODO what is a good test for VML availability? aside from just assuming its there because nothing else is.
  28. vmlAvailable = !(canvasAvailable | svgAvailable);
  29. // finds the index of some value in an array, using a deep equals test.
  30. var _findIndex = function(a, v, b, s) {
  31. var _eq = function(o1, o2) {
  32. if (o1 === o2) return true;
  33. else if (typeof o1 == "object" && typeof o2 == "object") {
  34. var same = true;
  35. for ( var propertyName in o1) {
  36. if (!_eq(o1[propertyName], o2[propertyName])) {
  37. same = false;
  38. break;
  39. }
  40. }
  41. for ( var propertyName in o2) {
  42. if (!_eq(o2[propertyName], o1[propertyName])) {
  43. same = false;
  44. break;
  45. }
  46. }
  47. return same;
  48. }
  49. };
  50. for ( var i = +b || 0, l = a.length; i < l; i++) {
  51. if (_eq(a[i], v))
  52. return i;
  53. }
  54. return -1;
  55. },
  56. _findWithFunction = function(a, f) {
  57. if (a)
  58. for (var i = 0; i < a.length; i++) if (f(a[i])) return i;
  59. return -1;
  60. },
  61. _removeWithFunction = function(a, f) {
  62. var idx = _findWithFunction(a, f);
  63. if (idx > -1) a.splice(idx, 1);
  64. return idx != -1;
  65. },
  66. // TODO support insert index
  67. _addWithFunction = function(list, item, hashFunction) {
  68. if (_findWithFunction(list, hashFunction) == -1) list.push(item);
  69. };
  70. // for those browsers that dont have it. they still don't have it! but at least they won't crash.
  71. if (!window.console)
  72. window.console = { time:function(){}, timeEnd:function(){}, group:function(){}, groupEnd:function(){}, log:function(){} };
  73. /**
  74. * helper method to add an item to a list, creating the list if it does
  75. * not yet exist.
  76. */
  77. var _addToList = function(map, key, value) {
  78. var l = map[key];
  79. if (l == null) {
  80. l = [], map[key] = l;
  81. }
  82. l.push(value);
  83. return l;
  84. },
  85. _connectionBeingDragged = null,
  86. _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); },
  87. _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); },
  88. _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); },
  89. _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
  90. _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); },
  91. _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
  92. _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
  93. _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); },
  94. _logEnabled = true,
  95. _log = function() {
  96. if (_logEnabled && typeof console != "undefined") {
  97. try {
  98. var msg = arguments[arguments.length - 1];
  99. console.log(msg);
  100. }
  101. catch (e) {}
  102. }
  103. },
  104. _group = function(g) {
  105. if (_logEnabled && typeof console != "undefined") console.group(g);
  106. },
  107. _groupEnd = function(g) {
  108. if (_logEnabled && typeof console != "undefined") console.groupEnd(g);
  109. },
  110. _time = function(t) {
  111. if (_logEnabled && typeof console != "undefined") console.time(t);
  112. },
  113. _timeEnd = function(t) {
  114. if (_logEnabled && typeof console != "undefined") console.timeEnd(t);
  115. };
  116. /**
  117. * EventGenerator
  118. * Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
  119. */
  120. EventGenerator = function() {
  121. var _listeners = {}, self = this;
  122. // this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to
  123. // jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
  124. // listeners to bring down jsPlumb - or do we. i can't make up my mind about this, but i know i want to hear about it if the "ready"
  125. // event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
  126. // to hear what other people think.
  127. var eventsToDieOn = [ "ready" ];
  128. /*
  129. * Binds a listener to an event.
  130. *
  131. * Parameters:
  132. * event - name of the event to bind to.
  133. * listener - function to execute.
  134. */
  135. this.bind = function(event, listener) {
  136. _addToList(_listeners, event, listener);
  137. };
  138. /*
  139. * Fires an update for the given event.
  140. *
  141. * Parameters:
  142. * event - event to fire
  143. * value - value to pass to the event listener(s).
  144. * originalEvent - the original event from the browser
  145. */
  146. this.fire = function(event, value, originalEvent) {
  147. if (_listeners[event]) {
  148. for ( var i = 0; i < _listeners[event].length; i++) {
  149. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  150. // method will have the whole call stack available in the debugger.
  151. if (_findIndex(eventsToDieOn, event) != -1)
  152. _listeners[event][i](value, originalEvent);
  153. else {
  154. // for events we don't want to die on, catch and log.
  155. try {
  156. _listeners[event][i](value, originalEvent);
  157. } catch (e) {
  158. _log("jsPlumb: fire failed for event " + event + " : " + e);
  159. }
  160. }
  161. }
  162. }
  163. };
  164. /*
  165. * Clears either all listeners, or listeners for some specific event.
  166. *
  167. * Parameters:
  168. * event - optional. constrains the clear to just listeners for this event.
  169. */
  170. this.clearListeners = function(event) {
  171. if (event)
  172. delete _listeners[event];
  173. else {
  174. delete _listeners;
  175. _listeners = {};
  176. }
  177. };
  178. this.getListener = function(forEvent) {
  179. return _listeners[forEvent];
  180. };
  181. },
  182. /**
  183. * creates a timestamp, using milliseconds since 1970, but as a string.
  184. */
  185. _timestamp = function() { return "" + (new Date()).getTime(); },
  186. /*
  187. * Class:jsPlumbUIComponent
  188. * Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle,
  189. * and also extends EventGenerator to provide the bind and fire methods.
  190. */
  191. jsPlumbUIComponent = function(params) {
  192. var self = this, a = arguments, _hover = false, parameters = params.parameters || {}, idPrefix = self.idPrefix,
  193. id = idPrefix + (new Date()).getTime();
  194. self._jsPlumb = params["_jsPlumb"];
  195. self.getId = function() { return id; };
  196. self.tooltip = params.tooltip;
  197. self.hoverClass = params.hoverClass;
  198. // all components can generate events
  199. EventGenerator.apply(this);
  200. // all components get this clone function.
  201. // TODO issue 116 showed a problem with this - it seems 'a' that is in
  202. // the clone function's scope is shared by all invocations of it, the classic
  203. // JS closure problem. for now, jsPlumb does a version of this inline where
  204. // it used to call clone. but it would be nice to find some time to look
  205. // further at this.
  206. this.clone = function() {
  207. var o = new Object();
  208. self.constructor.apply(o, a);
  209. return o;
  210. };
  211. this.getParameter = function(name) { return parameters[name]; },
  212. this.getParameters = function() { return parameters; },
  213. this.setParameter = function(name, value) { parameters[name] = value; },
  214. this.setParameters = function(p) { parameters = p; },
  215. this.overlayPlacements = [],
  216. this.paintStyle = null,
  217. this.hoverPaintStyle = null;
  218. // user can supply a beforeDetach callback, which will be executed before a detach
  219. // is performed; returning false prevents the detach.
  220. var beforeDetach = params.beforeDetach;
  221. this.isDetachAllowed = function(connection) {
  222. var r = true;
  223. if (beforeDetach) {
  224. try {
  225. r = beforeDetach(connection);
  226. }
  227. catch (e) { _log("jsPlumb: beforeDetach callback failed", e); }
  228. }
  229. return r;
  230. };
  231. // user can supply a beforeDrop callback, which will be executed before a dropped
  232. // connection is confirmed. user can return false to reject connection.
  233. var beforeDrop = params.beforeDrop;
  234. this.isDropAllowed = function(sourceId, targetId, scope) {
  235. var r = self._jsPlumb.checkCondition("beforeDrop", { sourceId:sourceId, targetId:targetId, scope:scope });
  236. if (beforeDrop) {
  237. try {
  238. r = beforeDrop({ sourceId:sourceId, targetId:targetId, scope:scope });
  239. }
  240. catch (e) { _log("jsPlumb: beforeDrop callback failed", e); }
  241. }
  242. return r;
  243. };
  244. // helper method to update the hover style whenever it, or paintStyle, changes.
  245. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  246. // top.
  247. var _updateHoverStyle = function() {
  248. if (self.paintStyle && self.hoverPaintStyle) {
  249. var mergedHoverStyle = {};
  250. jsPlumb.extend(mergedHoverStyle, self.paintStyle);
  251. jsPlumb.extend(mergedHoverStyle, self.hoverPaintStyle);
  252. delete self["hoverPaintStyle"];
  253. // we want the fillStyle of paintStyle to override a gradient, if possible.
  254. if (mergedHoverStyle.gradient && self.paintStyle.fillStyle)
  255. delete mergedHoverStyle["gradient"];
  256. self.hoverPaintStyle = mergedHoverStyle;
  257. }
  258. };
  259. /*
  260. * Sets the paint style and then repaints the element.
  261. *
  262. * Parameters:
  263. * style - Style to use.
  264. */
  265. this.setPaintStyle = function(style, doNotRepaint) {
  266. self.paintStyle = style;
  267. self.paintStyleInUse = self.paintStyle;
  268. _updateHoverStyle();
  269. if (!doNotRepaint) self.repaint();
  270. };
  271. /*
  272. * Sets the paint style to use when the mouse is hovering over the element. This is null by default.
  273. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  274. * it. This is because people will most likely want to change just one thing when hovering, say the
  275. * color for example, but leave the rest of the appearance the same.
  276. *
  277. * Parameters:
  278. * style - Style to use when the mouse is hovering.
  279. * doNotRepaint - if true, the component will not be repainted. useful when setting things up initially.
  280. */
  281. this.setHoverPaintStyle = function(style, doNotRepaint) {
  282. self.hoverPaintStyle = style;
  283. _updateHoverStyle();
  284. if (!doNotRepaint) self.repaint();
  285. };
  286. /*
  287. * sets/unsets the hover state of this element.
  288. *
  289. * Parameters:
  290. * hover - hover state boolean
  291. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  292. */
  293. this.setHover = function(hover, ignoreAttachedElements, timestamp) {
  294. // while dragging, we ignore these events. this keeps the UI from flashing and
  295. // swishing and whatevering.
  296. if (!self._jsPlumb.currentlyDragging && !self._jsPlumb.isHoverSuspended()) {
  297. _hover = hover;
  298. if (self.hoverClass != null && self.canvas != null) {
  299. if (hover)
  300. jpcl.addClass(self.canvas, self.hoverClass);
  301. else
  302. jpcl.removeClass(self.canvas, self.hoverClass);
  303. }
  304. if (self.hoverPaintStyle != null) {
  305. self.paintStyleInUse = hover ? self.hoverPaintStyle : self.paintStyle;
  306. timestamp = timestamp || _timestamp();
  307. self.repaint({timestamp:timestamp, recalc:false});
  308. }
  309. // get the list of other affected elements, if supported by this component.
  310. // for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  311. if (self.getAttachedElements && !ignoreAttachedElements)
  312. _updateAttachedElements(hover, _timestamp(), self);
  313. }
  314. };
  315. this.isHover = function() { return _hover; };
  316. var jpcl = jsPlumb.CurrentLibrary,
  317. events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ],
  318. eventFilters = { "mouseout":"mouseexit" },
  319. bindOne = function(o, c, evt) {
  320. var filteredEvent = eventFilters[evt] || evt;
  321. jpcl.bind(o, evt, function(ee) {
  322. c.fire(filteredEvent, c, ee);
  323. });
  324. },
  325. unbindOne = function(o, evt) {
  326. var filteredEvent = eventFilters[evt] || evt;
  327. jpcl.unbind(o, evt);
  328. };
  329. this.attachListeners = function(o, c) {
  330. for (var i = 0; i < events.length; i++) {
  331. bindOne(o, c, events[i]);
  332. }
  333. };
  334. var _updateAttachedElements = function(state, timestamp, sourceElement) {
  335. var affectedElements = self.getAttachedElements(); // implemented in subclasses
  336. if (affectedElements) {
  337. for (var i = 0; i < affectedElements.length; i++) {
  338. if (!sourceElement || sourceElement != affectedElements[i])
  339. affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements.
  340. }
  341. }
  342. };
  343. this.reattachListenersForElement = function(o) {
  344. if (arguments.length > 1) {
  345. for (var i = 0; i < events.length; i++)
  346. unbindOne(o, events[i]);
  347. for (var i = 1; i < arguments.length; i++)
  348. self.attachListeners(o, arguments[i]);
  349. }
  350. };
  351. },
  352. overlayCapableJsPlumbUIComponent = function(params) {
  353. jsPlumbUIComponent.apply(this, arguments);
  354. var self = this;
  355. /*
  356. * Property: overlays
  357. * List of Overlays for this component.
  358. */
  359. this.overlays = [];
  360. var processOverlay = function(o) {
  361. var _newOverlay = null;
  362. if (o.constructor == Array) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  363. // there's also a three arg version:
  364. // ["Arrow", { width:50 }, {location:0.7}]
  365. // which merges the 3rd arg into the 2nd.
  366. var type = o[0],
  367. // make a copy of the object so as not to mess up anyone else's reference...
  368. p = jsPlumb.extend({component:self, _jsPlumb:self._jsPlumb}, o[1]);
  369. if (o.length == 3) jsPlumb.extend(p, o[2]);
  370. _newOverlay = new jsPlumb.Overlays[self._jsPlumb.getRenderMode()][type](p);
  371. if (p.events) {
  372. for (var evt in p.events) {
  373. _newOverlay.bind(evt, p.events[evt]);
  374. }
  375. }
  376. } else if (o.constructor == String) {
  377. _newOverlay = new jsPlumb.Overlays[self._jsPlumb.getRenderMode()][o]({component:self, _jsPlumb:self._jsPlumb});
  378. } else {
  379. _newOverlay = o;
  380. }
  381. self.overlays.push(_newOverlay);
  382. },
  383. calculateOverlaysToAdd = function(params) {
  384. var defaultKeys = self.defaultOverlayKeys || [],
  385. o = params.overlays,
  386. checkKey = function(k) {
  387. return self._jsPlumb.Defaults[k] || jsPlumb.Defaults[k] || [];
  388. };
  389. if (!o) o = [];
  390. for (var i = 0; i < defaultKeys.length; i++)
  391. o.unshift.apply(o, checkKey(defaultKeys[i]));
  392. return o;
  393. }
  394. var _overlays = calculateOverlaysToAdd(params);//params.overlays || self._jsPlumb.Defaults.Overlays;
  395. if (_overlays) {
  396. for (var i = 0; i < _overlays.length; i++) {
  397. processOverlay(_overlays[i]);
  398. }
  399. }
  400. // overlay finder helper method
  401. var _getOverlayIndex = function(id) {
  402. var idx = -1;
  403. for (var i = 0; i < self.overlays.length; i++) {
  404. if (id === self.overlays[i].id) {
  405. idx = i;
  406. break;
  407. }
  408. }
  409. return idx;
  410. };
  411. /*
  412. * Function: addOverlay
  413. * Adds an Overlay to the Connection.
  414. *
  415. * Parameters:
  416. * overlay - Overlay to add.
  417. */
  418. this.addOverlay = function(overlay) {
  419. processOverlay(overlay);
  420. self.repaint();
  421. };
  422. /*
  423. * Function: getOverlay
  424. * Gets an overlay, by ID. Note: by ID. You would pass an 'id' parameter
  425. * in to the Overlay's constructor arguments, and then use that to retrieve
  426. * it via this method.
  427. */
  428. this.getOverlay = function(id) {
  429. var idx = _getOverlayIndex(id);
  430. return idx >= 0 ? self.overlays[idx] : null;
  431. };
  432. /*
  433. * Function: hideOverlay
  434. * Hides the overlay specified by the given id.
  435. */
  436. this.hideOverlay = function(id) {
  437. var o = self.getOverlay(id);
  438. if (o) o.hide();
  439. };
  440. /*
  441. * Function: showOverlay
  442. * Shows the overlay specified by the given id.
  443. */
  444. this.showOverlay = function(id) {
  445. var o = self.getOverlay(id);
  446. if (o) o.show();
  447. };
  448. /**
  449. * Function: removeAllOverlays
  450. * Removes all overlays from the Connection, and then repaints.
  451. */
  452. this.removeAllOverlays = function() {
  453. self.overlays.splice(0, self.overlays.length);
  454. self.repaint();
  455. };
  456. /**
  457. * Function:removeOverlay
  458. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  459. * Parameters:
  460. * overlayId - id of the overlay to remove.
  461. */
  462. this.removeOverlay = function(overlayId) {
  463. var idx = _getOverlayIndex(overlayId);
  464. if (idx != -1) {
  465. var o = self.overlays[idx];
  466. o.cleanup();
  467. self.overlays.splice(idx, 1);
  468. }
  469. };
  470. /**
  471. * Function:removeOverlays
  472. * Removes a set of overlays by ID. Note: by ID. this is a string you set in the overlay spec.
  473. * Parameters:
  474. * overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
  475. */
  476. this.removeOverlays = function() {
  477. for (var i = 0; i < arguments.length; i++)
  478. self.removeOverlay(arguments[i]);
  479. };
  480. // this is a shortcut helper method to let people add a label as
  481. // overlay.
  482. var _internalLabelOverlayId = "__label",
  483. _makeLabelOverlay = function(params) {
  484. var _params = {
  485. cssClass:params.cssClass,
  486. labelStyle : this.labelStyle,
  487. id:_internalLabelOverlayId,
  488. component:self,
  489. _jsPlumb:self._jsPlumb
  490. },
  491. mergedParams = jsPlumb.extend(_params, params);
  492. return new jsPlumb.Overlays[self._jsPlumb.getRenderMode()].Label( mergedParams );
  493. };
  494. if (params.label) {
  495. var loc = params.labelLocation || self.defaultLabelLocation || 0.5,
  496. labelStyle = params.labelStyle || self._jsPlumb.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;
  497. this.overlays.push(_makeLabelOverlay({
  498. label:params.label,
  499. location:loc,
  500. labelStyle:labelStyle
  501. }));
  502. }
  503. /*
  504. * Function: setLabel
  505. * Sets the Connection's label.
  506. *
  507. * Parameters:
  508. * l - label to set. May be a String, a Function that returns a String, or a params object containing { "label", "labelStyle", "location", "cssClass" }
  509. */
  510. this.setLabel = function(l) {
  511. var lo = self.getOverlay(_internalLabelOverlayId);
  512. if (!lo) {
  513. var params = l.constructor == String || l.constructor == Function ? { label:l } : l;
  514. lo = _makeLabelOverlay(params);
  515. this.overlays.push(lo);
  516. }
  517. else {
  518. if (l.constructor == String || l.constructor == Function) lo.setLabel(l);
  519. else {
  520. if (l.label) lo.setLabel(l.label);
  521. if (l.location) lo.setLocation(l.location);
  522. }
  523. }
  524. self.repaint();
  525. };
  526. /*
  527. Function:getLabel
  528. Returns the label text for this component (or a function if you are labelling with a function).
  529. This does not return the overlay itself; this is a convenience method which is a pair with
  530. setLabel; together they allow you to add and access a Label Overlay without having to create the
  531. Overlay object itself. For access to the underlying label overlay that jsPlumb has created,
  532. use getLabelOverlay.
  533. */
  534. this.getLabel = function() {
  535. var lo = self.getOverlay(_internalLabelOverlayId);
  536. return lo != null ? lo.getLabel() : null;
  537. };
  538. /*
  539. Function:getLabelOverlay
  540. Returns the underlying internal label overlay, which will exist if you specified a label on
  541. a connect or addEndpoint call, or have called setLabel at any stage.
  542. */
  543. this.getLabelOverlay = function() {
  544. return self.getOverlay(_internalLabelOverlayId);
  545. }
  546. },
  547. _bindListeners = function(obj, _self, _hoverFunction) {
  548. obj.bind("click", function(ep, e) { _self.fire("click", _self, e); });
  549. obj.bind("dblclick", function(ep, e) { _self.fire("dblclick", _self, e); });
  550. obj.bind("contextmenu", function(ep, e) { _self.fire("contextmenu", _self, e); });
  551. // this method is different; endpoint delegates hover to the first connection if there is one.
  552. // that allows the connection to notify all its endpoint and avoids a circular loop
  553. obj.bind("mouseenter", function(ep, e) {
  554. if (!_self.isHover()) {
  555. _hoverFunction(true);
  556. _self.fire("mouseenter", _self, e);
  557. }
  558. });
  559. // this method is different; endpoint delegates hover to the first connection if there is one.
  560. // that allows the connection to notify all its endpoint and avoids a circular loop
  561. obj.bind("mouseexit", function(ep, e) {
  562. if (_self.isHover()) {
  563. _hoverFunction(false);
  564. _self.fire("mouseexit", self, e);
  565. }
  566. });
  567. };
  568. var _jsPlumbInstanceIndex = 0,
  569. getInstanceIndex = function() {
  570. var i = _jsPlumbInstanceIndex + 1;
  571. _jsPlumbInstanceIndex++;
  572. return i;
  573. };
  574. var jsPlumbInstance = function(_defaults) {
  575. /*
  576. * Property: Defaults
  577. *
  578. * These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
  579. * to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
  580. * by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
  581. *
  582. * Properties:
  583. * - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
  584. * - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
  585. * - *Connector* The default connector definition to use for all connections. Default is "Bezier".
  586. * - *Container* Optional selector or element id that instructs jsPlumb to append elements it creates to a specific element.
  587. * - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  588. * - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  589. * - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
  590. * - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
  591. * - *EndpointStyle* The default style definition to use for all endpoints. Default is fillStyle:"#456".
  592. * - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
  593. * - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
  594. * - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
  595. * - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
  596. * - *LabelStyle* The default style to use for label overlays on connections.
  597. * - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
  598. * - *Overlays* The default overlay definitions. Defaults to an empty list.
  599. * - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
  600. * - *MouseEventsEnabled* Whether or not mouse events are enabled when using the canvas renderer. Defaults to true.
  601. * The idea of this is just to give people a way to prevent all the mouse listeners from activating if they know they won't need mouse events.
  602. * - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
  603. * - *RenderMode* What mode to use to paint with. If you're on IE<9, you don't really get to choose this. You'll just get VML. Otherwise, the jsPlumb default is to use Canvas elements.
  604. * - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
  605. */
  606. this.Defaults = {
  607. Anchor : "BottomCenter",
  608. Anchors : [ null, null ],
  609. ConnectionsDetachable : true,
  610. Connector : "Bezier",
  611. Container : null,
  612. DragOptions : { },
  613. DropOptions : { },
  614. Endpoint : "Dot",
  615. Endpoints : [ null, null ],
  616. EndpointStyle : { fillStyle : "#456" },
  617. EndpointStyles : [ null, null ],
  618. EndpointHoverStyle : null,
  619. EndpointHoverStyles : [ null, null ],
  620. HoverPaintStyle : null,
  621. LabelStyle : { color : "black" },
  622. LogEnabled : false,
  623. Overlays : [ ],
  624. MaxConnections : 1,
  625. MouseEventsEnabled : true,
  626. PaintStyle : { lineWidth : 8, strokeStyle : "#456" },
  627. //Reattach:false,
  628. RenderMode : "svg",
  629. Scope : "jsPlumb_DefaultScope"
  630. };
  631. if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
  632. this.logEnabled = this.Defaults.LogEnabled;
  633. EventGenerator.apply(this);
  634. var _bb = this.bind;
  635. this.bind = function(event, fn) {
  636. if ("ready" === event && initialized) fn();
  637. else _bb(event, fn);
  638. };
  639. var _currentInstance = this,
  640. _instanceIndex = getInstanceIndex(),
  641. log = null,
  642. repaintFunction = function() {
  643. jsPlumb.repaintEverything();
  644. },
  645. automaticRepaint = true,
  646. repaintEverything = function() {
  647. if (automaticRepaint)
  648. repaintFunction();
  649. },
  650. resizeTimer = null,
  651. initialized = false,
  652. connectionsByScope = {},
  653. /**
  654. * map of element id -> endpoint lists. an element can have an arbitrary
  655. * number of endpoints on it, and not all of them have to be connected
  656. * to anything.
  657. */
  658. endpointsByElement = {},
  659. endpointsByUUID = {},
  660. offsets = {},
  661. offsetTimestamps = {},
  662. floatingConnections = {},
  663. draggableStates = {},
  664. _mouseEventsEnabled = this.Defaults.MouseEventsEnabled,
  665. canvasList = [],
  666. sizes = [],
  667. //listeners = {}, // a map: keys are event types, values are lists of listeners.
  668. DEFAULT_SCOPE = this.Defaults.Scope,
  669. renderMode = null, // will be set in init()
  670. /**
  671. * helper method to add an item to a list, creating the list if it does
  672. * not yet exist.
  673. */
  674. _addToList = function(map, key, value) {
  675. var l = map[key];
  676. if (l == null) {
  677. l = [];
  678. map[key] = l;
  679. }
  680. l.push(value);
  681. return l;
  682. },
  683. /**
  684. * appends an element to some other element, which is calculated as follows:
  685. *
  686. * 1. if _currentInstance.Defaults.Container exists, use that element.
  687. * 2. if the 'parent' parameter exists, use that.
  688. * 3. otherwise just use the document body.
  689. *
  690. */
  691. _appendElement = function(el, parent) {
  692. if (_currentInstance.Defaults.Container)
  693. jsPlumb.CurrentLibrary.appendElement(el, _currentInstance.Defaults.Container);
  694. else if (!parent)
  695. document.body.appendChild(el);
  696. else
  697. jsPlumb.CurrentLibrary.appendElement(el, parent);
  698. },
  699. _curIdStamp = 1,
  700. _idstamp = function() { return "" + _curIdStamp++; },
  701. /**
  702. * YUI, for some reason, put the result of a Y.all call into an object that contains
  703. * a '_nodes' array, instead of handing back an array-like object like the other
  704. * libraries do.
  705. */
  706. _convertYUICollection = function(c) {
  707. return c._nodes ? c._nodes : c;
  708. },
  709. _suspendDrawing = false,
  710. /*
  711. sets whether or not to suspend drawing. you should use this if you need to connect a whole load of things in one go.
  712. it will save you a lot of time.
  713. */
  714. _setSuspendDrawing = function(val, repaintAfterwards) {
  715. _suspendDrawing = val;
  716. if (repaintAfterwards) _currentInstance.repaintEverything();
  717. },
  718. /**
  719. * Draws an endpoint and its connections. this is the main entry point into drawing connections as well
  720. * as endpoints, since jsPlumb is endpoint-centric under the hood.
  721. *
  722. * @param element element to draw (of type library specific element object)
  723. * @param ui UI object from current library's event system. optional.
  724. * @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  725. */
  726. _draw = function(element, ui, timestamp) {
  727. if (!_suspendDrawing) {
  728. var id = _getAttribute(element, "id");
  729. _currentInstance.anchorManager.redraw(id, ui, timestamp);
  730. }
  731. },
  732. /**
  733. * executes the given function against the given element if the first
  734. * argument is an object, or the list of elements, if the first argument
  735. * is a list. the function passed in takes (element, elementId) as
  736. * arguments.
  737. */
  738. _elementProxy = function(element, fn) {
  739. var retVal = null;
  740. if (element.constructor == Array) {
  741. retVal = [];
  742. for ( var i = 0; i < element.length; i++) {
  743. var el = _getElementObject(element[i]), id = _getAttribute(el, "id");
  744. retVal.push(fn(el, id)); // append return values to what we will return
  745. }
  746. } else {
  747. var el = _getElementObject(element), id = _getAttribute(el, "id");
  748. retVal = fn(el, id);
  749. }
  750. return retVal;
  751. },
  752. /**
  753. * gets an Endpoint by uuid.
  754. */
  755. _getEndpoint = function(uuid) { return endpointsByUUID[uuid]; },
  756. /**
  757. * inits a draggable if it's not already initialised.
  758. */
  759. _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  760. var draggable = isDraggable == null ? false : isDraggable;
  761. if (draggable) {
  762. if (jsPlumb.CurrentLibrary.isDragSupported(element) && !jsPlumb.CurrentLibrary.isAlreadyDraggable(element)) {
  763. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  764. options = jsPlumb.extend( {}, options); // make a copy.
  765. var dragEvent = jsPlumb.CurrentLibrary.dragEvents["drag"],
  766. stopEvent = jsPlumb.CurrentLibrary.dragEvents["stop"];
  767. options[dragEvent] = _wrap(options[dragEvent], function() {
  768. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  769. _draw(element, ui);
  770. _addClass(element, "jsPlumb_dragged");
  771. });
  772. options[stopEvent] = _wrap(options[stopEvent], function() {
  773. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  774. _draw(element, ui);
  775. _removeClass(element, "jsPlumb_dragged");
  776. });
  777. draggableStates[_getId(element)] = true;
  778. var draggable = draggableStates[_getId(element)];
  779. options.disabled = draggable == null ? false : !draggable;
  780. jsPlumb.CurrentLibrary.initDraggable(element, options, false);
  781. }
  782. }
  783. },
  784. /*
  785. * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc.
  786. */
  787. _prepareConnectionParams = function(params, referenceParams) {
  788. var _p = jsPlumb.extend( {}, params);
  789. if (referenceParams) jsPlumb.extend(_p, referenceParams);
  790. if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source;
  791. if (_p.source && _p.target.endpoint) _p.targetEndpoint = _p.target;
  792. // test for endpoint uuids to connect
  793. if (params.uuids) {
  794. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  795. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  796. }
  797. // now ensure that if we do have Endpoints already, they're not full.
  798. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  799. _log(_currentInstance, "could not add connection; source endpoint is full");
  800. return;
  801. }
  802. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  803. _log(_currentInstance, "could not add connection; target endpoint is full");
  804. return;
  805. }
  806. // copy in any connectorOverlays that were specified on the source endpoint.
  807. // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not.
  808. if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) {
  809. _p.overlays = _p.overlays || [];
  810. for (var i = 0; i < _p.sourceEndpoint.connectorOverlays.length; i++) {
  811. _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]);
  812. }
  813. }
  814. // tooltip. params.tooltip takes precedence, then sourceEndpoint.connectorTooltip.
  815. _p.tooltip = params.tooltip;
  816. if (!_p.tooltip && _p.sourceEndpoint && _p.sourceEndpoint.connectorTooltip)
  817. _p.tooltip = _p.sourceEndpoint.connectorTooltip;
  818. if (_p.target && !_p.target.endpoint) {
  819. var tid = _getId(_p.target),
  820. tep =_targetEndpointDefinitions[tid];
  821. var overrideOne = function(singlePropertyName, pluralPropertyName, tepProperty, tep) {
  822. if (tep[tepProperty]) {
  823. if (_p[pluralPropertyName]) _p[pluralPropertyName][1] = tep[tepProperty];
  824. else if (_p[singlePropertyName]) {
  825. _p[pluralPropertyName] = [ _p[singlePropertyName], tep[tepProperty] ];
  826. _p[singlePropertyName] = null;
  827. }
  828. else _p[pluralPropertyName] = [ null, tep[tepProperty] ];
  829. }
  830. };
  831. if (tep) {
  832. overrideOne("endpoint", "endpoints", "endpoint", tep);
  833. overrideOne("endpointStyle", "endpointStyles", "paintStyle", tep);
  834. overrideOne("endpointHoverStyle", "endpointHoverStyles", "hoverPaintStyle", tep);
  835. }
  836. }
  837. return _p;
  838. },
  839. _newConnection = function(params) {
  840. var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
  841. endpointFunc = _currentInstance.Defaults.EndpointType || Endpoint,
  842. parent = jsPlumb.CurrentLibrary.getParent;
  843. if (params.container)
  844. params["parent"] = params.container;
  845. else {
  846. if (params.sourceEndpoint)
  847. params["parent"] = params.sourceEndpoint.parent;
  848. else if (params.source.constructor == endpointFunc)
  849. params["parent"] = params.source.parent;
  850. else params["parent"] = parent(params.source);
  851. }
  852. params["_jsPlumb"] = _currentInstance;
  853. var con = new connectionFunc(params);
  854. con.id = "con_" + _idstamp();
  855. _eventFireProxy("click", "click", con);
  856. _eventFireProxy("dblclick", "dblclick", con);
  857. _eventFireProxy("contextmenu", "contextmenu", con);
  858. return con;
  859. },
  860. /**
  861. * adds the connection to the backing model, fires an event if necessary and then redraws
  862. */
  863. _finaliseConnection = function(jpc, params, originalEvent) {
  864. params = params || {};
  865. // add to list of connections (by scope).
  866. if (!jpc.suspendedEndpoint)
  867. _addToList(connectionsByScope, jpc.scope, jpc);
  868. // fire an event
  869. if (!params.doNotFireConnectionEvent && params.fireEvent !== false) {
  870. _currentInstance.fire("jsPlumbConnection", {
  871. connection:jpc,
  872. source : jpc.source, target : jpc.target,
  873. sourceId : jpc.sourceId, targetId : jpc.targetId,
  874. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  875. }, originalEvent);
  876. }
  877. // always inform the anchor manager
  878. // except that if jpc has a suspended endpoint it's not true to say the
  879. // connection is new; it has just (possibly) moved. the question is whether
  880. // to make that call here or in the anchor manager. i think perhaps here.
  881. _currentInstance.anchorManager.newConnection(jpc);
  882. // force a paint
  883. _draw(jpc.source);
  884. },
  885. _eventFireProxy = function(event, proxyEvent, obj) {
  886. obj.bind(event, function(originalObject, originalEvent) {
  887. _currentInstance.fire(proxyEvent, obj, originalEvent);
  888. });
  889. },
  890. /**
  891. * for the given endpoint params, returns an appropriate parent element for the UI elements that will be added.
  892. * this function is used by _newEndpoint (directly below), and also in the makeSource function in jsPlumb.
  893. *
  894. * the logic is to first look for a "container" member of params, and pass that back if found. otherwise we
  895. * handoff to the 'getParent' function in the current library.
  896. */
  897. _getParentFromParams = function(params) {
  898. if (params.container)
  899. return params.container;
  900. else {
  901. var tag = jsPlumb.CurrentLibrary.getTagName(params.source),
  902. p = jsPlumb.CurrentLibrary.getParent(params.source);
  903. if (tag && tag.toLowerCase() === "td")
  904. return jsPlumb.CurrentLibrary.getParent(p);
  905. else return p;
  906. }
  907. },
  908. /**
  909. factory method to prepare a new endpoint. this should always be used instead of creating Endpoints
  910. manually, since this method attaches event listeners and an id.
  911. */
  912. _newEndpoint = function(params) {
  913. var endpointFunc = _currentInstance.Defaults.EndpointType || Endpoint;
  914. params.parent = _getParentFromParams(params);
  915. params["_jsPlumb"] = _currentInstance;
  916. var ep = new endpointFunc(params);
  917. ep.id = "ep_" + _idstamp();
  918. _eventFireProxy("click", "endpointClick", ep);
  919. _eventFireProxy("dblclick", "endpointDblClick", ep);
  920. _eventFireProxy("contextmenu", "contextmenu", ep);
  921. return ep;
  922. },
  923. /**
  924. * performs the given function operation on all the connections found
  925. * for the given element id; this means we find all the endpoints for
  926. * the given element, and then for each endpoint find the connectors
  927. * connected to it. then we pass each connection in to the given
  928. * function.
  929. */
  930. _operation = function(elId, func, endpointFunc) {
  931. var endpoints = endpointsByElement[elId];
  932. if (endpoints && endpoints.length) {
  933. for ( var i = 0; i < endpoints.length; i++) {
  934. for ( var j = 0; j < endpoints[i].connections.length; j++) {
  935. var retVal = func(endpoints[i].connections[j]);
  936. // if the function passed in returns true, we exit.
  937. // most functions return false.
  938. if (retVal) return;
  939. }
  940. if (endpointFunc) endpointFunc(endpoints[i]);
  941. }
  942. }
  943. },
  944. /**
  945. * perform an operation on all elements.
  946. */
  947. _operationOnAll = function(func) {
  948. for ( var elId in endpointsByElement) {
  949. _operation(elId, func);
  950. }
  951. },
  952. /**
  953. * helper to remove an element from the DOM.
  954. */
  955. _removeElement = function(element, parent) {
  956. if (element != null && element.parentNode != null) {
  957. element.parentNode.removeChild(element);
  958. }
  959. },
  960. /**
  961. * helper to remove a list of elements from the DOM.
  962. */
  963. _removeElements = function(elements, parent) {
  964. for ( var i = 0; i < elements.length; i++)
  965. _removeElement(elements[i], parent);
  966. },
  967. /**
  968. * Sets whether or not the given element(s) should be draggable,
  969. * regardless of what a particular plumb command may request.
  970. *
  971. * @param element
  972. * May be a string, a element objects, or a list of
  973. * strings/elements.
  974. * @param draggable
  975. * Whether or not the given element(s) should be draggable.
  976. */
  977. _setDraggable = function(element, draggable) {
  978. return _elementProxy(element, function(el, id) {
  979. draggableStates[id] = draggable;
  980. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  981. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  982. }
  983. });
  984. },
  985. /**
  986. * private method to do the business of hiding/showing.
  987. *
  988. * @param el
  989. * either Id of the element in question or a library specific
  990. * object for the element.
  991. * @param state
  992. * String specifying a value for the css 'display' property
  993. * ('block' or 'none').
  994. */
  995. _setVisible = function(el, state, alsoChangeEndpoints) {
  996. state = state === "block";
  997. var endpointFunc = null;
  998. if (alsoChangeEndpoints) {
  999. if (state) endpointFunc = function(ep) {
  1000. ep.setVisible(true, true, true);
  1001. };
  1002. else endpointFunc = function(ep) {
  1003. ep.setVisible(false, true, true);
  1004. };
  1005. }
  1006. var id = _getAttribute(el, "id");
  1007. _operation(id, function(jpc) {
  1008. if (state && alsoChangeEndpoints) {
  1009. // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
  1010. // this block will only set a connection to be visible if the other endpoint in the connection is also visible.
  1011. var oidx = jpc.sourceId === id ? 1 : 0;
  1012. if (jpc.endpoints[oidx].isVisible()) jpc.setVisible(true);
  1013. }
  1014. else // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
  1015. jpc.setVisible(state);
  1016. }, endpointFunc);
  1017. },
  1018. /**
  1019. * toggles the draggable state of the given element(s).
  1020. *
  1021. * @param el
  1022. * either an id, or an element object, or a list of
  1023. * ids/element objects.
  1024. */
  1025. _toggleDraggable = function(el) {
  1026. return _elementProxy(el, function(el, elId) {
  1027. var state = draggableStates[elId] == null ? false : draggableStates[elId];
  1028. state = !state;
  1029. draggableStates[elId] = state;
  1030. jsPlumb.CurrentLibrary.setDraggable(el, state);
  1031. return state;
  1032. });
  1033. },
  1034. /**
  1035. * private method to do the business of toggling hiding/showing.
  1036. *
  1037. * @param elId
  1038. * Id of the element in question
  1039. */
  1040. _toggleVisible = function(elId, changeEndpoints) {
  1041. var endpointFunc = null;
  1042. if (changeEndpoints) {
  1043. endpointFunc = function(ep) {
  1044. var state = ep.isVisible();
  1045. ep.setVisible(!state);
  1046. };
  1047. }
  1048. _operation(elId, function(jpc) {
  1049. var state = jpc.isVisible();
  1050. jpc.setVisible(!state);
  1051. }, endpointFunc);
  1052. // todo this should call _elementProxy, and pass in the
  1053. // _operation(elId, f) call as a function. cos _toggleDraggable does
  1054. // that.
  1055. },
  1056. /**
  1057. * updates the offset and size for a given element, and stores the
  1058. * values. if 'offset' is not null we use that (it would have been
  1059. * passed in from a drag call) because it's faster; but if it is null,
  1060. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  1061. */
  1062. _updateOffset = function(params) {
  1063. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId;
  1064. if (!recalc) {
  1065. if (timestamp && timestamp === offsetTimestamps[elId])
  1066. return offsets[elId];
  1067. }
  1068. if (recalc || !offset) { // if forced repaint or no offset
  1069. // available, we recalculate.
  1070. // get the current size and offset, and store them
  1071. var s = _getElementObject(elId);
  1072. if (s != null) {
  1073. sizes[elId] = _getSize(s);
  1074. offsets[elId] = _getOffset(s);
  1075. offsetTimestamps[elId] = timestamp;
  1076. }
  1077. } else {
  1078. offsets[elId] = offset;
  1079. if (sizes[elId] == null) {
  1080. var s = _getElementObject(elId);
  1081. if (s != null)
  1082. sizes[elId] = _getSize(s);
  1083. }
  1084. }
  1085. if(offsets[elId] && !offsets[elId].right) {
  1086. offsets[elId].right = offsets[elId].left + sizes[elId][0];
  1087. offsets[elId].bottom = offsets[elId].top + sizes[elId][1];
  1088. offsets[elId].width = sizes[elId][0];
  1089. offsets[elId].height = sizes[elId][1];
  1090. offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2);
  1091. offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2);
  1092. }
  1093. return offsets[elId];
  1094. },
  1095. // TODO comparison performance
  1096. _getCachedData = function(elId) {
  1097. var o = offsets[elId];
  1098. if (!o) o = _updateOffset({elId:elId});
  1099. return {o:o, s:sizes[elId]};
  1100. },
  1101. /**
  1102. * gets an id for the given element, creating and setting one if
  1103. * necessary. the id is of the form
  1104. *
  1105. * jsPlumb_<instance index>_<index in instance>
  1106. *
  1107. * where "index in instance" is a monotonically increasing integer that starts at 0,
  1108. * for each instance. this method is used not only to assign ids to elements that do not
  1109. * have them but also to connections and endpoints.
  1110. */
  1111. _getId = function(element, uuid) {
  1112. var ele = _getElementObject(element);
  1113. var id = _getAttribute(ele, "id");
  1114. if (!id || id == "undefined") {
  1115. // check if fixed uuid parameter is given
  1116. if (arguments.length == 2 && arguments[1] != undefined)
  1117. id = uuid;
  1118. else
  1119. id = "jsPlumb_" + _instanceIndex + "_" + _idstamp();
  1120. _setAttribute(ele, "id", id);
  1121. }
  1122. return id;
  1123. },
  1124. /**
  1125. * wraps one function with another, creating a placeholder for the
  1126. * wrapped function if it was null. this is used to wrap the various
  1127. * drag/drop event functions - to allow jsPlumb to be notified of
  1128. * important lifecycle events without imposing itself on the user's
  1129. * drag/drop functionality. TODO: determine whether or not we should
  1130. * support an error handler concept, if one of the functions fails.
  1131. *
  1132. * @param wrappedFunction original function to wrap; may be null.
  1133. * @param newFunction function to wrap the original with.
  1134. * @param returnOnThisValue Optional. Indicates that the wrappedFunction should
  1135. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  1136. * note that this is a simple comparison and only works for primitives right now.
  1137. */
  1138. _wrap = function(wrappedFunction, newFunction, returnOnThisValue) {
  1139. wrappedFunction = wrappedFunction || function() { };
  1140. newFunction = newFunction || function() { };
  1141. return function() {
  1142. var r = null;
  1143. try {
  1144. r = newFunction.apply(this, arguments);
  1145. } catch (e) {
  1146. _log(_currentInstance, 'jsPlumb function failed : ' + e);
  1147. }
  1148. if (returnOnThisValue == null || (r !== returnOnThisValue)) {
  1149. try {
  1150. wrappedFunction.apply(this, arguments);
  1151. } catch (e) {
  1152. _log(_currentInstance, 'wrapped function failed : ' + e);
  1153. }
  1154. }
  1155. return r;
  1156. };
  1157. };
  1158. /*
  1159. * Property: connectorClass
  1160. * The CSS class to set on Connection elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  1161. */
  1162. this.connectorClass = "_jsPlumb_connector";
  1163. /*
  1164. * Property: endpointClass
  1165. * The CSS class to set on Endpoint elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  1166. */
  1167. this.endpointClass = "_jsPlumb_endpoint";
  1168. /*
  1169. * Property: overlayClass
  1170. * 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.
  1171. */
  1172. this.overlayClass = "_jsPlumb_overlay";
  1173. this.Anchors = {};
  1174. this.Connectors = {
  1175. "canvas":{},
  1176. "svg":{},
  1177. "vml":{}
  1178. };
  1179. this.Endpoints = {
  1180. "canvas":{},
  1181. "svg":{},
  1182. "vml":{}
  1183. };
  1184. this.Overlays = {
  1185. "canvas":{},
  1186. "svg":{},
  1187. "vml":{}
  1188. };
  1189. // ************************ PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS *****************************************
  1190. /*
  1191. * Function: bind
  1192. * Bind to an event on jsPlumb.
  1193. *
  1194. * Parameters:
  1195. * event - the event to bind. Available events on jsPlumb are:
  1196. * - *jsPlumbConnection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
  1197. * - *jsPlumbConnectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
  1198. * - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
  1199. * - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
  1200. * - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
  1201. * - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
  1202. *
  1203. * callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
  1204. */
  1205. /*
  1206. * Function: clearListeners
  1207. * Clears either all listeners, or listeners for some specific event.
  1208. *
  1209. * Parameters:
  1210. * event - optional. constrains the clear to just listeners for this event.
  1211. */
  1212. // *************** END OF PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS ***********************************************************
  1213. /*
  1214. Function: addClass
  1215. Helper method to abstract out differences in setting css classes on the different renderer types.
  1216. */
  1217. this.addClass = function(el, clazz) {
  1218. return jsPlumb.CurrentLibrary.addClass(el, clazz);
  1219. };
  1220. /*
  1221. Function: removeClass
  1222. Helper method to abstract out differences in setting css classes on the different renderer types.
  1223. */
  1224. this.removeClass = function(el, clazz) {
  1225. return jsPlumb.CurrentLibrary.removeClass(el, clazz);
  1226. };
  1227. /*
  1228. Function: hasClass
  1229. Helper method to abstract out differences in testing for css classes on the different renderer types.
  1230. */
  1231. this.hasClass = function(el, clazz) {
  1232. return jsPlumb.CurrentLibrary.hasClass(el, clazz);
  1233. };
  1234. /*
  1235. Function: addEndpoint
  1236. Adds an <Endpoint> to a given element or elements.
  1237. Parameters:
  1238. el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  1239. params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
  1240. referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
  1241. shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
  1242. this object are anything that 'params' can contain. See <Endpoint>.
  1243. Returns:
  1244. The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
  1245. See Also:
  1246. <addEndpoints>
  1247. */
  1248. this.addEndpoint = function(el, params, referenceParams) {
  1249. referenceParams = referenceParams || {};
  1250. var p = jsPlumb.extend({}, referenceParams);
  1251. jsPlumb.extend(p, params);
  1252. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
  1253. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  1254. // YUI wrapper
  1255. el = _convertYUICollection(el);
  1256. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  1257. for (var i = 0; i < inputs.length; i++) {
  1258. var _el = _getElementObject(inputs[i]), id = _getId(_el);
  1259. p.source = _el;
  1260. _updateOffset({ elId : id });
  1261. var e = _newEndpoint(p);
  1262. if (p.parentAnchor) e.parentAnchor = p.parentAnchor;
  1263. _addToList(endpointsByElement, id, e);
  1264. var myOffset = offsets[id], myWH = sizes[id];
  1265. var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e });
  1266. e.paint({ anchorLoc : anchorLoc });
  1267. results.push(e);
  1268. }
  1269. return results.length == 1 ? results[0] : results;
  1270. };
  1271. /*
  1272. Function: addEndpoints
  1273. Adds a list of <Endpoint>s to a given element or elements.
  1274. Parameters:
  1275. target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  1276. endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
  1277. referenceParams - Object containing more Endpoint constructor arguments; 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.
  1278. Returns:
  1279. List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
  1280. See Also:
  1281. <addEndpoint>
  1282. */
  1283. this.addEndpoints = function(el, endpoints, referenceParams) {
  1284. var results = [];
  1285. for ( var i = 0; i < endpoints.length; i++) {
  1286. var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
  1287. if (e.constructor == Array)
  1288. Array.prototype.push.apply(results, e);
  1289. else results.push(e);
  1290. }
  1291. return results;
  1292. };
  1293. /*
  1294. Function: animate
  1295. This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
  1296. the 'step' function if necessary). This only supports the two-arg version of the animate call in jQuery, the one that takes an 'options' object as
  1297. the second arg. MooTools has only one method, a two arg one. Which is handy. YUI has a one-arg method, so jsPlumb merges 'properties' and 'options' together for YUI.
  1298. Parameters:
  1299. el - Element to animate. Either an id, or a selector representing the element.
  1300. properties - The 'properties' argument you want passed to the library's animate call.
  1301. options - The 'options' argument you want passed to the library's animate call.
  1302. Returns:
  1303. void
  1304. */
  1305. this.animate = function(el, properties, options) {
  1306. var ele = _getElementObject(el), id = _getAttribute(el, "id");
  1307. options = options || {};
  1308. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  1309. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  1310. options[stepFunction] = _wrap(options[stepFunction], function() {
  1311. _currentInstance.repaint(id);
  1312. });
  1313. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  1314. options[completeFunction] = _wrap(options[completeFunction],
  1315. function() {
  1316. _currentInstance.repaint(id);
  1317. });
  1318. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  1319. };
  1320. /**
  1321. * checks for a listener for the given condition, executing it if found, passing in the given value.
  1322. * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since
  1323. * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition"
  1324. * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these
  1325. * condition events anyway.
  1326. */
  1327. this.checkCondition = function(conditionName, value) {
  1328. var l = _currentInstance.getListener(conditionName);
  1329. var r = true;
  1330. if (l && l.length > 0) {
  1331. try {
  1332. for (var i = 0 ; i < l.length; i++) {
  1333. r = r && l[i](value);
  1334. }
  1335. }
  1336. catch (e) {
  1337. _log(_currentInstance, "cannot check condition [" + conditionName + "]" + e);
  1338. }
  1339. }
  1340. return r;
  1341. };
  1342. /*
  1343. Function: connect
  1344. Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
  1345. Parameters:
  1346. params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
  1347. referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
  1348. Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
  1349. Returns:
  1350. The newly created <Connection>.
  1351. */
  1352. this.connect = function(params, referenceParams) {
  1353. // prepare a final set of parameters to create connection with
  1354. var _p = _prepareConnectionParams(params, referenceParams);
  1355. // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams
  1356. // will return null (and log something) if either endpoint was full. what would be nicer is to
  1357. // create a dedicated 'error' object.
  1358. if (_p) {
  1359. // a connect call will delete its created endpoints on detach, unless otherwise specified.
  1360. // this is because the endpoints belong to this connection only, and are no use to
  1361. // anyone else, so they hang around like a bad smell.
  1362. if (_p.deleteEndpointsOnDetach == null)
  1363. _p.deleteEndpointsOnDetach = true;
  1364. // create the connection. it is not yet registered
  1365. var jpc = _newConnection(_p);
  1366. // now add it the model, fire an event, and redraw
  1367. _finaliseConnection(jpc, _p);
  1368. return jpc;
  1369. }
  1370. };
  1371. /*
  1372. Function: deleteEndpoint
  1373. Deletes an Endpoint and removes all Connections it has (which removes the Connections from the other Endpoints involved too)
  1374. Parameters:
  1375. object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
  1376. Returns:
  1377. void
  1378. */
  1379. this.deleteEndpoint = function(object) {
  1380. var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object;
  1381. if (endpoint) {
  1382. var uuid = endpoint.getUuid();
  1383. if (uuid) endpointsByUUID[uuid] = null;
  1384. endpoint.detachAll();
  1385. _removeElements(endpoint.endpoint.getDisplayElements());
  1386. _currentInstance.anchorManager.deleteEndpoint(endpoint);
  1387. for (var e in endpointsByElement) {
  1388. var endpoints = endpointsByElement[e];
  1389. if (endpoints) {
  1390. var newEndpoints = [];
  1391. for (var i = 0; i < endpoints.length; i++)
  1392. if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
  1393. endpointsByElement[e] = newEndpoints;
  1394. }
  1395. }
  1396. delete endpoint;
  1397. }
  1398. };
  1399. /*
  1400. Function: deleteEveryEndpoint
  1401. Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
  1402. between this method and jsPlumb.reset).
  1403. Returns:
  1404. void
  1405. */
  1406. this.deleteEveryEndpoint = function() {
  1407. for ( var id in endpointsByElement) {
  1408. var endpoints = endpointsByElement[id];
  1409. if (endpoints && endpoints.length) {
  1410. for ( var i = 0; i < endpoints.length; i++) {
  1411. _currentInstance.deleteEndpoint(endpoints[i]);
  1412. }
  1413. }
  1414. }
  1415. delete endpointsByElement;
  1416. endpointsByElement = {};
  1417. delete endpointsByUUID;
  1418. endpointsByUUID = {};
  1419. };
  1420. var fireDetachEvent = function(jpc, doFireEvent) {
  1421. // may have been given a connection, or in special cases, an object
  1422. var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
  1423. argIsConnection = jpc.constructor == connType,
  1424. params = argIsConnection ? {
  1425. connection:jpc,
  1426. source : jpc.source, target : jpc.target,
  1427. sourceId : jpc.sourceId, targetId : jpc.targetId,
  1428. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  1429. } : jpc;
  1430. if (doFireEvent) _currentInstance.fire("jsPlumbConnectionDetached", params);
  1431. _currentInstance.anchorManager.connectionDetached(params);
  1432. };
  1433. /*
  1434. Function: detach
  1435. Detaches and then removes a <Connection>. From 1.3.5 this method has been altered to remove support for
  1436. specifying Connections by various parameters; you can now pass in a Connection as the first argument and
  1437. an optional parameters object as a second argument. If you need the functionality this method provided
  1438. before 1.3.5 then you should use the getConnections method to get the list of Connections to detach, and
  1439. then iterate through them, calling this for each one.
  1440. Parameters:
  1441. connection - the <Connection> to detach
  1442. params - optional parameters to the detach call. valid values here are
  1443. fireEvent : defaults to false; indicates you want jsPlumb to fire a connection
  1444. detached event. The thinking behind this is that if you made a programmatic
  1445. call to detach an event, you probably don't need the callback.
  1446. forceDetach : defaults to false. allows you to override any beforeDetach listeners that may be registered.
  1447. Returns:
  1448. true if successful, false if not.
  1449. */
  1450. this.detach = function() {
  1451. if (arguments.length == 0) return;
  1452. var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
  1453. firstArgIsConnection = arguments[0].constructor == connType,
  1454. params = arguments.length == 2 ? firstArgIsConnection ? (arguments[1] || {}) : arguments[0] : arguments[0],
  1455. fireEvent = (params.fireEvent !== false),
  1456. forceDetach = params.forceDetach,
  1457. connection = firstArgIsConnection ? arguments[0] : params.connection;
  1458. if (connection) {
  1459. if (forceDetach || (connection.isDetachAllowed(connection)
  1460. && connection.endpoints[0].isDetachAllowed(connection)
  1461. && connection.endpoints[1].isDetachAllowed(connection))) {
  1462. if (forceDetach || _currentInstance.checkCondition("beforeDetach", connection))
  1463. connection.endpoints[0].detach(connection, false, true, fireEvent); // TODO check this param iscorrect for endpoint's detach method
  1464. }
  1465. }
  1466. else {
  1467. var _p = jsPlumb.extend( {}, params); // a backwards compatibility hack: source should be thought of as 'params' in this case.
  1468. // test for endpoint uuids to detach
  1469. if (_p.uuids) {
  1470. _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]), fireEvent);
  1471. } else if (_p.sourceEndpoint && _p.targetEndpoint) {
  1472. _p.sourceEndpoint.detachFrom(_p.targetEndpoint);
  1473. } else {
  1474. var sourceId = _getId(_p.source),
  1475. targetId = _getId(_p.target);
  1476. _operation(sourceId, function(jpc) {
  1477. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  1478. if (_currentInstance.checkCondition("beforeDetach", jpc)) {
  1479. jpc.endpoints[0].detach(jpc, false, true, fireEvent);
  1480. }
  1481. }
  1482. });
  1483. }
  1484. }
  1485. };
  1486. /*
  1487. Function: detachAllConnections
  1488. Removes all an element's Connections.
  1489. Parameters:
  1490. el - either the id of the element, or a selector for the element.
  1491. params - optional parameters. alowed values:
  1492. fireEvent : defaults to true, whether or not to fire the detach event.
  1493. Returns:
  1494. void
  1495. */
  1496. this.detachAllConnections = function(el, params) {
  1497. params = params || {};
  1498. el = _getElementObject(el);
  1499. var id = _getAttribute(el, "id"),
  1500. endpoints = endpointsByElement[id];
  1501. if (endpoints && endpoints.length) {
  1502. for ( var i = 0; i < endpoints.length; i++) {
  1503. endpoints[i].detachAll(params.fireEvent);
  1504. }
  1505. }
  1506. };
  1507. /*
  1508. Function: detachEveryConnection
  1509. Remove all Connections from all elements, but leaves Endpoints in place.
  1510. Parameters:
  1511. params - optional params object containing:
  1512. fireEvent : whether or not to fire detach events. defaults to true.
  1513. Returns:
  1514. void
  1515. See Also:
  1516. <removeEveryEndpoint>
  1517. */
  1518. this.detachEveryConnection = function(params) {
  1519. params = params || {};
  1520. for ( var id in endpointsByElement) {
  1521. var endpoints = endpointsByElement[id];
  1522. if (endpoints && endpoints.length) {
  1523. for ( var i = 0; i < endpoints.length; i++) {
  1524. endpoints[i].detachAll(params.fireEvent);
  1525. }
  1526. }
  1527. }
  1528. delete connectionsByScope;
  1529. connectionsByScope = {};
  1530. };
  1531. /*
  1532. Function: draggable
  1533. Initialises the draggability of some element or elements. You should use this instead of y
  1534. our library's draggable method so that jsPlumb can setup the appropriate callbacks. Your
  1535. underlying library's drag method is always called from this method.
  1536. Parameters:
  1537. el - either an element id, a list of element ids, or a selector.
  1538. options - options to pass through to the underlying library
  1539. Returns:
  1540. void
  1541. */
  1542. // TODO it would be nice if this supported a selector string, instead of an id.
  1543. this.draggable = function(el, options) {
  1544. if (typeof el == 'object' && el.length) {
  1545. for ( var i = 0; i < el.length; i++) {
  1546. var ele = _getElementObject(el[i]);
  1547. if (ele) _initDraggableIfNecessary(ele, true, options);
  1548. }
  1549. }
  1550. else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced
  1551. // into the library adapters (for jquery and mootools aswell)
  1552. for ( var i = 0; i < el._nodes.length; i++) {
  1553. var ele = _getElementObject(el._nodes[i]);
  1554. if (ele) _initDraggableIfNecessary(ele, true, options);
  1555. }
  1556. }
  1557. else {
  1558. var ele = _getElementObject(el);
  1559. if (ele) _initDraggableIfNecessary(ele, true, options);
  1560. }
  1561. };
  1562. /*
  1563. Function: extend
  1564. Wraps the underlying library's extend functionality.
  1565. Parameters:
  1566. o1 - object to extend
  1567. o2 - object to extend o1 with
  1568. Returns:
  1569. o1, extended with all properties from o2.
  1570. */
  1571. this.extend = function(o1, o2) {
  1572. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1573. };
  1574. /*
  1575. * Function: getDefaultEndpointType
  1576. * Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
  1577. * you would make a call like this in your class's constructor:
  1578. * jsPlumb.getDefaultEndpointType().apply(this, arguments);
  1579. *
  1580. * Returns:
  1581. * the default Endpoint function used by jsPlumb.
  1582. */
  1583. this.getDefaultEndpointType = function() {
  1584. return Endpoint;
  1585. };
  1586. /*
  1587. * Function: getDefaultConnectionType
  1588. * Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
  1589. * you would make a call like this in your class's constructor:
  1590. * jsPlumb.getDefaultConnectionType().apply(this, arguments);
  1591. *
  1592. * Returns:
  1593. * the default Connection function used by jsPlumb.
  1594. */
  1595. this.getDefaultConnectionType = function() {
  1596. return Connection;
  1597. };
  1598. /*
  1599. * Function: getConnections
  1600. * Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
  1601. * the result will be a list of connections having that scope (passing in no scope at all will result in jsPlumb assuming you want the
  1602. * default scope). If multiple scopes are passed in, the return value will be a map of { scope -> [ connection... ] }.
  1603. *
  1604. * Parameters
  1605. * scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
  1606. * of connections that are in the given scope.
  1607. * options - if the argument is a JS object, you can specify a finer-grained filter:
  1608. *
  1609. * - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes.
  1610. * - *source* either a string representing an element id, or a selector. constrains the result to connections having this source.
  1611. * - *target* either a string representing an element id, or a selector. constrains the result to connections having this target.
  1612. *
  1613. */
  1614. this.getConnections = function(options) {
  1615. if (!options) {
  1616. options = {};
  1617. } else if (options.constructor == String) {
  1618. options = { "scope": options };
  1619. }
  1620. var prepareList = function(input) {
  1621. var r = [];
  1622. if (input) {
  1623. if (typeof input == 'string')
  1624. r.push(input);
  1625. else
  1626. r = input;
  1627. }
  1628. return r;
  1629. },
  1630. scope = options.scope || _currentInstance.getDefaultScope(),
  1631. scopes = prepareList(scope),
  1632. sources = prepareList(options.source),
  1633. targets = prepareList(options.target),
  1634. filter = function(list, value) {
  1635. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1636. },
  1637. results = scopes.length > 1 ? {} : [],
  1638. _addOne = function(scope, obj) {
  1639. if (scopes.length > 1) {
  1640. var ss = results[scope];
  1641. if (ss == null) {
  1642. ss = []; results[scope] = ss;
  1643. }
  1644. ss.push(obj);
  1645. } else results.push(obj);
  1646. };
  1647. for ( var i in connectionsByScope) {
  1648. if (filter(scopes, i)) {
  1649. for ( var j = 0; j < connectionsByScope[i].length; j++) {
  1650. var c = connectionsByScope[i][j];
  1651. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1652. _addOne(i, c);
  1653. }
  1654. }
  1655. }
  1656. return results;
  1657. };
  1658. /*
  1659. * Function: getAllConnections
  1660. * Gets all connections, as a map of { scope -> [ connection... ] }.
  1661. */
  1662. this.getAllConnections = function() {
  1663. return connectionsByScope;
  1664. };
  1665. /*
  1666. * Function: getDefaultScope
  1667. * Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a
  1668. * scope to an endpoint or connection allows you to support different
  1669. * types of connections in the same UI. but if you're only interested in
  1670. * one type of connection, you don't need to supply a scope. this method
  1671. * will probably be used by very few people; it's good for testing
  1672. * though.
  1673. */
  1674. this.getDefaultScope = function() {
  1675. return DEFAULT_SCOPE;
  1676. };
  1677. /*
  1678. Function: getEndpoint
  1679. Gets an Endpoint by UUID
  1680. Parameters:
  1681. uuid - the UUID for the Endpoint
  1682. Returns:
  1683. Endpoint with the given UUID, null if nothing found.
  1684. */
  1685. this.getEndpoint = _getEndpoint;
  1686. /**
  1687. * Function:getEndpoints
  1688. * Gets the list of Endpoints for a given selector, or element id.
  1689. * @param el
  1690. * @return
  1691. */
  1692. this.getEndpoints = function(el) {
  1693. return endpointsByElement[_getId(el)];
  1694. };
  1695. /*
  1696. * Gets an element's id, creating one if necessary. really only exposed
  1697. * for the lib-specific functionality to access; would be better to pass
  1698. * the current instance into the lib-specific code (even though this is
  1699. * a static call. i just don't want to expose it to the public API).
  1700. */
  1701. this.getId = _getId;
  1702. this.getOffset = function(id) {
  1703. var o = offsets[id];
  1704. return _updateOffset({elId:id});
  1705. };
  1706. this.getSelector = function(spec) {
  1707. return jsPlumb.CurrentLibrary.getSelector(spec);
  1708. };
  1709. this.getSize = function(id) {
  1710. var s = sizes[id];
  1711. if (!s) _updateOffset({elId:id});
  1712. return sizes[id];
  1713. };
  1714. this.appendElement = _appendElement;
  1715. var _hoverSuspended = false;
  1716. this.isHoverSuspended = function() { return _hoverSuspended; };
  1717. this.setHoverSuspended = function(s) { _hoverSuspended = s; };
  1718. /*
  1719. Function: hide
  1720. Sets an element's connections to be hidden.
  1721. Parameters:
  1722. el - either the id of the element, or a selector for the element.
  1723. changeEndpoints - whether not to also hide endpoints on the element. by default this is false.
  1724. Returns:
  1725. void
  1726. */
  1727. this.hide = function(el, changeEndpoints) {
  1728. _setVisible(el, "none", changeEndpoints);
  1729. };
  1730. // exposed for other objects to use to get a unique id.
  1731. this.idstamp = _idstamp;
  1732. /**
  1733. * callback from the current library to tell us to prepare ourselves (attach
  1734. * mouse listeners etc; can't do that until the library has provided a bind method)
  1735. * @return
  1736. */
  1737. this.init = function() {
  1738. if (!initialized) {
  1739. _currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run.
  1740. var bindOne = function(event) {
  1741. jsPlumb.CurrentLibrary.bind(document, event, function(e) {
  1742. if (!_currentInstance.currentlyDragging && _mouseEventsEnabled && renderMode == jsPlumb.CANVAS) {
  1743. // try connections first
  1744. for (var scope in connectionsByScope) {
  1745. var c = connectionsByScope[scope];
  1746. for (var i = 0; i < c.length; i++) {
  1747. var t = c[i].connector[event](e);
  1748. if (t) return;
  1749. }
  1750. }
  1751. for (var el in endpointsByElement) {
  1752. var ee = endpointsByElement[el];
  1753. for (var i = 0; i < ee.length; i++) {
  1754. if (ee[i].endpoint[event](e)) return;
  1755. }
  1756. }
  1757. }
  1758. });
  1759. };
  1760. bindOne("click");bindOne("dblclick");bindOne("mousemove");bindOne("mousedown");bindOne("mouseup");bindOne("contextmenu");
  1761. initialized = true;
  1762. _currentInstance.fire("ready");
  1763. }
  1764. };
  1765. this.log = log;
  1766. this.jsPlumbUIComponent = jsPlumbUIComponent;
  1767. this.EventGenerator = EventGenerator;
  1768. /*
  1769. * Creates an anchor with the given params.
  1770. *
  1771. *
  1772. * Returns: The newly created Anchor.
  1773. */
  1774. this.makeAnchor = function() {
  1775. if (arguments.length == 0) return null;
  1776. var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null;
  1777. if (!jsPlumbInstance)
  1778. throw "NO JSPLUMB SET";
  1779. // if it appears to be an anchor already...
  1780. if (specimen.compute && specimen.getOrientation) return specimen; //TODO hazy here about whether it should be added or is already added somehow.
  1781. // is it the name of an anchor type?
  1782. else if (typeof specimen == "string") {
  1783. newAnchor = jsPlumb.Anchors[arguments[0]]({elementId:elementId, jsPlumbInstance:_currentInstance});
  1784. }
  1785. // is it an array? it will be one of:
  1786. // an array of [name, params] - this defines a single anchor
  1787. // an array of arrays - this defines some dynamic anchors
  1788. // an array of numbers - this defines a single anchor.
  1789. else if (specimen.constructor == Array) {
  1790. if (specimen[0].constructor == Array || specimen[0].constructor == String) {
  1791. if (specimen.length == 2 && specimen[0].constructor == String && specimen[1].constructor == Object) {
  1792. var pp = jsPlumb.extend({elementId:elementId, jsPlumbInstance:_currentInstance}, specimen[1]);
  1793. newAnchor = jsPlumb.Anchors[specimen[0]](pp);
  1794. }
  1795. else
  1796. newAnchor = new DynamicAnchor(specimen, null, elementId);
  1797. }
  1798. else {
  1799. var anchorParams = {
  1800. x:specimen[0], y:specimen[1],
  1801. orientation : (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0,0],
  1802. offsets : (specimen.length == 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ],
  1803. elementId:elementId
  1804. };
  1805. newAnchor = new Anchor(anchorParams);
  1806. newAnchor.clone = function() { return new Anchor(anchorParams); };
  1807. }
  1808. }
  1809. if (!newAnchor.id) newAnchor.id = "anchor_" + _idstamp();
  1810. return newAnchor;
  1811. };
  1812. /**
  1813. * makes a list of anchors from the given list of types or coords, eg
  1814. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  1815. */
  1816. this.makeAnchors = function(types, elementId, jsPlumbInstance) {
  1817. var r = [];
  1818. for ( var i = 0; i < types.length; i++) {
  1819. if (typeof types[i] == "string")
  1820. r.push(jsPlumb.Anchors[types[i]]({elementId:elementId, jsPlumbInstance:jsPlumbInstance}));
  1821. else if (types[i].constructor == Array)
  1822. r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance));
  1823. }
  1824. return r;
  1825. };
  1826. /**
  1827. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  1828. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  1829. * not need to provide this - i think).
  1830. */
  1831. this.makeDynamicAnchor = function(anchors, anchorSelector) {
  1832. return new DynamicAnchor(anchors, anchorSelector);
  1833. };
  1834. /**
  1835. * Function: makeTarget
  1836. * Makes some DOM element a Connection target, allowing you to drag connections to it
  1837. * without having to register any Endpoints on it first. When a Connection is established,
  1838. * the endpoint spec that was passed in to this method is used to create a suitable
  1839. * Endpoint (the default will be used if you do not provide one).
  1840. *
  1841. * Parameters:
  1842. * el - string id or element selector for the element to make a target.
  1843. * params - JS object containing parameters:
  1844. * endpoint optional. specification of an endpoint to create when a connection is created.
  1845. * scope optional. scope for the drop zone.
  1846. * dropOptions optional. same stuff as you would pass to dropOptions of an Endpoint definition.
  1847. * deleteEndpointsOnDetach optional, defaults to true. whether or not to delete
  1848. * any Endpoints created by a connection to this target if
  1849. * the connection is subsequently detached. this will not
  1850. * remove Endpoints that have had more Connections attached
  1851. * to them after they were created.
  1852. *
  1853. *
  1854. */
  1855. var _targetEndpointDefinitions = {};
  1856. var _setEndpointPaintStylesAndAnchor = function(ep, epIndex) {
  1857. ep.paintStyle = ep.paintStyle ||
  1858. _currentInstance.Defaults.EndpointStyles[epIndex] ||
  1859. _currentInstance.Defaults.EndpointStyle ||
  1860. jsPlumb.Defaults.EndpointStyles[epIndex] ||
  1861. jsPlumb.Defaults.EndpointStyle;
  1862. ep.hoverPaintStyle = ep.hoverPaintStyle ||
  1863. _currentInstance.Defaults.EndpointHoverStyles[epIndex] ||
  1864. _currentInstance.Defaults.EndpointHoverStyle ||
  1865. jsPlumb.Defaults.EndpointHoverStyles[epIndex] ||
  1866. jsPlumb.Defaults.EndpointHoverStyle;
  1867. ep.anchor = ep.anchor ||
  1868. _currentInstance.Defaults.Anchors[epIndex] ||
  1869. _currentInstance.Defaults.Anchor ||
  1870. jsPlumb.Defaults.Anchors[epIndex] ||
  1871. jsPlumb.Defaults.Anchor;
  1872. };
  1873. this.makeTarget = function(el, params, referenceParams) {
  1874. var p = jsPlumb.extend({}, referenceParams);
  1875. jsPlumb.extend(p, params);
  1876. var jpcl = jsPlumb.CurrentLibrary,
  1877. targetScope = p.scope || _currentInstance.Defaults.Scope,
  1878. deleteEndpointsOnDetach = p.deleteEndpointsOnDetach || true,
  1879. _doOne = function(_el) {
  1880. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  1881. // and use the endpoint definition if found.
  1882. var elid = _getId(_el);
  1883. _targetEndpointDefinitions[elid] = p.endpoint;
  1884. var dropOptions = jsPlumb.extend({}, p.dropOptions || {}),
  1885. _drop = function() {
  1886. _currentInstance.currentlyDragging = false;
  1887. var draggable = _getElementObject(jpcl.getDragObject(arguments)),
  1888. id = _getAttribute(draggable, "dragId"),
  1889. // restore the original scope if necessary (issue 57)
  1890. scope = _getAttribute(draggable, "originalScope"),
  1891. jpc = floatingConnections[id],
  1892. source = jpc.endpoints[0],
  1893. _endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : {};
  1894. // use defaults for endpoint style, if not present..this either uses EndpointStyle, or EndpointStyles[1],
  1895. // if it is present, since this is a target endpoint.
  1896. // TODO - this should be a helper method. makeTarget should use it too. give it an endpoint
  1897. _setEndpointPaintStylesAndAnchor(_endpoint, 1);
  1898. // unlock the source anchor to allow it to refresh its position if necessary
  1899. source.anchor.locked = false;
  1900. if (scope) jpcl.setDragScope(draggable, scope);
  1901. // check if drop is allowed here.
  1902. var _continue = jpc.isDropAllowed(jpc.sourceId, _getId(_el), jpc.scope);
  1903. // regardless of whether the connection is ok, reconfigure the existing connection to
  1904. // point at the current info. we need this to be correct for the detach event that will follow.
  1905. // clear the source endpoint from the list to detach. we will detach this connection at this
  1906. // point, but we want to keep the source endpoint. the target is a floating endpoint and should
  1907. // be removed. TODO need to figure out whether this code can result in endpoints kicking around
  1908. // when they shouldnt be. like is this a full detach of a connection? can it be?
  1909. if (jpc.endpointsToDeleteOnDetach) {
  1910. if (source === jpc.endpointsToDeleteOnDetach[0])
  1911. jpc.endpointsToDeleteOnDetach[0] = null;
  1912. else if (source === jpc.endpointsToDeleteOnDetach[1])
  1913. jpc.endpointsToDeleteOnDetach[1] = null;
  1914. }
  1915. // reinstate any suspended endpoint; this just puts the connection back into
  1916. // a state in which it will report sensible values if someone asks it about
  1917. // its target. we're going to throw this connection away shortly so it doesnt matter
  1918. // if we manipulate it a bit.
  1919. if (jpc.suspendedEndpoint) {
  1920. jpc.targetId = jpc.suspendedEndpoint.elementId;
  1921. jpc.target = jpcl.getElementObject(jpc.suspendedEndpoint.elementId);
  1922. jpc.endpoints[1] = jpc.suspendedEndpoint;
  1923. }
  1924. if (_continue) {
  1925. // detach this connection from the source.
  1926. source.detach(jpc, false, true, true);//source.endpointWillMoveAfterConnection);
  1927. // make a new Endpoint for the target
  1928. var newEndpoint = _currentInstance.addEndpoint(_el, _endpoint);
  1929. // if the anchor has a 'positionFinder' set, then delegate to that function to find
  1930. // out where to locate the anchor.
  1931. if (newEndpoint.anchor.positionFinder != null) {
  1932. var dropPosition = jpcl.getUIPosition(arguments),
  1933. elPosition = jpcl.getOffset(_el),
  1934. elSize = jpcl.getSize(_el),
  1935. ap = newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor);
  1936. newEndpoint.anchor.x = ap[0];
  1937. newEndpoint.anchor.y = ap[1];
  1938. // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to
  1939. // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation
  1940. // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be
  1941. // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which
  1942. // the target is furthest away from the source.
  1943. }
  1944. var c = _currentInstance.connect({
  1945. source:source,
  1946. target:newEndpoint,
  1947. scope:scope,
  1948. previousConnection:jpc,
  1949. container:jpc.parent,
  1950. // 'endpointWillMoveAfterConnection' is set by the makeSource function, and it indicates that the
  1951. // given endpoint will actually transfer from the element it is currently attached to to some other
  1952. // element after a connection has been established. in that case, we do not want to fire the
  1953. // connection event, since it will have the wrong data in it; makeSource will do it for us.
  1954. // this is controlled by the 'parent' parameter on a makeSource call.
  1955. doNotFireConnectionEvent:source.endpointWillMoveAfterConnection
  1956. });
  1957. if (deleteEndpointsOnDetach)
  1958. c.endpointsToDeleteOnDetach = [ source, newEndpoint ];
  1959. }
  1960. // if not allowed to drop...
  1961. else {
  1962. // TODO this code is identical (pretty much) to what happens when a connection
  1963. // dragged from a normal endpoint is in this situation. refactor.
  1964. // is this an existing connection, and will we reattach?
  1965. if (jpc.suspendedEndpoint) {
  1966. if (source.isReattach) {
  1967. jpc.setHover(false);
  1968. jpc.floatingAnchorIndex = null;
  1969. jpc.suspendedEndpoint.addConnection(jpc);
  1970. _currentInstance.repaint(source.elementId);
  1971. }
  1972. else
  1973. source.detach(jpc, false, true, true); // otherwise, detach the connection and tell everyone about it.
  1974. }
  1975. }
  1976. };
  1977. var dropEvent = jpcl.dragEvents['drop'];
  1978. dropOptions["scope"] = dropOptions["scope"] || targetScope;
  1979. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop);
  1980. jpcl.initDroppable(_el, dropOptions, true);
  1981. };
  1982. el = _convertYUICollection(el);
  1983. var inputs = el.length && el.constructor != String ? el : [ el ];
  1984. for (var i = 0; i < inputs.length; i++) {
  1985. _doOne(_getElementObject(inputs[i]));
  1986. }
  1987. };
  1988. /**
  1989. * helper method to make a list of elements drop targets.
  1990. * @param els
  1991. * @param params
  1992. * @param referenceParams
  1993. * @return
  1994. */
  1995. this.makeTargets = function(els, params, referenceParams) {
  1996. for ( var i = 0; i < els.length; i++) {
  1997. _currentInstance.makeTarget(els[i], params, referenceParams);
  1998. }
  1999. };
  2000. /**
  2001. * Function: makeSource
  2002. * Makes some DOM element a Connection source, allowing you to drag connections from it
  2003. * without having to register any Endpoints on it first. When a Connection is established,
  2004. * the endpoint spec that was passed in to this method is used to create a suitable
  2005. * Endpoint (the default will be used if you do not provide one).
  2006. *
  2007. * Parameters:
  2008. * el - string id or element selector for the element to make a source.
  2009. * params - JS object containing parameters:
  2010. * endpoint optional. specification of an endpoint to create when a connection is created.
  2011. * parent optional. the element to add Endpoints to when a Connection is established. if you omit this,
  2012. * Endpoints will be added to 'el'.
  2013. * scope optional. scope for the connections dragged from this element.
  2014. * dragOptions optional. same stuff as you would pass to dragOptions of an Endpoint definition.
  2015. * deleteEndpointsOnDetach optional, defaults to false. whether or not to delete
  2016. * any Endpoints created by a connection from this source if
  2017. * the connection is subsequently detached. this will not
  2018. * remove Endpoints that have had more Connections attached
  2019. * to them after they were created.
  2020. *
  2021. *
  2022. */
  2023. var _sourceEndpointDefinitions = {};
  2024. this.makeSource = function(el, params, referenceParams) {
  2025. var p = jsPlumb.extend({}, referenceParams);
  2026. jsPlumb.extend(p, params);
  2027. var jpcl = jsPlumb.CurrentLibrary,
  2028. _doOne = function(_el) {
  2029. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  2030. // and use the endpoint definition if found.
  2031. var elid = _getId(_el);
  2032. _sourceEndpointDefinitions[elid] = p.endpoint || {};
  2033. var stopEvent = jpcl.dragEvents["stop"],
  2034. dragEvent = jpcl.dragEvents["drag"],
  2035. dragOptions = jsPlumb.extend({ }, p.dragOptions || _sourceEndpointDefinitions[elid].dragOptions || {}),
  2036. existingDrag = dragOptions.drag,
  2037. existingStop = dragOptions.stop,
  2038. ep = null,
  2039. endpointAddedButNoDragYet = false;
  2040. // set scope if its not set in dragOptions but was passed in in params
  2041. dragOptions["scope"] = dragOptions["scope"] || p.scope;
  2042. // make sure this method honours whatever defaults have been set for Endpoint.
  2043. _sourceEndpointDefinitions[elid].endpoint = _sourceEndpointDefinitions[elid].endpoint || _currentInstance.Defaults.Endpoints[0] || _currentInstance.Defaults.Endpoint;
  2044. // set endpoint paint styles and anchor, using either styles that are set or defaults.
  2045. _setEndpointPaintStylesAndAnchor(_sourceEndpointDefinitions[elid], 0);
  2046. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() {
  2047. if (existingDrag) existingDrag.apply(this, arguments);
  2048. endpointAddedButNoDragYet = false;
  2049. });
  2050. dragOptions[stopEvent] = function() {
  2051. if (existingStop) existingStop.apply(this, arguments);
  2052. //_currentlyDown = false;
  2053. _currentInstance.currentlyDragging = false;
  2054. if (ep.connections.length == 0)
  2055. _currentInstance.deleteEndpoint(ep);
  2056. else {
  2057. jpcl.unbind(ep.canvas, "mousedown");
  2058. // reset the anchor to the anchor that was initially provided. the one we were using to drag
  2059. // the connection was just a placeholder that was located at the place the user pressed the
  2060. // mouse button to initiate the drag.
  2061. var anchorDef = _sourceEndpointDefinitions[elid].anchor || _currentInstance.Defaults.Anchor;
  2062. ep.anchor = _currentInstance.makeAnchor(anchorDef, elid, _currentInstance);
  2063. if (p.parent) {
  2064. var parent = jpcl.getElementObject(p.parent);
  2065. if (parent) {
  2066. var currentId = ep.elementId;
  2067. ep.setElement(parent);
  2068. ep.endpointWillMoveAfterConnection = false;
  2069. _currentInstance.anchorManager.rehomeEndpoint(currentId, parent);
  2070. ep.connections[0].previousConnection = null;
  2071. _finaliseConnection(ep.connections[0]);
  2072. }
  2073. }
  2074. _currentInstance.repaint(elid);
  2075. }
  2076. };
  2077. // when the user presses the mouse, add an Endpoint
  2078. var mouseDownListener = function(e) {
  2079. // make sure we have the latest offset for this div
  2080. var myOffsetInfo = _updateOffset({elId:elid});
  2081. var x = ((e.pageX || e.page.x) - myOffsetInfo.left) / myOffsetInfo.width,
  2082. y = ((e.pageY || e.page.y) - myOffsetInfo.top) / myOffsetInfo.height,
  2083. parentX = x,
  2084. parentY = y;
  2085. // if there is a parent, the endpoint will actually be added to it now, rather than the div
  2086. // that was the source. in that case, we have to adjust the anchor position so it refers to
  2087. // the parent.
  2088. if (p.parent) {
  2089. var pEl = jsPlumb.CurrentLibrary.getElementObject(p.parent),
  2090. pId = _getId(pEl);
  2091. myOffsetInfo = _updateOffset({elId:pId});
  2092. parentX = ((e.pageX || e.page.x) - myOffsetInfo.left) / myOffsetInfo.width,
  2093. parentY = ((e.pageY || e.page.y) - myOffsetInfo.top) / myOffsetInfo.height;
  2094. }
  2095. // we need to override the anchor in here, and force 'isSource', but we don't want to mess with
  2096. // the params passed in, because after a connection is established we're going to reset the endpoint
  2097. // to have the anchor we were given.
  2098. var tempEndpointParams = {};
  2099. jsPlumb.extend(tempEndpointParams, _sourceEndpointDefinitions[elid]);
  2100. tempEndpointParams.isSource = true;
  2101. tempEndpointParams.anchor = [x,y,0,0];
  2102. tempEndpointParams.parentAnchor = [ parentX, parentY, 0, 0 ];
  2103. tempEndpointParams.dragOptions = dragOptions;
  2104. // if a parent was given we need to turn that into a "container" argument. this is, by default,
  2105. // the parent of the element we will move to, so parent of p.parent in this case. however, if
  2106. // the user has specified a 'container' on the endpoint definition or on
  2107. // the defaults, we should use that.
  2108. if (p.parent) {
  2109. var potentialParent = tempEndpointParams.container || _currentInstance.Defaults.Container;
  2110. if (potentialParent)
  2111. tempEndpointParams.container = potentialParent;
  2112. else
  2113. tempEndpointParams.container = jsPlumb.CurrentLibrary.getParent(p.parent);
  2114. }
  2115. ep = _currentInstance.addEndpoint(elid, tempEndpointParams);
  2116. endpointAddedButNoDragYet = true;
  2117. // we set this to prevent connections from firing attach events before this function has had a chance
  2118. // to move the endpoint.
  2119. ep.endpointWillMoveAfterConnection = p.parent != null;
  2120. ep.endpointWillMoveTo = p.parent ? jpcl.getElementObject(p.parent) : null;
  2121. var _delTempEndpoint = function() {
  2122. // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools
  2123. // it is fired even if dragging has occurred, in which case we would blow away a perfectly
  2124. // legitimate endpoint, were it not for this check. the flag is set after adding an
  2125. // endpoint and cleared in a drag listener we set in the dragOptions above.
  2126. if(endpointAddedButNoDragYet) {
  2127. _currentInstance.deleteEndpoint(ep);
  2128. }
  2129. };
  2130. _currentInstance.registerListener(ep.canvas, "mouseup", _delTempEndpoint);
  2131. _currentInstance.registerListener(_el, "mouseup", _delTempEndpoint);
  2132. // and then trigger its mousedown event, which will kick off a drag, which will start dragging
  2133. // a new connection from this endpoint.
  2134. jpcl.trigger(ep.canvas, "mousedown", e);
  2135. };
  2136. // register this on jsPlumb so that it can be cleared by a reset.
  2137. _currentInstance.registerListener(_el, "mousedown", mouseDownListener);
  2138. };
  2139. el = _convertYUICollection(el);
  2140. var inputs = el.length && el.constructor != String ? el : [ el ];
  2141. for (var i = 0; i < inputs.length; i++) {
  2142. _doOne(_getElementObject(inputs[i]));
  2143. }
  2144. };
  2145. /**
  2146. * helper method to make a list of elements connection sources.
  2147. * @param els
  2148. * @param params
  2149. * @param referenceParams
  2150. * @return
  2151. */
  2152. this.makeSources = function(els, params, referenceParams) {
  2153. for ( var i = 0; i < els.length; i++) {
  2154. _currentInstance.makeSource(els[i], params, referenceParams);
  2155. }
  2156. };
  2157. /*
  2158. Function: ready
  2159. Helper method to bind a function to jsPlumb's ready event.
  2160. */
  2161. this.ready = function(fn) {
  2162. _currentInstance.bind("ready", fn);
  2163. },
  2164. /*
  2165. Function: repaint
  2166. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  2167. Parameters:
  2168. el - either the id of the element or a selector representing the element.
  2169. Returns:
  2170. void
  2171. See Also:
  2172. <repaintEverything>
  2173. */
  2174. this.repaint = function(el) {
  2175. var _processElement = function(el) { _draw(_getElementObject(el)); };
  2176. // support both lists...
  2177. if (typeof el == 'object')
  2178. for ( var i = 0; i < el.length; i++) _processElement(el[i]);
  2179. else // ...and single strings.
  2180. _processElement(el);
  2181. };
  2182. /*
  2183. Function: repaintEverything
  2184. Repaints all connections.
  2185. Returns:
  2186. void
  2187. See Also:
  2188. <repaint>
  2189. */
  2190. this.repaintEverything = function() {
  2191. var timestamp = _timestamp();
  2192. for ( var elId in endpointsByElement) {
  2193. _draw(_getElementObject(elId), null, timestamp);
  2194. }
  2195. };
  2196. /*
  2197. Function: removeAllEndpoints
  2198. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  2199. Parameters:
  2200. el - either an element id, or a selector for an element.
  2201. Returns:
  2202. void
  2203. See Also:
  2204. <removeEndpoint>
  2205. */
  2206. this.removeAllEndpoints = function(el) {
  2207. var elId = _getAttribute(el, "id"),
  2208. ebe = endpointsByElement[elId];
  2209. if (ebe) {
  2210. for ( var i = 0; i < ebe.length; i++)
  2211. _currentInstance.deleteEndpoint(ebe[i]);
  2212. }
  2213. endpointsByElement[elId] = [];
  2214. };
  2215. /*
  2216. Removes every Endpoint in this instance of jsPlumb.
  2217. @deprecated use deleteEveryEndpoint instead
  2218. */
  2219. this.removeEveryEndpoint = this.deleteEveryEndpoint;
  2220. /*
  2221. Removes the given Endpoint from the given element.
  2222. @deprecated Use jsPlumb.deleteEndpoint instead (and note you dont need to supply the element. it's irrelevant).
  2223. */
  2224. this.removeEndpoint = function(el, endpoint) {
  2225. _currentInstance.deleteEndpoint(endpoint);
  2226. };
  2227. var _registeredListeners = {},
  2228. _unbindRegisteredListeners = function() {
  2229. for (var i in _registeredListeners) {
  2230. for (var j = 0; j < _registeredListeners[i].length; j++) {
  2231. var info = _registeredListeners[i][j];
  2232. jsPlumb.CurrentLibrary.unbind(info.el, info.event, info.listener);
  2233. }
  2234. }
  2235. _registeredListeners = {};
  2236. };
  2237. // internal register listener method. gives us a hook to clean things up
  2238. // with if the user calls jsPlumb.reset.
  2239. this.registerListener = function(el, type, listener) {
  2240. jsPlumb.CurrentLibrary.bind(el, type, listener);
  2241. _addToList(_registeredListeners, type, {el:el, event:type, listener:listener});
  2242. };
  2243. /*
  2244. Function:reset
  2245. Removes all endpoints and connections and clears the listener list. To keep listeners call jsPlumb.deleteEveryEndpoint instead of this.
  2246. */
  2247. this.reset = function() {
  2248. _currentInstance.deleteEveryEndpoint();
  2249. _currentInstance.clearListeners();
  2250. _unbindRegisteredListeners();
  2251. _currentInstance.anchorManager.reset();
  2252. };
  2253. /*
  2254. Function: setAutomaticRepaint
  2255. Sets/unsets automatic repaint on window resize.
  2256. Parameters:
  2257. value - whether or not to automatically repaint when the window is resized.
  2258. Returns: void
  2259. */
  2260. this.setAutomaticRepaint = function(value) {
  2261. automaticRepaint = value;
  2262. };
  2263. /*
  2264. * Function: setDefaultScope
  2265. * Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
  2266. * scope to an Endpoint or Connection allows you to support different
  2267. * types of Connections in the same UI. If you're only interested in
  2268. * one type of Connection, you don't need to supply a scope. This method
  2269. * will probably be used by very few people; it just instructs jsPlumb
  2270. * to use a different key for the default scope.
  2271. *
  2272. * Parameters:
  2273. * scope - scope to set as default.
  2274. */
  2275. this.setDefaultScope = function(scope) {
  2276. DEFAULT_SCOPE = scope;
  2277. };
  2278. /*
  2279. * Function: setDraggable
  2280. * Sets whether or not a given element is
  2281. * draggable, regardless of what any jsPlumb command may request.
  2282. *
  2283. * Parameters:
  2284. * el - either the id for the element, or a selector representing the element.
  2285. *
  2286. * Returns:
  2287. * void
  2288. */
  2289. this.setDraggable = _setDraggable;
  2290. this.setDebugLog = function(debugLog) {
  2291. log = debugLog;
  2292. };
  2293. /*
  2294. * Function: setRepaintFunction
  2295. * Sets the function to fire when the window size has changed and a repaint was fired.
  2296. *
  2297. * Parameters:
  2298. * f - Function to execute.
  2299. *
  2300. * Returns: void
  2301. */
  2302. this.setRepaintFunction = function(f) {
  2303. repaintFunction = f;
  2304. };
  2305. /*
  2306. * Function: setMouseEventsEnabled
  2307. * Sets whether or not mouse events are enabled. Default is true.
  2308. *
  2309. * Parameters:
  2310. * enabled - whether or not mouse events should be enabled.
  2311. *
  2312. * Returns:
  2313. * void
  2314. */
  2315. this.setMouseEventsEnabled = function(enabled) {
  2316. _mouseEventsEnabled = enabled;
  2317. };
  2318. /*
  2319. * Function: setSuspendDrawing
  2320. * Suspends drawing operations. This can be used when you have a lot of connections to make or endpoints to register;
  2321. * it will save you a lot of time.
  2322. */
  2323. this.setSuspendDrawing = _setSuspendDrawing;
  2324. /*
  2325. * Constant for use with the setRenderMode method
  2326. */
  2327. this.CANVAS = "canvas";
  2328. /*
  2329. * Constant for use with the setRenderMode method
  2330. */
  2331. this.SVG = "svg";
  2332. this.VML = "vml";
  2333. /*
  2334. * Function: setRenderMode
  2335. * Sets render mode: jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that
  2336. * what you asked for is not supported (and that VML is). If you asked for VML but the browser does
  2337. * not support it, jsPlumb uses SVG.
  2338. *
  2339. * Returns:
  2340. * the render mode that jsPlumb set, which of course may be different from that requested.
  2341. */
  2342. this.setRenderMode = function(mode) {
  2343. if (mode)
  2344. mode = mode.toLowerCase();
  2345. else
  2346. return;
  2347. if (mode !== jsPlumb.CANVAS && mode !== jsPlumb.SVG && mode !== jsPlumb.VML) throw new Error("render mode must be one of jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML");
  2348. // now test we actually have the capability to do this.
  2349. if (mode === jsPlumb.CANVAS && canvasAvailable)
  2350. renderMode = jsPlumb.CANVAS;
  2351. else if (mode === jsPlumb.SVG && svgAvailable)
  2352. renderMode = jsPlumb.SVG;
  2353. else if (vmlAvailable)
  2354. renderMode = jsPlumb.VML;
  2355. return renderMode;
  2356. };
  2357. this.getRenderMode = function() { return renderMode; };
  2358. /*
  2359. * Function: show
  2360. * Sets an element's connections to be visible.
  2361. *
  2362. * Parameters:
  2363. * el - either the id of the element, or a selector for the element.
  2364. * changeEndpoints - whether or not to also change the visible state of the endpoints on the element. this also has a bearing on
  2365. * other connections on those endpoints: if their other endpoint is also visible, the connections are made visible.
  2366. *
  2367. * Returns:
  2368. * void
  2369. */
  2370. this.show = function(el, changeEndpoints) {
  2371. _setVisible(el, "block", changeEndpoints);
  2372. };
  2373. /*
  2374. * Function: sizeCanvas
  2375. * Helper to size a canvas. You would typically use
  2376. * this when writing your own Connector or Endpoint implementation.
  2377. *
  2378. * Parameters:
  2379. * x - [int] x position for the Canvas origin
  2380. * y - [int] y position for the Canvas origin
  2381. * w - [int] width of the canvas
  2382. * h - [int] height of the canvas
  2383. *
  2384. * Returns:
  2385. * void
  2386. */
  2387. this.sizeCanvas = function(canvas, x, y, w, h) {
  2388. if (canvas) {
  2389. canvas.style.height = h + "px";
  2390. canvas.height = h;
  2391. canvas.style.width = w + "px";
  2392. canvas.width = w;
  2393. canvas.style.left = x + "px";
  2394. canvas.style.top = y + "px";
  2395. }
  2396. };
  2397. /**
  2398. * gets some test hooks. nothing writable.
  2399. */
  2400. this.getTestHarness = function() {
  2401. return {
  2402. endpointsByElement : endpointsByElement,
  2403. endpointCount : function(elId) {
  2404. var e = endpointsByElement[elId];
  2405. return e ? e.length : 0;
  2406. },
  2407. connectionCount : function(scope) {
  2408. scope = scope || DEFAULT_SCOPE;
  2409. var c = connectionsByScope[scope];
  2410. return c ? c.length : 0;
  2411. },
  2412. findIndex : _findIndex,
  2413. getId : _getId,
  2414. makeAnchor:self.makeAnchor,
  2415. makeDynamicAnchor:self.makeDynamicAnchor
  2416. };
  2417. };
  2418. /**
  2419. * Toggles visibility of an element's connections. kept for backwards
  2420. * compatibility
  2421. */
  2422. this.toggle = _toggleVisible;
  2423. /*
  2424. * Function: toggleVisible
  2425. * Toggles visibility of an element's Connections.
  2426. *
  2427. * Parameters:
  2428. * el - either the element's id, or a selector representing the element.
  2429. * changeEndpoints - whether or not to also toggle the endpoints on the element.
  2430. *
  2431. * Returns:
  2432. * void, but should be updated to return the current state
  2433. */
  2434. // TODO: update this method to return the current state.
  2435. this.toggleVisible = _toggleVisible;
  2436. /*
  2437. * Function: toggleDraggable
  2438. * Toggles draggability (sic?) of an element's Connections.
  2439. *
  2440. * Parameters:
  2441. * el - either the element's id, or a selector representing the element.
  2442. *
  2443. * Returns:
  2444. * The current draggable state.
  2445. */
  2446. this.toggleDraggable = _toggleDraggable;
  2447. /*
  2448. * Function: unload
  2449. * Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element.
  2450. *
  2451. * Returns:
  2452. * void
  2453. */
  2454. this.unload = function() {
  2455. // this used to do something, but it turns out that what it did was nothing.
  2456. // now it exists only for backwards compatibility.
  2457. };
  2458. /*
  2459. * Helper method to wrap an existing function with one of
  2460. * your own. This is used by the various implementations to wrap event
  2461. * callbacks for drag/drop etc; it allows jsPlumb to be transparent in
  2462. * its handling of these things. If a user supplies their own event
  2463. * callback, for anything, it will always be called.
  2464. */
  2465. this.wrap = _wrap;
  2466. this.addListener = this.bind;
  2467. var adjustForParentOffsetAndScroll = function(xy, el) {
  2468. var offsetParent = null, result = xy;
  2469. if (el.tagName.toLowerCase() === "svg" && el.parentNode) {
  2470. offsetParent = el.parentNode;
  2471. }
  2472. else if (el.offsetParent) {
  2473. offsetParent = el.offsetParent;
  2474. }
  2475. if (offsetParent != null) {
  2476. var po = offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(offsetParent),
  2477. so = offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : {left:offsetParent.scrollLeft, top:offsetParent.scrollTop};
  2478. // i thought it might be cool to do this:
  2479. // lastReturnValue[0] = lastReturnValue[0] - offsetParent.offsetLeft + offsetParent.scrollLeft;
  2480. // lastReturnValue[1] = lastReturnValue[1] - offsetParent.offsetTop + offsetParent.scrollTop;
  2481. // but i think it ignores margins. my reasoning was that it's quicker to not hand off to some underlying
  2482. // library.
  2483. result[0] = xy[0] - po.left + so.left;
  2484. result[1] = xy[1] - po.top + so.top;
  2485. }
  2486. return result;
  2487. };
  2488. /**
  2489. * 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
  2490. * 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"),
  2491. * 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
  2492. * creation of Anchors without user intervention.
  2493. */
  2494. var Anchor = function(params) {
  2495. var self = this;
  2496. this.x = params.x || 0;
  2497. this.y = params.y || 0;
  2498. this.elementId = params.elementId;
  2499. var orientation = params.orientation || [ 0, 0 ];
  2500. var lastTimestamp = null, lastReturnValue = null;
  2501. this.offsets = params.offsets || [ 0, 0 ];
  2502. self.timestamp = null;
  2503. this.compute = function(params) {
  2504. var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
  2505. if (timestamp && timestamp === self.timestamp)
  2506. return lastReturnValue;
  2507. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  2508. // adjust loc if there is an offsetParent
  2509. lastReturnValue = adjustForParentOffsetAndScroll(lastReturnValue, element.canvas);
  2510. self.timestamp = timestamp;
  2511. return lastReturnValue;
  2512. };
  2513. this.getOrientation = function(_endpoint) { return orientation; };
  2514. this.equals = function(anchor) {
  2515. if (!anchor) return false;
  2516. var ao = anchor.getOrientation();
  2517. var o = this.getOrientation();
  2518. return this.x == anchor.x && this.y == anchor.y
  2519. && this.offsets[0] == anchor.offsets[0]
  2520. && this.offsets[1] == anchor.offsets[1]
  2521. && o[0] == ao[0] && o[1] == ao[1];
  2522. };
  2523. this.getCurrentLocation = function() { return lastReturnValue; };
  2524. };
  2525. /**
  2526. * An Anchor that floats. its orientation is computed dynamically from
  2527. * its position relative to the anchor it is floating relative to. It is used when creating
  2528. * a connection through drag and drop.
  2529. *
  2530. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  2531. */
  2532. var FloatingAnchor = function(params) {
  2533. // this is the anchor that this floating anchor is referenced to for
  2534. // purposes of calculating the orientation.
  2535. var ref = params.reference,
  2536. // the canvas this refers to.
  2537. refCanvas = params.referenceCanvas,
  2538. size = _getSize(_getElementObject(refCanvas)),
  2539. // these are used to store the current relative position of our
  2540. // anchor wrt the reference anchor. they only indicate
  2541. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  2542. // values are written by the compute method, and read
  2543. // by the getOrientation method.
  2544. xDir = 0, yDir = 0,
  2545. // temporary member used to store an orientation when the floating
  2546. // anchor is hovering over another anchor.
  2547. orientation = null,
  2548. _lastResult = null;
  2549. // set these to 0 each; they are used by certain types of connectors in the loopback case,
  2550. // when the connector is trying to clear the element it is on. but for floating anchor it's not
  2551. // very important.
  2552. this.x = 0; this.y = 0;
  2553. this.isFloating = true;
  2554. this.compute = function(params) {
  2555. var xy = params.xy, element = params.element,
  2556. 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.
  2557. // adjust loc if there is an offsetParent
  2558. result = adjustForParentOffsetAndScroll(result, element.canvas);
  2559. _lastResult = result;
  2560. return result;
  2561. };
  2562. this.getOrientation = function(_endpoint) {
  2563. if (orientation) return orientation;
  2564. else {
  2565. var o = ref.getOrientation(_endpoint);
  2566. // here we take into account the orientation of the other
  2567. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  2568. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  2569. return [ Math.abs(o[0]) * xDir * -1,
  2570. Math.abs(o[1]) * yDir * -1 ];
  2571. }
  2572. };
  2573. /**
  2574. * notification the endpoint associated with this anchor is hovering
  2575. * over another anchor; we want to assume that anchor's orientation
  2576. * for the duration of the hover.
  2577. */
  2578. this.over = function(anchor) {
  2579. orientation = anchor.getOrientation();
  2580. };
  2581. /**
  2582. * notification the endpoint associated with this anchor is no
  2583. * longer hovering over another anchor; we should resume calculating
  2584. * orientation as we normally do.
  2585. */
  2586. this.out = function() { orientation = null; };
  2587. this.getCurrentLocation = function() { return _lastResult; };
  2588. };
  2589. /*
  2590. * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
  2591. * through at compute time to find the one that is located closest to
  2592. * the center of the target element, and returns that Anchor's compute
  2593. * method result. this causes endpoints to follow each other with
  2594. * respect to the orientation of their target elements, which is a useful
  2595. * feature for some applications.
  2596. *
  2597. */
  2598. var DynamicAnchor = function(anchors, anchorSelector, elementId) {
  2599. this.isSelective = true;
  2600. this.isDynamic = true;
  2601. var _anchors = [], self = this,
  2602. _convert = function(anchor) {
  2603. return anchor.constructor == Anchor ? anchor: _currentInstance.makeAnchor(anchor, elementId, _currentInstance);
  2604. };
  2605. for (var i = 0; i < anchors.length; i++)
  2606. _anchors[i] = _convert(anchors[i]);
  2607. this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
  2608. this.getAnchors = function() { return _anchors; };
  2609. this.locked = false;
  2610. var _curAnchor = _anchors.length > 0 ? _anchors[0] : null,
  2611. _curIndex = _anchors.length > 0 ? 0 : -1,
  2612. self = this,
  2613. // helper method to calculate the distance between the centers of the two elements.
  2614. _distance = function(anchor, cx, cy, xy, wh) {
  2615. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
  2616. return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
  2617. },
  2618. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  2619. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  2620. // xy - xy loc of the anchor's element
  2621. // wh - anchor's element's dimensions
  2622. // txy - xy loc of the element of the other anchor in the connection
  2623. // twh - dimensions of the element of the other anchor in the connection.
  2624. // anchors - the list of selectable anchors
  2625. _anchorSelector = anchorSelector || function(xy, wh, txy, twh, anchors) {
  2626. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  2627. var minIdx = -1, minDist = Infinity;
  2628. for ( var i = 0; i < anchors.length; i++) {
  2629. var d = _distance(anchors[i], cx, cy, xy, wh);
  2630. if (d < minDist) {
  2631. minIdx = i + 0;
  2632. minDist = d;
  2633. }
  2634. }
  2635. return anchors[minIdx];
  2636. };
  2637. this.compute = function(params) {
  2638. var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
  2639. // if anchor is locked or an opposite element was not given, we
  2640. // maintain our state. anchor will be locked
  2641. // if it is the source of a drag and drop.
  2642. if (self.locked || txy == null || twh == null)
  2643. return _curAnchor.compute(params);
  2644. else
  2645. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  2646. _curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
  2647. self.x = _curAnchor.x;
  2648. self.y = _curAnchor.y;
  2649. return _curAnchor.compute(params);
  2650. };
  2651. this.getCurrentLocation = function() {
  2652. return _curAnchor != null ? _curAnchor.getCurrentLocation() : null;
  2653. };
  2654. this.getOrientation = function(_endpoint) { return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ]; };
  2655. this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
  2656. this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
  2657. };
  2658. /*
  2659. manages anchors for all elements.
  2660. */
  2661. // "continuous" anchors: anchors that pick their location based on how many connections the given element has.
  2662. // this requires looking at a lot more elements than normal - anything that has had a Continuous anchor applied has
  2663. // to be recalculated. so this manager is used as a reference point. the first time, with a new timestamp, that
  2664. // a continuous anchor is asked to compute, it calls this guy. or maybe, even, this guy gets called somewhere else
  2665. // and compute only ever returns pre-computed values. either way, this is the central point, and we want it to
  2666. // be called as few times as possible.
  2667. var continuousAnchors = {},
  2668. continuousAnchorLocations = {},
  2669. continuousAnchorOrientations = {},
  2670. Orientation = { HORIZONTAL : "horizontal", VERTICAL : "vertical", DIAGONAL : "diagonal", IDENTITY:"identity" },
  2671. // TODO this functions uses a crude method of determining orientation between two elements.
  2672. // 'diagonal' should be chosen when the angle of the line between the two centers is around
  2673. // one of 45, 135, 225 and 315 degrees. maybe +- 15 degrees.
  2674. calculateOrientation = function(sourceId, targetId, sd, td) {
  2675. if (sourceId === targetId) return {
  2676. orientation:Orientation.IDENTITY,
  2677. a:["top", "top"]
  2678. };
  2679. var theta = Math.atan2((td.centery - sd.centery) , (td.centerx - sd.centerx)),
  2680. theta2 = Math.atan2((sd.centery - td.centery) , (sd.centerx - td.centerx)),
  2681. h = ((sd.left <= td.left && sd.right >= td.left) || (sd.left <= td.right && sd.right >= td.right) ||
  2682. (sd.left <= td.left && sd.right >= td.right) || (td.left <= sd.left && td.right >= sd.right)),
  2683. v = ((sd.top <= td.top && sd.bottom >= td.top) || (sd.top <= td.bottom && sd.bottom >= td.bottom) ||
  2684. (sd.top <= td.top && sd.bottom >= td.bottom) || (td.top <= sd.top && td.bottom >= sd.bottom));
  2685. if (! (h || v)) {
  2686. var a = null, rls = false, rrs = false, sortValue = null;
  2687. if (td.left > sd.left && td.top > sd.top)
  2688. a = ["right", "top"];
  2689. else if (td.left > sd.left && sd.top > td.top)
  2690. a = [ "top", "left"];
  2691. else if (td.left < sd.left && td.top < sd.top)
  2692. a = [ "top", "right"];
  2693. else if (td.left < sd.left && td.top > sd.top)
  2694. a = ["left", "top" ];
  2695. return { orientation:Orientation.DIAGONAL, a:a, theta:theta, theta2:theta2 };
  2696. }
  2697. else if (h) return {
  2698. orientation:Orientation.HORIZONTAL,
  2699. a:sd.top < td.top ? ["bottom", "top"] : ["top", "bottom"],
  2700. theta:theta, theta2:theta2
  2701. }
  2702. else return {
  2703. orientation:Orientation.VERTICAL,
  2704. a:sd.left < td.left ? ["right", "left"] : ["left", "right"],
  2705. theta:theta, theta2:theta2
  2706. }
  2707. },
  2708. placeAnchorsOnLine = function(desc, elementDimensions, elementPosition,
  2709. connections, horizontal, otherMultiplier, reverse) {
  2710. var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
  2711. for (var i = 0; i < connections.length; i++) {
  2712. var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
  2713. if (reverse)
  2714. val = elementDimensions[horizontal ? 0 : 1] - val;
  2715. var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
  2716. dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
  2717. a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
  2718. }
  2719. return a;
  2720. },
  2721. standardEdgeSort = function(a, b) { return a[0] > b[0] ? 1 : -1 },
  2722. currySort = function(reverseAngles) {
  2723. return function(a,b) {
  2724. var r = true;
  2725. if (reverseAngles) {
  2726. if (a[0][0] < b[0][0])
  2727. r = true;
  2728. else
  2729. r = a[0][1] > b[0][1];
  2730. }
  2731. else {
  2732. if (a[0][0] > b[0][0])
  2733. r= true;
  2734. else
  2735. r =a[0][1] > b[0][1];
  2736. }
  2737. return r === false ? -1 : 1;
  2738. };
  2739. },
  2740. leftSort = function(a,b) {
  2741. // first get adjusted values
  2742. var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
  2743. p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
  2744. if (p1 > p2) return 1;
  2745. else return a[0][1] > b[0][1] ? 1 : -1;
  2746. },
  2747. edgeSortFunctions = {
  2748. "top":standardEdgeSort,
  2749. "right":currySort(true),
  2750. "bottom":currySort(true),
  2751. "left":leftSort
  2752. },
  2753. _sortHelper = function(_array, _fn) {
  2754. return _array.sort(_fn);
  2755. },
  2756. placeAnchors = function(elementId, _anchorLists) {
  2757. var sS = sizes[elementId], sO = offsets[elementId],
  2758. placeSomeAnchors = function(desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier) {
  2759. if (unsortedConnections.length > 0) {
  2760. var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
  2761. //sc = unsortedConnections.sort(edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
  2762. reverse = desc === "right" || desc === "top",
  2763. anchors = placeAnchorsOnLine(desc, elementDimensions,
  2764. elementPosition, sc,
  2765. isHorizontal, otherMultiplier, reverse );
  2766. // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
  2767. var _setAnchorLocation = function(endpoint, anchorPos) {
  2768. var a = adjustForParentOffsetAndScroll([anchorPos[0], anchorPos[1]], endpoint.canvas);
  2769. continuousAnchorLocations[endpoint.id] = [ a[0], a[1], anchorPos[2], anchorPos[3] ];
  2770. };
  2771. for (var i = 0; i < anchors.length; i++) {
  2772. var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
  2773. if (weAreSource)
  2774. _setAnchorLocation(c.endpoints[0], anchors[i]);
  2775. else if (weAreTarget)
  2776. _setAnchorLocation(c.endpoints[1], anchors[i]);
  2777. }
  2778. }
  2779. };
  2780. placeSomeAnchors("bottom", sS, [sO.left,sO.top], _anchorLists.bottom, true, 1);
  2781. placeSomeAnchors("top", sS, [sO.left,sO.top], _anchorLists.top, true, 0);
  2782. placeSomeAnchors("left", sS, [sO.left,sO.top], _anchorLists.left, false, 0);
  2783. placeSomeAnchors("right", sS, [sO.left,sO.top], _anchorLists.right, false, 1);
  2784. },
  2785. AnchorManager = function() {
  2786. var _amEndpoints = {},
  2787. endpointConnectionsByElementId = {},
  2788. continuousAnchorConnectionsByElementId = {},
  2789. continuousAnchorEndpoints = [],
  2790. self = this,
  2791. anchorLists = {};
  2792. this.reset = function() {
  2793. endpointConnectionsByElementId = {};
  2794. continuousAnchorConnectionsByElementId = {};
  2795. continuousAnchorEndpoints = [];
  2796. anchorLists = {};
  2797. };
  2798. this.newConnection = function(conn) {
  2799. var sourceId = conn.sourceId, targetId = conn.targetId,
  2800. ep = conn.endpoints,
  2801. doRegisterTarget = true,
  2802. registerConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) {
  2803. if (otherAnchor.constructor == DynamicAnchor || otherAnchor.constructor == Anchor) {
  2804. _addToList(endpointConnectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor == DynamicAnchor]);
  2805. }
  2806. else {
  2807. // continuous. if they are the same element, just assign the same anchor
  2808. // to both.
  2809. if (sourceId == targetId) {
  2810. // remove the target endpoint's canvas. we dont need it.
  2811. jsPlumb.CurrentLibrary.removeElement(ep[1].canvas);
  2812. doRegisterTarget = false;
  2813. }
  2814. _addToList(continuousAnchorConnectionsByElementId, elId, c);
  2815. }
  2816. };
  2817. registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
  2818. if (doRegisterTarget)
  2819. registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
  2820. };
  2821. this.connectionDetached = function(connInfo) {
  2822. var sourceId = connInfo.sourceId,
  2823. targetId = connInfo.targetId,
  2824. ep = connInfo.connection.endpoints,
  2825. removeConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) {
  2826. if (otherAnchor.constructor == FloatingAnchor) {
  2827. // no-op
  2828. }
  2829. else if (otherAnchor.constructor == DynamicAnchor || otherAnchor.constructor == Anchor) {
  2830. var _conns = endpointConnectionsByElementId[elId];
  2831. if (_conns) {
  2832. _removeWithFunction(_conns, function(e) { return e[0].id == c.id; });
  2833. }
  2834. }
  2835. else // continuous.
  2836. _removeWithFunction(continuousAnchorConnectionsByElementId[elId], function(_c) {
  2837. return _c.id == c.id;
  2838. });
  2839. };
  2840. removeConnection(1, ep[1], ep[1].anchor, sourceId, connInfo.connection);
  2841. removeConnection(0, ep[0], ep[0].anchor, targetId, connInfo.connection);
  2842. // remove from anchorLists
  2843. var sEl = connInfo.connection.sourceId,
  2844. tEl = connInfo.connection.targetId,
  2845. sE = connInfo.connection.endpoints[0].id,
  2846. tE = connInfo.connection.endpoints[1].id,
  2847. _remove = function(list, eId) {
  2848. if (list) { // transient anchors dont get entries in this list.
  2849. var f = function(e) { return e[4] == eId; };
  2850. _removeWithFunction(list["top"], f);
  2851. _removeWithFunction(list["left"], f);
  2852. _removeWithFunction(list["bottom"], f);
  2853. _removeWithFunction(list["right"], f);
  2854. }
  2855. };
  2856. _remove(anchorLists[sEl], sE);
  2857. _remove(anchorLists[tEl], tE);
  2858. self.redraw(sEl);
  2859. self.redraw(tEl);
  2860. };
  2861. this.add = function(endpoint, elementId) {
  2862. _addToList(_amEndpoints, elementId, endpoint);
  2863. };
  2864. this.get = function(elementId) {
  2865. return {
  2866. "standard":endpointConnectionsByElementId[elementId] || [],
  2867. "continuous":continuousAnchorConnectionsByElementId[elementId] || [],
  2868. "endpoints":_amEndpoints[elementId],
  2869. "continuousAnchorEndpoints":continuousAnchorEndpoints
  2870. };
  2871. };
  2872. this.deleteEndpoint = function(endpoint) {
  2873. var cIdx = _findIndex(continuousAnchorEndpoints, endpoint);
  2874. if (cIdx > -1)
  2875. continuousAnchorEndpoints.splice(cIdx, 1);
  2876. else
  2877. _removeWithFunction(_amEndpoints[endpoint.elementId], function(e) {
  2878. return e.id == endpoint.id;
  2879. });
  2880. };
  2881. this.clearFor = function(elementId) {
  2882. delete _amEndpoints[elementId];
  2883. _amEndpoints[elementId] = [];
  2884. };
  2885. // updates the given anchor list by either updating an existing anchor's info, or adding it. this function
  2886. // also removes the anchor from its previous list, if the edge it is on has changed.
  2887. // all connections found along the way (those that are connected to one of the faces this function
  2888. // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
  2889. // them wthout having to calculate anything else about them.
  2890. var _updateAnchorList = function(lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
  2891. // first try to find the exact match, but keep track of the first index of a matching element id along the way.s
  2892. var exactIdx = -1,
  2893. firstMatchingElIdx = -1,
  2894. endpoint = conn.endpoints[idx],
  2895. endpointId = endpoint.id,
  2896. oIdx = [1,0][idx],
  2897. values = [ [ theta, order ], conn, aBoolean, otherElId, endpointId ],
  2898. listToAddTo = lists[edgeId],
  2899. listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null;
  2900. if (listToRemoveFrom) {
  2901. var rIdx = _findWithFunction(listToRemoveFrom, function(e) { return e[4] == endpointId });
  2902. if (rIdx != -1) {
  2903. listToRemoveFrom.splice(rIdx, 1);
  2904. // get all connections from this list
  2905. for (var i = 0; i < listToRemoveFrom.length; i++) {
  2906. _addWithFunction(connsToPaint, listToRemoveFrom[i][1], function(c) { return c.id == listToRemoveFrom[i][1].id });
  2907. _addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function(e) { return e.id == listToRemoveFrom[i][1].endpoints[idx].id });
  2908. }
  2909. }
  2910. }
  2911. for (var i = 0; i < listToAddTo.length; i++) {
  2912. if (idx == 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx == -1)
  2913. firstMatchingElIdx = i;
  2914. _addWithFunction(connsToPaint, listToAddTo[i][1], function(c) { return c.id == listToAddTo[i][1].id });
  2915. _addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function(e) { return e.id == listToAddTo[i][1].endpoints[idx].id });
  2916. }
  2917. if (exactIdx != -1) {
  2918. listToAddTo[exactIdx] = values;
  2919. }
  2920. else {
  2921. var insertIdx = reverse ? firstMatchingElIdx != -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
  2922. listToAddTo.splice(insertIdx, 0, values);
  2923. }
  2924. // store this for next time.
  2925. endpoint._continuousAnchorEdge = edgeId;
  2926. };
  2927. this.redraw = function(elementId, ui, timestamp) {
  2928. // get all the endpoints for this element
  2929. var ep = _amEndpoints[elementId] || [],
  2930. endpointConnections = endpointConnectionsByElementId[elementId] || [],
  2931. continuousAnchorConnections = continuousAnchorConnectionsByElementId[elementId] || [],
  2932. connectionsToPaint = [],
  2933. endpointsToPaint = [],
  2934. anchorsToUpdate = [];
  2935. timestamp = timestamp || _timestamp();
  2936. _updateOffset( { elId : elementId, offset : ui, recalc : false, timestamp : timestamp });
  2937. // valid for one paint cycle.
  2938. var myOffset = offsets[elementId],
  2939. myWH = sizes[elementId],
  2940. orientationCache = {};
  2941. // actually, first we should compute the orientation of this element to all other elements to which
  2942. // this element is connected with a continuous anchor (whether both ends of the connection have
  2943. // a continuous anchor or just one)
  2944. for (var i = 0; i < continuousAnchorConnections.length; i++) {
  2945. var conn = continuousAnchorConnections[i],
  2946. sourceId = conn.sourceId,
  2947. targetId = conn.targetId,
  2948. oKey = sourceId + "_" + targetId,
  2949. oKey2 = targetId + "_" + sourceId,
  2950. o = orientationCache[oKey],
  2951. td = _getCachedData(targetId),
  2952. sd = _getCachedData(sourceId),
  2953. oIdx = conn.sourceId == elementId ? 1 : 0;
  2954. if (!anchorLists[sourceId]) anchorLists[sourceId] = { top:[], right:[], bottom:[], left:[] };
  2955. if (!anchorLists[targetId]) anchorLists[targetId] = { top:[], right:[], bottom:[], left:[] };
  2956. if (targetId == sourceId) {
  2957. // here we may want to improve this by somehow determining the face we'd like
  2958. // to put the connector on. ideally, when drawing, the face should be calculated
  2959. // by determining which face is closest to the point at which the mouse button
  2960. // was released. for now, we're putting it on the top face.
  2961. _updateAnchorList(anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint)
  2962. }
  2963. else {
  2964. if (!o) {
  2965. o = calculateOrientation(sourceId, targetId, sd.o, td.o);
  2966. orientationCache[oKey] = o;
  2967. // this would be a performance enhancement, but the computed angles need to be clamped to
  2968. //the (-PI/2 -> PI/2) range in order for the sorting to work properly.
  2969. /* orientationCache[oKey2] = {
  2970. orientation:o.orientation,
  2971. a:[o.a[1], o.a[0]],
  2972. theta:o.theta + Math.PI,
  2973. theta2:o.theta2 + Math.PI
  2974. };*/
  2975. }
  2976. _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
  2977. _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
  2978. }
  2979. _addWithFunction(anchorsToUpdate, sourceId, function(a) { return a === sourceId; });
  2980. _addWithFunction(anchorsToUpdate, targetId, function(a) { return a === targetId; });
  2981. _addWithFunction(connectionsToPaint, conn, function(c) { return c.id == conn.id; });
  2982. _addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function(e) { return e.id == conn.endpoints[oIdx].id; });
  2983. }
  2984. // now place all the continuous anchors we need to;
  2985. for (var i = 0; i < anchorsToUpdate.length; i++) {
  2986. placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]);
  2987. }
  2988. // now that continuous anchors have been placed, paint all the endpoints for this element
  2989. // TODO performance: add the endpoint ids to a temp array, and then when iterating in the next
  2990. // loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way.
  2991. for (var i = 0; i < ep.length; i++) {
  2992. ep[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  2993. }
  2994. // ... and any other endpoints we came across as a result of the continuous anchors.
  2995. for (var i = 0; i < endpointsToPaint.length; i++) {
  2996. endpointsToPaint[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  2997. }
  2998. // paint all the standard and "dynamic connections", which are connections whose other anchor is
  2999. // static and therefore does need to be recomputed; we make sure that happens only one time.
  3000. for (var i = 0; i < endpointConnections.length; i++) {
  3001. var otherEndpoint = endpointConnections[i][1];
  3002. if (otherEndpoint.anchor.constructor == DynamicAnchor) {
  3003. otherEndpoint.paint({ elementWithPrecedence:elementId });
  3004. _addWithFunction(connectionsToPaint, endpointConnections[i][0], function(c) { return c.id == endpointConnections[i][0].id; });
  3005. // all the connections for the other endpoint now need to be repainted
  3006. for (var k = 0; k < otherEndpoint.connections.length; k++) {
  3007. if (otherEndpoint.connections[k] !== endpointConnections[i][0])
  3008. _addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function(c) { return c.id == otherEndpoint.connections[k].id; });
  3009. }
  3010. } else if (otherEndpoint.anchor.constructor == Anchor) {
  3011. _addWithFunction(connectionsToPaint, endpointConnections[i][0], function(c) { return c.id == endpointConnections[i][0].id; });
  3012. }
  3013. }
  3014. // paint current floating connection for this element, if there is one.
  3015. var fc = floatingConnections[elementId];
  3016. if (fc)
  3017. fc.paint({timestamp:timestamp, recalc:false, elId:elementId});
  3018. // paint all the connections
  3019. for (var i = 0; i < connectionsToPaint.length; i++) {
  3020. connectionsToPaint[i].paint({elId:elementId, timestamp:timestamp, recalc:false});
  3021. }
  3022. };
  3023. this.rehomeEndpoint = function(currentId, element) {
  3024. var eps = _amEndpoints[currentId] || [], //,
  3025. elementId = _currentInstance.getId(element);
  3026. for (var i = 0; i < eps.length; i++) {
  3027. self.add(eps[i], elementId);
  3028. }
  3029. eps.splice(0, eps.length);
  3030. };
  3031. };
  3032. _currentInstance.anchorManager = new AnchorManager();
  3033. _currentInstance.continuousAnchorFactory = {
  3034. get:function(params) {
  3035. var existing = continuousAnchors[params.elementId];
  3036. if (!existing) {
  3037. existing = {
  3038. type:"Continuous",
  3039. compute : function(params) {
  3040. return continuousAnchorLocations[params.element.id] || [0,0];
  3041. },
  3042. getCurrentLocation : function(endpoint) {
  3043. return continuousAnchorLocations[endpoint.id] || [0,0];
  3044. },
  3045. getOrientation : function(endpoint) {
  3046. return continuousAnchorOrientations[endpoint.id] || [0,0];
  3047. },
  3048. isDynamic : true,
  3049. isContinuous : true
  3050. };
  3051. continuousAnchors[params.elementId] = existing;
  3052. }
  3053. return existing;
  3054. }
  3055. };
  3056. /*
  3057. * Class: Connection
  3058. * The connecting line between two Endpoints.
  3059. */
  3060. /*
  3061. * Function: Connection
  3062. * Connection constructor.
  3063. *
  3064. * Parameters:
  3065. * source - either an element id, a selector for an element, or an Endpoint.
  3066. * target - either an element id, a selector for an element, or an Endpoint
  3067. * scope - scope descriptor for this connection. optional.
  3068. * container - optional id or selector instructing jsPlumb where to attach all the elements it creates for this connection. you should read the documentation for a full discussion of this.
  3069. * endpoint - Optional. Endpoint definition to use for both ends of the connection.
  3070. * endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  3071. * endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
  3072. * endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  3073. * paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
  3074. * 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).
  3075. * overlays - Optional array of Overlay definitions to appear on this Connection.
  3076. * drawEndpoints - if false, instructs jsPlumb to not draw the endpoints for this Connection. Be careful with this: it only really works when you tell jsPlumb to attach elements to the document body. Read the documentation for a full discussion of this.
  3077. */
  3078. var Connection = function(params) {
  3079. var self = this, visible = true;
  3080. self.idPrefix = "_jsplumb_c_";
  3081. self.defaultLabelLocation = 0.5;
  3082. self.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
  3083. this.parent = params.parent;
  3084. overlayCapableJsPlumbUIComponent.apply(this, arguments);
  3085. // ************** get the source and target and register the connection. *******************
  3086. /**
  3087. Function:isVisible
  3088. Returns whether or not the Connection is currently visible.
  3089. */
  3090. this.isVisible = function() { return visible; };
  3091. /**
  3092. Function: setVisible
  3093. Sets whether or not the Connection should be visible.
  3094. Parameters:
  3095. visible - boolean indicating desired visible state.
  3096. */
  3097. this.setVisible = function(v) {
  3098. visible = v;
  3099. if (self.connector && self.connector.canvas) self.connector.canvas.style.display = v ? "block" : "none";
  3100. };
  3101. /**
  3102. Property: source
  3103. The source element for this Connection.
  3104. */
  3105. this.source = _getElementObject(params.source);
  3106. /**
  3107. Property:target
  3108. The target element for this Connection.
  3109. */
  3110. this.target = _getElementObject(params.target);
  3111. // sourceEndpoint and targetEndpoint override source/target, if they are present. but
  3112. // source is not overridden if the Endpoint has declared it is not the final target of a connection;
  3113. // instead we use the source that the Endpoint declares will be the final source element.
  3114. if (params.sourceEndpoint) {
  3115. this.source = params.sourceEndpoint.endpointWillMoveTo || params.sourceEndpoint.getElement();
  3116. }
  3117. if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
  3118. // if a new connection is the result of moving some existing connection, params.previousConnection
  3119. // will have that Connection in it. listeners for the jsPlumbConnection event can look for that
  3120. // member and take action if they need to.
  3121. self.previousConnection = params.previousConnection;
  3122. var _cost = params.cost;
  3123. self.getCost = function() { return _cost; };
  3124. self.setCost = function(c) { _cost = c; };
  3125. var _bidirectional = params.bidirectional === true;
  3126. self.isBidirectional = function() { return _bidirectional; };
  3127. /*
  3128. * Property: sourceId
  3129. * Id of the source element in the connection.
  3130. */
  3131. this.sourceId = _getAttribute(this.source, "id");
  3132. /*
  3133. * Property: targetId
  3134. * Id of the target element in the connection.
  3135. */
  3136. this.targetId = _getAttribute(this.target, "id");
  3137. /**
  3138. * implementation of abstract method in EventGenerator
  3139. * @return list of attached elements. in our case, a list of Endpoints.
  3140. */
  3141. this.getAttachedElements = function() {
  3142. return self.endpoints;
  3143. };
  3144. /*
  3145. * Property: scope
  3146. * Optional scope descriptor for the connection.
  3147. */
  3148. 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.
  3149. /*
  3150. * Property: endpoints
  3151. * Array of [source, target] Endpoint objects.
  3152. */
  3153. this.endpoints = [];
  3154. this.endpointStyles = [];
  3155. // wrapped the main function to return null if no input given. this lets us cascade defaults properly.
  3156. var _makeAnchor = function(anchorParams, elementId) {
  3157. if (anchorParams)
  3158. return _currentInstance.makeAnchor(anchorParams, elementId, _currentInstance);
  3159. },
  3160. prepareEndpoint = function(existing, index, params, element, elementId, connectorPaintStyle, connectorHoverPaintStyle) {
  3161. if (existing) {
  3162. self.endpoints[index] = existing;
  3163. existing.addConnection(self);
  3164. } else {
  3165. if (!params.endpoints) params.endpoints = [ null, null ];
  3166. var ep = params.endpoints[index]
  3167. || params.endpoint
  3168. || _currentInstance.Defaults.Endpoints[index]
  3169. || jsPlumb.Defaults.Endpoints[index]
  3170. || _currentInstance.Defaults.Endpoint
  3171. || jsPlumb.Defaults.Endpoint;
  3172. if (!params.endpointStyles) params.endpointStyles = [ null, null ];
  3173. if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
  3174. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  3175. // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
  3176. if (es.fillStyle == null && connectorPaintStyle != null)
  3177. es.fillStyle = connectorPaintStyle.strokeStyle;
  3178. // TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
  3179. //*
  3180. if (es.outlineColor == null && connectorPaintStyle != null)
  3181. es.outlineColor = connectorPaintStyle.outlineColor;
  3182. if (es.outlineWidth == null && connectorPaintStyle != null)
  3183. es.outlineWidth = connectorPaintStyle.outlineWidth;
  3184. //*/
  3185. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _currentInstance.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
  3186. // endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
  3187. if (connectorHoverPaintStyle != null) {
  3188. if (ehs == null) ehs = {};
  3189. if (ehs.fillStyle == null) {
  3190. ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
  3191. }
  3192. }
  3193. var a = params.anchors ? params.anchors[index] :
  3194. params.anchor ? params.anchor :
  3195. _makeAnchor(_currentInstance.Defaults.Anchors[index], elementId) ||
  3196. _makeAnchor(jsPlumb.Defaults.Anchors[index], elementId) ||
  3197. _makeAnchor(_currentInstance.Defaults.Anchor, elementId) ||
  3198. _makeAnchor(jsPlumb.Defaults.Anchor, elementId),
  3199. u = params.uuids ? params.uuids[index] : null,
  3200. e = _newEndpoint({
  3201. paintStyle : es,
  3202. hoverPaintStyle:ehs,
  3203. endpoint : ep,
  3204. connections : [ self ],
  3205. uuid : u,
  3206. anchor : a,
  3207. source : element,
  3208. container:params.container,
  3209. reattach:params.reattach,
  3210. detachable:params.detachable
  3211. });
  3212. self.endpoints[index] = e;
  3213. if (params.drawEndpoints === false) e.setVisible(false, true, true);
  3214. return e;
  3215. }
  3216. };
  3217. var eS = prepareEndpoint(params.sourceEndpoint,
  3218. 0,
  3219. params,
  3220. self.source,
  3221. self.sourceId,
  3222. params.paintStyle,
  3223. params.hoverPaintStyle);
  3224. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  3225. // if there were no endpoints supplied and the source element is the target element, we will reuse the source
  3226. // endpoint that was just created.
  3227. var existingTargetEndpoint = ((self.sourceId == self.targetId) && params.targetEndpoint == null) ? eS : params.targetEndpoint,
  3228. eT = prepareEndpoint(existingTargetEndpoint,
  3229. 1,
  3230. params,
  3231. self.target,
  3232. self.targetId,
  3233. params.paintStyle,
  3234. params.hoverPaintStyle);
  3235. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  3236. // if scope not set, set it to be the scope for the source endpoint.
  3237. if (!this.scope) this.scope = this.endpoints[0].scope;
  3238. // if delete endpoints on detach, keep a record of just exactly which endpoints they are.
  3239. if (params.deleteEndpointsOnDetach)
  3240. self.endpointsToDeleteOnDetach = [eS, eT];
  3241. var _detachable = _currentInstance.Defaults.ConnectionsDetachable;
  3242. if (params.detachable === false) _detachable = false;
  3243. if(self.endpoints[0].connectionsDetachable === false) _detachable = false;
  3244. if(self.endpoints[1].connectionsDetachable === false) _detachable = false;
  3245. // inherit connectin cost if it was set on source endpoint
  3246. if (_cost == null) _cost = self.endpoints[0].getConnectionCost();
  3247. // inherit bidirectional flag if set no source endpoint
  3248. if (params.bidirectional == null) _bidirectional = self.endpoints[0].areConnectionsBidirectional();
  3249. /*
  3250. Function: isDetachable
  3251. Returns whether or not this connection can be detached from its target/source endpoint. by default this
  3252. is false; use it in conjunction with the 'reattach' parameter.
  3253. */
  3254. this.isDetachable = function() {
  3255. return _detachable === true;
  3256. };
  3257. /*
  3258. Function: setDetachable
  3259. Sets whether or not this connection is detachable.
  3260. */
  3261. this.setDetachable = function(detachable) {
  3262. _detachable = detachable === true;
  3263. };
  3264. // merge all the parameters objects into the connection. parameters set
  3265. // on the connection take precedence; then target endpoint params, then
  3266. // finally source endpoint params.
  3267. // TODO jsPlumb.extend could be made to take more than two args, and it would
  3268. // apply the second through nth args in order.
  3269. var _p = jsPlumb.extend({}, this.endpoints[0].getParameters());
  3270. jsPlumb.extend(_p, this.endpoints[1].getParameters());
  3271. jsPlumb.extend(_p, self.getParameters());
  3272. self.setParameters(_p);
  3273. // override setHover to pass it down to the underlying connector
  3274. var _sh = self.setHover;
  3275. self.setHover = function() {
  3276. self.connector.setHover.apply(self.connector, arguments);
  3277. _sh.apply(self, arguments);
  3278. };
  3279. var _internalHover = function(state) {
  3280. if (_connectionBeingDragged == null) {
  3281. self.setHover(state, false);
  3282. }
  3283. };
  3284. /*
  3285. * Function: setConnector
  3286. * Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method - the same
  3287. * thing that you would set as the 'connector' property on a jsPlumb.connect call.
  3288. *
  3289. * Parameters:
  3290. * connector - Connector definition
  3291. */
  3292. this.setConnector = function(connector, doNotRepaint) {
  3293. if (self.connector != null) _removeElements(self.connector.getDisplayElements(), self.parent);
  3294. var connectorArgs = {
  3295. _jsPlumb:self._jsPlumb,
  3296. parent:params.parent,
  3297. cssClass:params.cssClass,
  3298. container:params.container,
  3299. tooltip:self.tooltip
  3300. };
  3301. if (connector.constructor == String)
  3302. this.connector = new jsPlumb.Connectors[renderMode][connector](connectorArgs); // lets you use a string as shorthand.
  3303. else if (connector.constructor == Array)
  3304. this.connector = new jsPlumb.Connectors[renderMode][connector[0]](jsPlumb.extend(connector[1], connectorArgs));
  3305. self.canvas = self.connector.canvas;
  3306. // binds mouse listeners to the current connector.
  3307. _bindListeners(self.connector, self, _internalHover);
  3308. if (!doNotRepaint) self.repaint();
  3309. };
  3310. /*
  3311. * Property: connector
  3312. * The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
  3313. */
  3314. self.setConnector(this.endpoints[0].connector ||
  3315. this.endpoints[1].connector ||
  3316. params.connector ||
  3317. _currentInstance.Defaults.Connector ||
  3318. jsPlumb.Defaults.Connector, true);
  3319. this.setPaintStyle(this.endpoints[0].connectorStyle ||
  3320. this.endpoints[1].connectorStyle ||
  3321. params.paintStyle ||
  3322. _currentInstance.Defaults.PaintStyle ||
  3323. jsPlumb.Defaults.PaintStyle, true);
  3324. this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
  3325. this.endpoints[1].connectorHoverStyle ||
  3326. params.hoverPaintStyle ||
  3327. _currentInstance.Defaults.HoverPaintStyle ||
  3328. jsPlumb.Defaults.HoverPaintStyle, true);
  3329. this.paintStyleInUse = this.paintStyle;
  3330. this.moveParent = function(newParent) {
  3331. var jpcl = jsPlumb.CurrentLibrary, curParent = jpcl.getParent(self.connector.canvas);
  3332. jpcl.removeElement(self.connector.canvas, curParent);
  3333. jpcl.appendElement(self.connector.canvas, newParent);
  3334. if (self.connector.bgCanvas) {
  3335. jpcl.removeElement(self.connector.bgCanvas, curParent);
  3336. jpcl.appendElement(self.connector.bgCanvas, newParent);
  3337. }
  3338. // this only applies for DOMOverlays
  3339. for (var i = 0; i < self.overlays.length; i++) {
  3340. if (self.overlays[i].isAppendedAtTopLevel) {
  3341. jpcl.removeElement(self.overlays[i].canvas, curParent);
  3342. jpcl.appendElement(self.overlays[i].canvas, newParent);
  3343. if (self.overlays[i].reattachListeners)
  3344. self.overlays[i].reattachListeners(self.connector);
  3345. }
  3346. }
  3347. if (self.connector.reattachListeners) // this is for SVG/VML; change an element's parent and you have to reinit its listeners.
  3348. self.connector.reattachListeners(); // the Canvas implementation doesn't have to care about this
  3349. };
  3350. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3351. /*
  3352. * Function: bind
  3353. * Bind to an event on the Connection.
  3354. *
  3355. * Parameters:
  3356. * event - the event to bind. Available events on a Connection are:
  3357. * - *click* : notification that a Connection was clicked.
  3358. * - *dblclick* : notification that a Connection was double clicked.
  3359. * - *mouseenter* : notification that the mouse is over a Connection.
  3360. * - *mouseexit* : notification that the mouse exited a Connection.
  3361. *
  3362. * callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
  3363. */
  3364. /*
  3365. * Function: setPaintStyle
  3366. * Sets the Connection's paint style and then repaints the Connection.
  3367. *
  3368. * Parameters:
  3369. * style - Style to use.
  3370. */
  3371. /*
  3372. * Function: setHoverPaintStyle
  3373. * Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
  3374. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  3375. * it. This is because people will most likely want to change just one thing when hovering, say the
  3376. * color for example, but leave the rest of the appearance the same.
  3377. *
  3378. * Parameters:
  3379. * style - Style to use when the mouse is hovering.
  3380. * doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
  3381. */
  3382. /*
  3383. * Function: setHover
  3384. * Sets/unsets the hover state of this Connection.
  3385. *
  3386. * Parameters:
  3387. * hover - hover state boolean
  3388. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  3389. */
  3390. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3391. _updateOffset( { elId : this.sourceId });
  3392. _updateOffset( { elId : this.targetId });
  3393. // paint the endpoints
  3394. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId],
  3395. otherOffset = offsets[this.targetId],
  3396. otherWH = sizes[this.targetId],
  3397. initialTimestamp = _timestamp(),
  3398. anchorLoc = this.endpoints[0].anchor.compute( {
  3399. xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
  3400. elementId:this.endpoints[0].elementId,
  3401. txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1],
  3402. timestamp:initialTimestamp
  3403. });
  3404. this.endpoints[0].paint( { anchorLoc : anchorLoc, timestamp:initialTimestamp });
  3405. anchorLoc = this.endpoints[1].anchor.compute( {
  3406. xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
  3407. elementId:this.endpoints[1].elementId,
  3408. txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0],
  3409. timestamp:initialTimestamp
  3410. });
  3411. this.endpoints[1].paint({ anchorLoc : anchorLoc, timestamp:initialTimestamp });
  3412. /*
  3413. * Paints the Connection. Not exposed for public usage.
  3414. *
  3415. * Parameters:
  3416. * elId - Id of the element that is in motion.
  3417. * ui - current library's event system ui object (present if we came from a drag to get here).
  3418. * recalc - whether or not to recalculate all anchors etc before painting.
  3419. * timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
  3420. */
  3421. this.paint = function(params) {
  3422. params = params || {};
  3423. var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp,
  3424. // if the moving object is not the source we must transpose the two references.
  3425. swap = false,
  3426. tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
  3427. tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  3428. var sourceInfo = _updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp }),
  3429. targetInfo = _updateOffset( { elId : tId, timestamp : timestamp }); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  3430. var sE = this.endpoints[sIdx], tE = this.endpoints[tIdx],
  3431. sAnchorP = sE.anchor.getCurrentLocation(sE),
  3432. tAnchorP = tE.anchor.getCurrentLocation(tE);
  3433. /* paint overlays*/
  3434. var maxSize = 0;
  3435. for ( var i = 0; i < self.overlays.length; i++) {
  3436. var o = self.overlays[i];
  3437. if (o.isVisible()) maxSize = Math.max(maxSize, o.computeMaxSize(self.connector));
  3438. }
  3439. var dim = this.connector.compute(sAnchorP, tAnchorP,
  3440. this.endpoints[sIdx], this.endpoints[tIdx],
  3441. this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor,
  3442. self.paintStyleInUse.lineWidth, maxSize,
  3443. sourceInfo,
  3444. targetInfo);
  3445. self.connector.paint(dim, self.paintStyleInUse);
  3446. /* paint overlays*/
  3447. for ( var i = 0; i < self.overlays.length; i++) {
  3448. var o = self.overlays[i];
  3449. if (o.isVisible) self.overlayPlacements[i] = o.draw(self.connector, self.paintStyleInUse, dim);
  3450. }
  3451. };
  3452. /*
  3453. * Function: repaint
  3454. * Repaints the Connection.
  3455. */
  3456. this.repaint = function(params) {
  3457. params = params || {};
  3458. var recalc = !(params.recalc === false);
  3459. this.paint({ elId : this.sourceId, recalc : recalc, timestamp:params.timestamp });
  3460. };
  3461. // just to make sure the UI gets initialised fully on all browsers.
  3462. self.repaint();
  3463. };
  3464. // ENDPOINT HELPER FUNCTIONS
  3465. var _makeConnectionDragHandler = function(placeholder) {
  3466. var stopped = false;
  3467. return {
  3468. drag : function() {
  3469. if (stopped) return true;
  3470. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments),
  3471. el = placeholder.element;
  3472. if (el) {
  3473. jsPlumb.CurrentLibrary.setOffset(el, _ui);
  3474. _draw(_getElementObject(el), _ui);
  3475. }
  3476. },
  3477. stopDrag : function() {
  3478. stopped = true;
  3479. }
  3480. };
  3481. };
  3482. var _makeFloatingEndpoint = function(paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement) {
  3483. var floatingAnchor = new FloatingAnchor( { reference : referenceAnchor, referenceCanvas : referenceCanvas });
  3484. //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
  3485. // adding the floating endpoint as a droppable. that makes more sense anyway!
  3486. return _newEndpoint({ paintStyle : paintStyle, endpoint : endpoint, anchor : floatingAnchor, source : sourceElement, scope:"__floating" });
  3487. };
  3488. /**
  3489. * creates a placeholder div for dragging purposes, adds it to the DOM, and pre-computes its offset. then returns
  3490. * both the element id and a selector for the element.
  3491. */
  3492. var _makeDraggablePlaceholder = function(placeholder, parent) {
  3493. var n = document.createElement("div");
  3494. n.style.position = "absolute";
  3495. var placeholderDragElement = _getElementObject(n);
  3496. _appendElement(n, parent);
  3497. var id = _getId(placeholderDragElement);
  3498. _updateOffset( { elId : id });
  3499. // create and assign an id, and initialize the offset.
  3500. placeholder.id = id;
  3501. placeholder.element = placeholderDragElement;
  3502. };
  3503. /*
  3504. * Class: Endpoint
  3505. *
  3506. * Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
  3507. * to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
  3508. * actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
  3509. * do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
  3510. * 'target' Endpoints for Connections.
  3511. *
  3512. *
  3513. */
  3514. /*
  3515. * Function: Endpoint
  3516. *
  3517. * Endpoint constructor.
  3518. *
  3519. * Parameters:
  3520. * 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.
  3521. * 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 } ].
  3522. * paintStyle - endpoint style, a js object. may be null.
  3523. * hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
  3524. * source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
  3525. * canvas - canvas element to use. may be, and most often is, null.
  3526. * container - optional id or selector instructing jsPlumb where to attach the element it creates for this endpoint. you should read the documentation for a full discussion of this.
  3527. * connections - optional list of Connections to configure the Endpoint with.
  3528. * isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
  3529. * maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
  3530. * dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
  3531. * connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
  3532. * connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
  3533. * 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", { curviness:160 } ].
  3534. * connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
  3535. * isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
  3536. * 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.
  3537. * 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.
  3538. */
  3539. var Endpoint = function(params) {
  3540. var self = this;
  3541. self.idPrefix = "_jsplumb_e_";
  3542. self.defaultLabelLocation = [ 0.5, 0.5 ];
  3543. self.defaultOverlayKeys = ["Overlays", "EndpointOverlays"];
  3544. this.parent = params.parent;
  3545. overlayCapableJsPlumbUIComponent.apply(this, arguments);
  3546. params = params || {};
  3547. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3548. /*
  3549. * Function: bind
  3550. * Bind to an event on the Endpoint.
  3551. *
  3552. * Parameters:
  3553. * event - the event to bind. Available events on an Endpoint are:
  3554. * - *click* : notification that a Endpoint was clicked.
  3555. * - *dblclick* : notification that a Endpoint was double clicked.
  3556. * - *mouseenter* : notification that the mouse is over a Endpoint.
  3557. * - *mouseexit* : notification that the mouse exited a Endpoint.
  3558. *
  3559. * callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
  3560. */
  3561. /*
  3562. * Function: setPaintStyle
  3563. * Sets the Endpoint's paint style and then repaints the Endpoint.
  3564. *
  3565. * Parameters:
  3566. * style - Style to use.
  3567. */
  3568. /*
  3569. * Function: setHoverPaintStyle
  3570. * Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
  3571. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  3572. * it. This is because people will most likely want to change just one thing when hovering, say the
  3573. * color for example, but leave the rest of the appearance the same.
  3574. *
  3575. * Parameters:
  3576. * style - Style to use when the mouse is hovering.
  3577. * doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
  3578. */
  3579. /*
  3580. * Function: setHover
  3581. * Sets/unsets the hover state of this Endpoint.
  3582. *
  3583. * Parameters:
  3584. * hover - hover state boolean
  3585. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  3586. */
  3587. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3588. var visible = true;
  3589. /*
  3590. Function: isVisible
  3591. Returns whether or not the Endpoint is currently visible.
  3592. */
  3593. this.isVisible = function() { return visible; };
  3594. /*
  3595. Function: setVisible
  3596. Sets whether or not the Endpoint is currently visible.
  3597. Parameters:
  3598. visible - whether or not the Endpoint should be visible.
  3599. doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
  3600. doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
  3601. */
  3602. this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  3603. visible = v;
  3604. if (self.canvas) self.canvas.style.display = v ? "block" : "none";
  3605. if (!doNotChangeConnections) {
  3606. for (var i = 0; i < self.connections.length; i++) {
  3607. self.connections[i].setVisible(v);
  3608. if (!doNotNotifyOtherEndpoint) {
  3609. var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
  3610. // only change the other endpoint if this is its only connection.
  3611. if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
  3612. }
  3613. }
  3614. }
  3615. };
  3616. var _element = params.source, _uuid = params.uuid, floatingEndpoint = null, inPlaceCopy = null;
  3617. if (_uuid) endpointsByUUID[_uuid] = self;
  3618. var _elementId = _getAttribute(_element, "id");
  3619. this.elementId = _elementId;
  3620. this.element = _element;
  3621. var _connectionCost = params.connectionCost;
  3622. this.getConnectionCost = function() { return _connectionCost; };
  3623. this.setConnectionCost = function(c) {
  3624. _connectionCost = c;
  3625. };
  3626. var _connectionsBidirectional = params.connectionsBidirectional === true;
  3627. this.areConnectionsBidirectional = function() { return _connectionsBidirectional; };
  3628. this.setConnectionsBidirectional = function(b) { _connectionsBidirectional = b; };
  3629. self.anchor = params.anchor ? _currentInstance.makeAnchor(params.anchor, _elementId, _currentInstance) : params.anchors ? _currentInstance.makeAnchor(params.anchors, _elementId, _currentInstance) : _currentInstance.makeAnchor("TopCenter", _elementId, _currentInstance);
  3630. // ANCHOR MANAGER
  3631. if (!params._transient) // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted.
  3632. _currentInstance.anchorManager.add(self, _elementId);
  3633. var _endpoint = params.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot",
  3634. endpointArgs = {
  3635. _jsPlumb:self._jsPlumb,
  3636. parent:params.parent,
  3637. container:params.container,
  3638. tooltip:params.tooltip,
  3639. connectorTooltip:params.connectorTooltip,
  3640. endpoint:self
  3641. };
  3642. if (_endpoint.constructor == String)
  3643. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint](endpointArgs);
  3644. else if (_endpoint.constructor == Array) {
  3645. endpointArgs = jsPlumb.extend(_endpoint[1], endpointArgs);
  3646. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint[0]](endpointArgs);
  3647. }
  3648. else {
  3649. _endpoint = _endpoint.clone();
  3650. }
  3651. // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
  3652. // and the clone is left in its place while the original one goes off on a magical journey.
  3653. // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by
  3654. // the whole world.
  3655. var argsForClone = jsPlumb.extend({}, endpointArgs);
  3656. _endpoint.clone = function() {
  3657. var o = new Object();
  3658. _endpoint.constructor.apply(o, [argsForClone]);
  3659. return o;
  3660. };
  3661. self.endpoint = _endpoint;
  3662. self.type = self.endpoint.type;
  3663. // override setHover to pass it down to the underlying endpoint
  3664. var _sh = self.setHover;
  3665. self.setHover = function() {
  3666. self.endpoint.setHover.apply(self.endpoint, arguments);
  3667. _sh.apply(self, arguments);
  3668. };
  3669. // endpoint delegates to first connection for hover, if there is one.
  3670. var internalHover = function(state) {
  3671. if (self.connections.length > 0)
  3672. self.connections[0].setHover(state, false);
  3673. else
  3674. self.setHover(state);
  3675. };
  3676. // bind listeners from endpoint to self, with the internal hover function defined above.
  3677. _bindListeners(self.endpoint, self, internalHover);
  3678. this.setPaintStyle(params.paintStyle ||
  3679. params.style ||
  3680. _currentInstance.Defaults.EndpointStyle ||
  3681. jsPlumb.Defaults.EndpointStyle, true);
  3682. this.setHoverPaintStyle(params.hoverPaintStyle ||
  3683. _currentInstance.Defaults.EndpointHoverStyle ||
  3684. jsPlumb.Defaults.EndpointHoverStyle, true);
  3685. this.paintStyleInUse = this.paintStyle;
  3686. this.connectorStyle = params.connectorStyle;
  3687. this.connectorHoverStyle = params.connectorHoverStyle;
  3688. this.connectorOverlays = params.connectorOverlays;
  3689. this.connector = params.connector;
  3690. this.connectorTooltip = params.connectorTooltip;
  3691. this.isSource = params.isSource || false;
  3692. this.isTarget = params.isTarget || false;
  3693. var _maxConnections = params.maxConnections || _currentInstance.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
  3694. this.getAttachedElements = function() {
  3695. return self.connections;
  3696. };
  3697. /*
  3698. * Property: canvas
  3699. * The Endpoint's Canvas.
  3700. */
  3701. this.canvas = this.endpoint.canvas;
  3702. /*
  3703. * Property: connections
  3704. * List of Connections this Endpoint is attached to.
  3705. */
  3706. this.connections = params.connections || [];
  3707. /*
  3708. * Property: scope
  3709. * Scope descriptor for this Endpoint.
  3710. */
  3711. this.scope = params.scope || DEFAULT_SCOPE;
  3712. this.timestamp = null;
  3713. self.isReattach = params.reattach || false;
  3714. self.connectionsDetachable = _currentInstance.Defaults.ConnectionsDetachable;
  3715. if (params.connectionsDetachable === false || params.detachable === false)
  3716. self.connectionsDetachable = false;
  3717. var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
  3718. this.computeAnchor = function(params) {
  3719. return self.anchor.compute(params);
  3720. };
  3721. /*
  3722. * Function: addConnection
  3723. * Adds a Connection to this Endpoint.
  3724. *
  3725. * Parameters:
  3726. * connection - the Connection to add.
  3727. */
  3728. this.addConnection = function(connection) {
  3729. self.connections.push(connection);
  3730. };
  3731. /*
  3732. * Function: detach
  3733. * Detaches the given Connection from this Endpoint.
  3734. *
  3735. * Parameters:
  3736. * connection - the Connection to detach.
  3737. * ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
  3738. */
  3739. this.detach = function(connection, ignoreTarget, forceDetach, fireEvent) {
  3740. //var idx = _findIndex(self.connections, connection), actuallyDetached = false;
  3741. var idx = _findWithFunction(self.connections, function(c) { return c.id == connection.id}),
  3742. actuallyDetached = false;
  3743. fireEvent = (fireEvent !== false);
  3744. if (idx >= 0) {
  3745. // 1. does the connection have a before detach (note this also checks jsPlumb's bound
  3746. // detach handlers; but then Endpoint's check will, too, hmm.)
  3747. if (forceDetach || connection._forceDetach || connection.isDetachable() || connection.isDetachAllowed(connection)) {
  3748. // get the target endpoint
  3749. var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
  3750. // it would be nice to check with both endpoints that it is ok to detach. but
  3751. // for this we'll have to get a bit fancier: right now if you use the same beforeDetach
  3752. // interceptor for two endpoints (which is kind of common, because it's part of the
  3753. // endpoint definition), then it gets fired twice. so in fact we need to loop through
  3754. // each beforeDetach and see if it returns false, at which point we exit. but if it
  3755. // returns true, we have to check the next one. however we need to track which ones
  3756. // have already been run, and not run them again.
  3757. if (forceDetach || connection._forceDetach || (self.isDetachAllowed(connection) /*&& t.isDetachAllowed(connection)*/)) {
  3758. self.connections.splice(idx, 1);
  3759. // this avoids a circular loop
  3760. if (!ignoreTarget) {
  3761. t.detach(connection, true, forceDetach);
  3762. // check connection to see if we want to delete the endpoints associated with it.
  3763. // we only detach those that have just this connection; this scenario is most
  3764. // likely if we got to this bit of code because it is set by the methods that
  3765. // create their own endpoints, like .connect or .makeTarget. the user is
  3766. // not likely to have interacted with those endpoints.
  3767. if (connection.endpointsToDeleteOnDetach){
  3768. for (var i = 0; i < connection.endpointsToDeleteOnDetach.length; i++) {
  3769. var cde = connection.endpointsToDeleteOnDetach[i];
  3770. if (cde && cde.connections.length == 0)
  3771. _currentInstance.deleteEndpoint(cde);
  3772. }
  3773. }
  3774. }
  3775. _removeElements(connection.connector.getDisplayElements(), connection.parent);
  3776. _removeWithFunction(connectionsByScope[connection.scope], function(c) {
  3777. return c.id == connection.id;
  3778. });
  3779. actuallyDetached = true;
  3780. var doFireEvent = (!ignoreTarget && fireEvent)
  3781. fireDetachEvent(connection, doFireEvent);
  3782. }
  3783. }
  3784. }
  3785. return actuallyDetached;
  3786. };
  3787. /*
  3788. * Function: detachAll
  3789. * Detaches all Connections this Endpoint has.
  3790. *
  3791. * Parameters:
  3792. * fireEvent - whether or not to fire the detach event. defaults to false.
  3793. */
  3794. this.detachAll = function(fireEvent) {
  3795. while (self.connections.length > 0) {
  3796. self.detach(self.connections[0], false, true, fireEvent);
  3797. }
  3798. };
  3799. /*
  3800. * Function: detachFrom
  3801. * Removes any connections from this Endpoint that are connected to the given target endpoint.
  3802. *
  3803. * Parameters:
  3804. * targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
  3805. * fireEvent - whether or not to fire the detach event. defaults to false.
  3806. */
  3807. this.detachFrom = function(targetEndpoint, fireEvent) {
  3808. var c = [];
  3809. for ( var i = 0; i < self.connections.length; i++) {
  3810. if (self.connections[i].endpoints[1] == targetEndpoint
  3811. || self.connections[i].endpoints[0] == targetEndpoint) {
  3812. c.push(self.connections[i]);
  3813. }
  3814. }
  3815. for ( var i = 0; i < c.length; i++) {
  3816. if (self.detach(c[i], false, true, fireEvent))
  3817. c[i].setHover(false, false);
  3818. }
  3819. };
  3820. /*
  3821. * Function: detachFromConnection
  3822. * Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
  3823. *
  3824. * Parameters:
  3825. * connection - Connection to detach from.
  3826. */
  3827. this.detachFromConnection = function(connection) {
  3828. var idx = _findIndex(self.connections, connection);
  3829. if (idx >= 0) {
  3830. self.connections.splice(idx, 1);
  3831. }
  3832. };
  3833. /*
  3834. * Function: getElement
  3835. * Returns the DOM element this Endpoint is attached to.
  3836. */
  3837. this.getElement = function() {
  3838. return _element;
  3839. };
  3840. /*
  3841. * Function: setElement
  3842. * Sets the DOM element this Endpoint is attached to.
  3843. */
  3844. this.setElement = function(el) {
  3845. // TODO possibly have this object take charge of moving the UI components into the appropriate
  3846. // parent. this is used only by makeSource right now, and that function takes care of
  3847. // moving the UI bits and pieces. however it would s
  3848. var parentId = _getId(el);
  3849. // remove the endpoint from the list for the current endpoint's element
  3850. _removeWithFunction(endpointsByElement[_elementId], function(e) {
  3851. return e.id == self.id;
  3852. });
  3853. _element = _getElementObject(el);
  3854. _elementId = _getId(_element);
  3855. self.elementId = _elementId;
  3856. // need to get the new parent now
  3857. var newParentElement = _getParentFromParams({source:parentId}),
  3858. curParent = jpcl.getParent(self.canvas);
  3859. jpcl.removeElement(self.canvas, curParent);
  3860. jpcl.appendElement(self.canvas, newParentElement);
  3861. // now move connection(s)...i would expect there to be only one but we will iterate.
  3862. for (var i = 0; i < self.connections.length; i++) {
  3863. self.connections[i].moveParent(newParentElement);
  3864. self.connections[i].sourceId = _elementId;
  3865. self.connections[i].source = _element;
  3866. }
  3867. _addToList(endpointsByElement, parentId, self);
  3868. _currentInstance.repaint(parentId);
  3869. };
  3870. /*
  3871. * Function: getUuid
  3872. * Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
  3873. */
  3874. this.getUuid = function() {
  3875. return _uuid;
  3876. };
  3877. /**
  3878. * private but must be exposed.
  3879. */
  3880. this.makeInPlaceCopy = function() {
  3881. return _newEndpoint( {
  3882. anchor : self.anchor,
  3883. source : _element,
  3884. paintStyle : this.paintStyle,
  3885. endpoint : _endpoint,
  3886. _transient:true,
  3887. scope:self.scope
  3888. });
  3889. };
  3890. /*
  3891. * Function: isConnectedTo
  3892. * Returns whether or not this endpoint is connected to the given Endpoint.
  3893. *
  3894. * Parameters:
  3895. * endpoint - Endpoint to test.
  3896. */
  3897. this.isConnectedTo = function(endpoint) {
  3898. var found = false;
  3899. if (endpoint) {
  3900. for ( var i = 0; i < self.connections.length; i++) {
  3901. if (self.connections[i].endpoints[1] == endpoint) {
  3902. found = true;
  3903. break;
  3904. }
  3905. }
  3906. }
  3907. return found;
  3908. };
  3909. /**
  3910. * private but needs to be exposed.
  3911. */
  3912. this.isFloating = function() {
  3913. return floatingEndpoint != null;
  3914. };
  3915. /**
  3916. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  3917. */
  3918. this.connectorSelector = function() {
  3919. var candidate = self.connections[0];
  3920. if (self.isTarget && candidate) return candidate;
  3921. else {
  3922. return (self.connections.length < _maxConnections) || _maxConnections == -1 ? null : candidate;
  3923. }
  3924. };
  3925. /*
  3926. * Function: isFull
  3927. * Returns whether or not the Endpoint can accept any more Connections.
  3928. */
  3929. this.isFull = function() {
  3930. return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
  3931. };
  3932. /*
  3933. * Function: setDragAllowedWhenFull
  3934. * Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
  3935. * which you're going to provide some other way of breaking connections, if you need to break them at all. This property
  3936. * is by default true; use it in conjunction with the 'reattach' option on a connect call.
  3937. *
  3938. * Parameters:
  3939. * allowed - whether drag is allowed or not when the Endpoint is full.
  3940. */
  3941. this.setDragAllowedWhenFull = function(allowed) {
  3942. dragAllowedWhenFull = allowed;
  3943. };
  3944. /*
  3945. * Function: setStyle
  3946. * 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.
  3947. * TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
  3948. * setStyle and deprecate it if so.
  3949. *
  3950. * Parameters:
  3951. * style - Style object to set, for example {fillStyle:"blue"}.
  3952. *
  3953. * @deprecated use setPaintStyle instead.
  3954. */
  3955. this.setStyle = self.setPaintStyle;
  3956. /**
  3957. * a deep equals check. everything must match, including the anchor,
  3958. * styles, everything. TODO: finish Endpoint.equals
  3959. */
  3960. this.equals = function(endpoint) {
  3961. return this.anchor.equals(endpoint.anchor);
  3962. };
  3963. // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
  3964. // or no connection to it is found, we return the first connection in our list.
  3965. var findConnectionToUseForDynamicAnchor = function(elementWithPrecedence) {
  3966. var idx = 0;
  3967. if (elementWithPrecedence != null) {
  3968. for (var i = 0; i < self.connections.length; i++) {
  3969. if (self.connections[i].sourceId == elementWithPrecedence || self.connections[i].targetId == elementWithPrecedence) {
  3970. idx = i;
  3971. break;
  3972. }
  3973. }
  3974. }
  3975. return self.connections[idx];
  3976. };
  3977. /*
  3978. * Function: paint
  3979. * Paints the Endpoint, recalculating offset and anchor positions if necessary. This does NOT paint
  3980. * any of the Endpoint's connections.
  3981. *
  3982. * Parameters:
  3983. * 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.
  3984. * canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
  3985. * connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
  3986. */
  3987. this.paint = function(params) {
  3988. params = params || {};
  3989. var timestamp = params.timestamp,
  3990. recalc = !(params.recalc === false);
  3991. if (!timestamp || self.timestamp !== timestamp) {
  3992. _updateOffset({ elId:_elementId, timestamp:timestamp, recalc:recalc });
  3993. var xy = params.offset || offsets[_elementId];
  3994. if(xy) {
  3995. var ap = params.anchorPoint,connectorPaintStyle = params.connectorPaintStyle;
  3996. if (ap == null) {
  3997. var wh = params.dimensions || sizes[_elementId];
  3998. if (xy == null || wh == null) {
  3999. _updateOffset( { elId : _elementId, timestamp : timestamp });
  4000. xy = offsets[_elementId];
  4001. wh = sizes[_elementId];
  4002. }
  4003. var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
  4004. if (recalc && self.anchor.isDynamic && self.connections.length > 0) {
  4005. var c = findConnectionToUseForDynamicAnchor(params.elementWithPrecedence),
  4006. oIdx = c.endpoints[0] == self ? 1 : 0,
  4007. oId = oIdx == 0 ? c.sourceId : c.targetId,
  4008. oOffset = offsets[oId], oWH = sizes[oId];
  4009. anchorParams.txy = [ oOffset.left, oOffset.top ];
  4010. anchorParams.twh = oWH;
  4011. anchorParams.tElement = c.endpoints[oIdx];
  4012. }
  4013. ap = self.anchor.compute(anchorParams);
  4014. }
  4015. var d = _endpoint.compute(ap, self.anchor.getOrientation(_endpoint), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
  4016. _endpoint.paint(d, self.paintStyleInUse, self.anchor);
  4017. self.timestamp = timestamp;
  4018. /* paint overlays*/
  4019. for ( var i = 0; i < self.overlays.length; i++) {
  4020. var o = self.overlays[i];
  4021. if (o.isVisible) self.overlayPlacements[i] = o.draw(self.endpoint, self.paintStyleInUse, d);
  4022. }
  4023. }
  4024. }
  4025. };
  4026. this.repaint = this.paint;
  4027. /**
  4028. * @deprecated
  4029. */
  4030. this.removeConnection = this.detach; // backwards compatibility
  4031. // is this a connection source? we make it draggable and have the
  4032. // drag listener maintain a connection with a floating endpoint.
  4033. if (jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  4034. var placeholderInfo = {
  4035. id:null,
  4036. element:null
  4037. },
  4038. jpc = null,
  4039. existingJpc = false,
  4040. existingJpcParams = null,
  4041. _dragHandler = _makeConnectionDragHandler(placeholderInfo);
  4042. var start = function() {
  4043. // drag might have started on an endpoint that is not actually a source, but which has
  4044. // one or more connections.
  4045. jpc = self.connectorSelector();
  4046. var _continue = true;
  4047. // if no connection and we're not a source, return.
  4048. if (jpc == null && !params.isSource) _continue = false;
  4049. // otherwise if we're full and not allowed to drag, also return false.
  4050. if (params.isSource && self.isFull() && !dragAllowedWhenFull) _continue = false;
  4051. // if the connection was setup as not detachable (or one of its endpoints
  4052. // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
  4053. // is set to false...
  4054. if (jpc != null && !jpc.isDetachable()) _continue = false;
  4055. if (_continue === false) {
  4056. // this is for mootools and yui. returning false from this causes jquery to stop drag.
  4057. // the events are wrapped in both mootools and yui anyway, but i don't think returning
  4058. // false from the start callback would stop a drag.
  4059. if (jsPlumb.CurrentLibrary.stopDrag) jsPlumb.CurrentLibrary.stopDrag();
  4060. _dragHandler.stopDrag();
  4061. return false;
  4062. }
  4063. // if we're not full but there was a connection, make it null. we'll create a new one.
  4064. if (jpc && !self.isFull() && params.isSource) jpc = null;
  4065. _updateOffset( { elId : _elementId });
  4066. inPlaceCopy = self.makeInPlaceCopy();
  4067. inPlaceCopy.paint();
  4068. _makeDraggablePlaceholder(placeholderInfo, self.parent);
  4069. // set the offset of this div to be where 'inPlaceCopy' is, to start with.
  4070. // TODO merge this code with the code in both Anchor and FloatingAnchor, because it
  4071. // does the same stuff.
  4072. var ipcoel = _getElementObject(inPlaceCopy.canvas),
  4073. ipco = jsPlumb.CurrentLibrary.getOffset(ipcoel),
  4074. po = adjustForParentOffsetAndScroll([ipco.left, ipco.top], inPlaceCopy.canvas);
  4075. jsPlumb.CurrentLibrary.setOffset(placeholderInfo.element, {left:po[0], top:po[1]});
  4076. // when using makeSource and a parent, we first draw the source anchor on the source element, then
  4077. // move it to the parent. note that this happens after drawing the placeholder for the
  4078. // first time.
  4079. if (self.parentAnchor) self.anchor = _currentInstance.makeAnchor(self.parentAnchor, self.elementId, _currentInstance);
  4080. // store the id of the dragging div and the source element. the drop function will pick these up.
  4081. _setAttribute(_getElementObject(self.canvas), "dragId", placeholderInfo.id);
  4082. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  4083. // create a floating anchor
  4084. floatingEndpoint = _makeFloatingEndpoint(self.paintStyle, self.anchor, _endpoint, self.canvas, placeholderInfo.element);
  4085. if (jpc == null) {
  4086. self.anchor.locked = true;
  4087. self.setHover(false, false);
  4088. // TODO the hover call above does not reset any target endpoint's hover
  4089. // states.
  4090. // create a connection. one end is this endpoint, the other is a floating endpoint.
  4091. jpc = _newConnection({
  4092. sourceEndpoint : self,
  4093. targetEndpoint : floatingEndpoint,
  4094. source : self.endpointWillMoveTo || _getElementObject(_element), // for makeSource with parent option. ensure source element is represented correctly.
  4095. target : placeholderInfo.element,
  4096. anchors : [ self.anchor, floatingEndpoint.anchor ],
  4097. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  4098. hoverPaintStyle:params.connectorHoverStyle,
  4099. connector : params.connector, // this can also be null. Connection will use the default.
  4100. overlays : params.connectorOverlays
  4101. });
  4102. } else {
  4103. existingJpc = true;
  4104. jpc.connector.setHover(false, false);
  4105. // jpc.endpoints[0].setHover(false, false);
  4106. //jpc.endpoints[1].setHover(false, false);
  4107. // if existing connection, allow to be dropped back on the source endpoint (issue 51).
  4108. _initDropTarget(_getElementObject(inPlaceCopy.canvas), false, true);
  4109. //var anchorIdx = jpc.sourceId == _elementId ? 0 : 1; // are we the source or the target?
  4110. // new anchor idx
  4111. var anchorIdx = jpc.endpoints[0].id == self.id ? 0 : 1;
  4112. jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
  4113. self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
  4114. // store the original scope (issue 57)
  4115. var c = _getElementObject(self.canvas),
  4116. dragScope = jsPlumb.CurrentLibrary.getDragScope(c);
  4117. _setAttribute(c, "originalScope", dragScope);
  4118. // now we want to get this endpoint's DROP scope, and set it for now: we can only be dropped on drop zones
  4119. // that have our drop scope (issue 57).
  4120. var dropScope = jsPlumb.CurrentLibrary.getDropScope(c);
  4121. jsPlumb.CurrentLibrary.setDragScope(c, dropScope);
  4122. // now we replace ourselves with the temporary div we created above:
  4123. if (anchorIdx == 0) {
  4124. existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
  4125. jpc.source = placeholderInfo.element;
  4126. jpc.sourceId = placeholderInfo.id;
  4127. } else {
  4128. existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
  4129. jpc.target = placeholderInfo.element;
  4130. jpc.targetId = placeholderInfo.id;
  4131. }
  4132. // lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
  4133. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
  4134. // store the original endpoint and assign the new floating endpoint for the drag.
  4135. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  4136. jpc.suspendedEndpoint.setHover(false);
  4137. jpc.endpoints[anchorIdx] = floatingEndpoint;
  4138. }
  4139. // register it and register connection on it.
  4140. floatingConnections[placeholderInfo.id] = jpc;
  4141. floatingEndpoint.addConnection(jpc);
  4142. // only register for the target endpoint; we will not be dragging the source at any time
  4143. // before this connection is either discarded or made into a permanent connection.
  4144. _addToList(endpointsByElement, placeholderInfo.id, floatingEndpoint);
  4145. // tell jsplumb about it
  4146. _currentInstance.currentlyDragging = true;
  4147. };
  4148. var jpcl = jsPlumb.CurrentLibrary,
  4149. dragOptions = params.dragOptions || {},
  4150. defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
  4151. startEvent = jpcl.dragEvents["start"],
  4152. stopEvent = jpcl.dragEvents["stop"],
  4153. dragEvent = jpcl.dragEvents["drag"];
  4154. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  4155. dragOptions.scope = dragOptions.scope || self.scope;
  4156. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  4157. // extracted drag handler function so can be used by makeSource
  4158. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], _dragHandler.drag);
  4159. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  4160. function() {
  4161. _currentInstance.currentlyDragging = false;
  4162. _removeWithFunction(endpointsByElement[placeholderInfo.id], function(e) {
  4163. return e.id == floatingEndpoint.id;
  4164. });
  4165. _removeElements( [ placeholderInfo.element[0], floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
  4166. _removeElement(inPlaceCopy.canvas, _element);
  4167. _currentInstance.anchorManager.clearFor(placeholderInfo.id);
  4168. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  4169. jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
  4170. if (jpc.endpoints[idx] == floatingEndpoint) {
  4171. // if the connection was an existing one:
  4172. if (existingJpc && jpc.suspendedEndpoint) {
  4173. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  4174. // floating endpoint has been replaced.
  4175. if (idx == 0) {
  4176. jpc.source = existingJpcParams[0];
  4177. jpc.sourceId = existingJpcParams[1];
  4178. } else {
  4179. jpc.target = existingJpcParams[0];
  4180. jpc.targetId = existingJpcParams[1];
  4181. }
  4182. // restore the original scope (issue 57)
  4183. jsPlumb.CurrentLibrary.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  4184. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  4185. if (self.isReattach || jpc._forceDetach || !jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc)) {
  4186. jpc.setHover(false);
  4187. jpc.floatingAnchorIndex = null;
  4188. jpc.suspendedEndpoint.addConnection(jpc);
  4189. _currentInstance.repaint(existingJpcParams[1]);
  4190. }
  4191. jpc._forceDetach = null;
  4192. } else {
  4193. // TODO this looks suspiciously kind of like an Endpoint.detach call too.
  4194. // i wonder if this one should post an event though. maybe this is good like this.
  4195. _removeElements(jpc.connector.getDisplayElements(), self.parent);
  4196. self.detachFromConnection(jpc);
  4197. }
  4198. }
  4199. self.anchor.locked = false;
  4200. self.paint({recalc:false});
  4201. jpc.setHover(false, false);
  4202. jpc = null;
  4203. inPlaceCopy = null;
  4204. delete endpointsByElement[floatingEndpoint.elementId];
  4205. floatingEndpoint.anchor = null;
  4206. floatingEndpoint = null;
  4207. _currentInstance.currentlyDragging = false;
  4208. });
  4209. var i = _getElementObject(self.canvas);
  4210. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions, true);
  4211. }
  4212. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  4213. // back onto the endpoint you detached it from.
  4214. var _initDropTarget = function(canvas, forceInit, isTransient) {
  4215. if ((params.isTarget || forceInit) && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  4216. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  4217. dropOptions = jsPlumb.extend( {}, dropOptions);
  4218. dropOptions.scope = dropOptions.scope || self.scope;
  4219. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'],
  4220. overEvent = jsPlumb.CurrentLibrary.dragEvents['over'],
  4221. outEvent = jsPlumb.CurrentLibrary.dragEvents['out'],
  4222. drop = function(originalEvent) {
  4223. var draggable = _getElementObject(jsPlumb.CurrentLibrary.getDragObject(arguments)),
  4224. id = _getAttribute(draggable, "dragId"),
  4225. elId = _getAttribute(draggable, "elId"),
  4226. scope = _getAttribute(draggable, "originalScope"),
  4227. jpc = floatingConnections[id],
  4228. idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
  4229. // restore the original scope if necessary (issue 57)
  4230. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  4231. if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
  4232. var _doContinue = true;
  4233. // the second check here is for the case that the user is dropping it back
  4234. // where it came from.
  4235. if (jpc.suspendedEndpoint && jpc.suspendedEndpoint.id != self.id) {
  4236. if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_currentInstance.checkCondition("beforeDetach", jpc))
  4237. _doContinue = false;
  4238. }
  4239. // these have to be set before testing for beforeDrop.
  4240. if (idx == 0) {
  4241. jpc.source = _element;
  4242. jpc.sourceId = _elementId;
  4243. } else {
  4244. jpc.target = _element;
  4245. jpc.targetId = _elementId;
  4246. }
  4247. // now check beforeDrop. this will be available only on Endpoints that are setup to
  4248. // have a beforeDrop condition (although, secretly, under the hood all Endpoints and
  4249. // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
  4250. // it only makes sense to have it on a target endpoint.
  4251. _doContinue = _doContinue && self.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope);
  4252. if (_doContinue) {
  4253. // remove this jpc from the current endpoint
  4254. jpc.endpoints[idx].detachFromConnection(jpc);
  4255. if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
  4256. jpc.endpoints[idx] = self;
  4257. self.addConnection(jpc);
  4258. if (!jpc.suspendedEndpoint) {
  4259. //_addToList(connectionsByScope, jpc.scope, jpc);
  4260. _initDraggableIfNecessary(_element, params.draggable, {});
  4261. }
  4262. else {
  4263. var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
  4264. // fire a detach event
  4265. fireDetachEvent({
  4266. source : idx == 0 ? suspendedElement : jpc.source,
  4267. target : idx == 1 ? suspendedElement : jpc.target,
  4268. sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
  4269. targetId : idx == 1 ? suspendedElementId : jpc.targetId,
  4270. sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  4271. targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  4272. connection : jpc
  4273. }, true);
  4274. }
  4275. // finalise will inform the anchor manager and also add to
  4276. // connectionsByScope if necessary.
  4277. _finaliseConnection(jpc, null, originalEvent);
  4278. }
  4279. else {
  4280. // otherwise just put it back on the endpoint it was on before the drag.
  4281. if (jpc.suspendedEndpoint) {
  4282. // self.detachFrom(jpc);
  4283. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  4284. jpc.setHover(false);
  4285. jpc._forceDetach = true;
  4286. if (idx == 0) {
  4287. jpc.source = jpc.suspendedEndpoint.element;
  4288. jpc.sourceId = jpc.suspendedEndpoint.elementId;
  4289. } else {
  4290. jpc.target = jpc.suspendedEndpoint.element;
  4291. jpc.targetId = jpc.suspendedEndpoint.elementId;;
  4292. }
  4293. jpc.suspendedEndpoint.addConnection(jpc);
  4294. jpc.endpoints[0].repaint();
  4295. jpc.repaint();
  4296. _currentInstance.repaint(jpc.source.elementId);
  4297. jpc._forceDetach = false;
  4298. }
  4299. }
  4300. jpc.floatingAnchorIndex = null;
  4301. }
  4302. _currentInstance.currentlyDragging = false;
  4303. delete floatingConnections[id];
  4304. };
  4305. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], drop);
  4306. dropOptions[overEvent] = _wrap(dropOptions[overEvent], function() {
  4307. if (self.isTarget) {
  4308. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  4309. id = _getAttribute( _getElementObject(draggable), "dragId"),
  4310. jpc = floatingConnections[id];
  4311. if (jpc != null) {
  4312. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  4313. jpc.endpoints[idx].anchor.over(self.anchor);
  4314. }
  4315. }
  4316. });
  4317. dropOptions[outEvent] = _wrap(dropOptions[outEvent], function() {
  4318. if (self.isTarget) {
  4319. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  4320. id = _getAttribute( _getElementObject(draggable), "dragId"),
  4321. jpc = floatingConnections[id];
  4322. if (jpc != null) {
  4323. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  4324. jpc.endpoints[idx].anchor.out();
  4325. }
  4326. }
  4327. });
  4328. jsPlumb.CurrentLibrary.initDroppable(canvas, dropOptions, true, isTransient);
  4329. }
  4330. };
  4331. // 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.
  4332. _initDropTarget(_getElementObject(self.canvas), true, !(params._transient || self.anchor.isFloating));
  4333. return self;
  4334. };
  4335. };
  4336. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  4337. jsPlumb.getInstance = function(_defaults) {
  4338. var j = new jsPlumbInstance(_defaults);
  4339. j.init();
  4340. return j;
  4341. };
  4342. jsPlumb.util = {
  4343. convertStyle : function(s, ignoreAlpha) {
  4344. // TODO: jsPlumb should support a separate 'opacity' style member.
  4345. if ("transparent" === s) return s;
  4346. var o = s,
  4347. pad = function(n) { return n.length == 1 ? "0" + n : n; },
  4348. hex = function(k) { return pad(Number(k).toString(16)); },
  4349. pattern = /(rgb[a]?\()(.*)(\))/;
  4350. if (s.match(pattern)) {
  4351. var parts = s.match(pattern)[2].split(",");
  4352. o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
  4353. if (!ignoreAlpha && parts.length == 4)
  4354. o = o + hex(parts[3]);
  4355. }
  4356. return o;
  4357. },
  4358. gradient : function(p1, p2) {
  4359. p1 = p1.constructor == Array ? p1 : [p1.x, p1.y];
  4360. p2 = p2.constructor == Array ? p2 : [p2.x, p2.y];
  4361. return (p2[1] - p1[1]) / (p2[0] - p1[0]);
  4362. },
  4363. normal : function(p1, p2) {
  4364. return -1 / jsPlumb.util.gradient(p1,p2);
  4365. },
  4366. segment : function(p1, p2) {
  4367. p1 = p1.constructor == Array ? p1 : [p1.x, p1.y];
  4368. p2 = p2.constructor == Array ? p2 : [p2.x, p2.y];
  4369. if (p2[0] > p1[0]) {
  4370. return (p2[1] > p1[1]) ? 2 : 1;
  4371. }
  4372. else {
  4373. return (p2[1] > p1[1]) ? 3 : 4;
  4374. }
  4375. },
  4376. segmentMultipliers : [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
  4377. inverseSegmentMultipliers : [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
  4378. pointOnLine : function(fromPoint, toPoint, distance) {
  4379. var m = jsPlumb.util.gradient(fromPoint, toPoint),
  4380. s = jsPlumb.util.segment(fromPoint, toPoint),
  4381. segmentMultiplier = distance > 0 ? jsPlumb.util.segmentMultipliers[s] : jsPlumb.util.inverseSegmentMultipliers[s],
  4382. theta = Math.atan(m),
  4383. y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
  4384. x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
  4385. return { x:fromPoint.x + x, y:fromPoint.y + y };
  4386. },
  4387. /**
  4388. * calculates a perpendicular to the line fromPoint->toPoint, that passes through toPoint and is 'length' long.
  4389. * @param fromPoint
  4390. * @param toPoint
  4391. * @param length
  4392. */
  4393. perpendicularLineTo : function(fromPoint, toPoint, length) {
  4394. var m = jsPlumb.util.gradient(fromPoint, toPoint),
  4395. theta2 = Math.atan(-1 / m),
  4396. y = length / 2 * Math.sin(theta2),
  4397. x = length / 2 * Math.cos(theta2);
  4398. return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
  4399. }
  4400. };
  4401. var _curryAnchor = function(x, y, ox, oy, type, fnInit) {
  4402. return function(params) {
  4403. params = params || {};
  4404. //var a = jsPlumb.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
  4405. var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
  4406. a.type = type;
  4407. if (fnInit) fnInit(a, params);
  4408. return a;
  4409. };
  4410. };
  4411. jsPlumb.Anchors["TopCenter"] = _curryAnchor(0.5, 0, 0,-1, "TopCenter");
  4412. jsPlumb.Anchors["BottomCenter"] = _curryAnchor(0.5, 1, 0, 1, "BottomCenter");
  4413. jsPlumb.Anchors["LeftMiddle"] = _curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
  4414. jsPlumb.Anchors["RightMiddle"] = _curryAnchor(1, 0.5, 1, 0, "RightMiddle");
  4415. jsPlumb.Anchors["Center"] = _curryAnchor(0.5, 0.5, 0, 0, "Center");
  4416. jsPlumb.Anchors["TopRight"] = _curryAnchor(1, 0, 0,-1, "TopRight");
  4417. jsPlumb.Anchors["BottomRight"] = _curryAnchor(1, 1, 0, 1, "BottomRight");
  4418. jsPlumb.Anchors["TopLeft"] = _curryAnchor(0, 0, 0, -1, "TopLeft");
  4419. jsPlumb.Anchors["BottomLeft"] = _curryAnchor(0, 1, 0, 1, "BottomLeft");
  4420. // TODO test that this does not break with the current instance idea
  4421. jsPlumb.Defaults.DynamicAnchors = function(params) {
  4422. return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
  4423. };
  4424. jsPlumb.Anchors["AutoDefault"] = function(params) {
  4425. var a = params.jsPlumbInstance.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors(params));
  4426. a.type = "AutoDefault";
  4427. return a;
  4428. };
  4429. jsPlumb.Anchors["Assign"] = _curryAnchor(0,0,0,0,"Assign", function(anchor, params) {
  4430. // find what to use as the "position finder". the user may have supplied a String which represents
  4431. // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
  4432. // position finder as a function. we find out what to use and then set it on the anchor.
  4433. var pf = params.position || "Fixed";
  4434. anchor.positionFinder = pf.constructor == String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf;
  4435. // always set the constructor params; the position finder might need them later (the Grid one does,
  4436. // for example)
  4437. anchor.constructorParams = params;
  4438. });
  4439. // Continuous anchor is just curried through to the 'get' method of the continuous anchor
  4440. // factory.
  4441. jsPlumb.Anchors["Continuous"] = function(params) {
  4442. return params.jsPlumbInstance.continuousAnchorFactory.get(params);
  4443. };
  4444. // these are the default anchor positions finders, which are used by the makeTarget function. supply
  4445. // a position finder argument to that function allows you to specify where the resulting anchor will
  4446. // be located
  4447. jsPlumb.AnchorPositionFinders = {
  4448. "Fixed": function(dp, ep, es, a) {
  4449. return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
  4450. },
  4451. "Grid":function(dp, ep, es, a) {
  4452. var dx = dp.left - ep.left, dy = dp.top - ep.top,
  4453. gx = es[0] / (a.constructorParams.grid[0]), gy = es[1] / (a.constructorParams.grid[1]),
  4454. mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
  4455. return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
  4456. }
  4457. };
  4458. })();