jsPlumb-1.3.6-RC1.js 206 KB

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