jsPlumb-1.3.4-RC1.js 195 KB

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