yui.jsPlumb-1.3.4-all.js 315 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986
  1. /*
  2. * jsPlumb
  3. *
  4. * Title:jsPlumb 1.3.5
  5. *
  6. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  7. * elements, or VML.
  8. *
  9. * This file contains the jsPlumb core code.
  10. *
  11. * Copyright (c) 2010 - 2012 Simon Porritt (simon.porritt@gmail.com)
  12. *
  13. * http://jsplumb.org
  14. * http://github.com/sporritt/jsplumb
  15. * http://code.google.com/p/jsplumb
  16. *
  17. * Dual licensed under the MIT and GPL2 licenses.
  18. */
  19. ;(function() {
  20. /**
  21. * Class:jsPlumb
  22. * The jsPlumb engine, registered as a static object in the window. This object contains all of the methods you will use to
  23. * create and maintain Connections and Endpoints.
  24. */
  25. var canvasAvailable = !!document.createElement('canvas').getContext,
  26. svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"),
  27. // TODO what is a good test for VML availability? aside from just assuming its there because nothing else is.
  28. vmlAvailable = !(canvasAvailable | svgAvailable);
  29. // finds the index of some value in an array, using a deep equals test.
  30. var _findIndex = function(a, v, b, s) {
  31. var _eq = function(o1, o2) {
  32. if (o1 === o2) return true;
  33. else if (typeof o1 == "object" && typeof o2 == "object") {
  34. var same = true;
  35. for ( var propertyName in o1) {
  36. if (!_eq(o1[propertyName], o2[propertyName])) {
  37. same = false;
  38. break;
  39. }
  40. }
  41. for ( var propertyName in o2) {
  42. if (!_eq(o2[propertyName], o1[propertyName])) {
  43. same = false;
  44. break;
  45. }
  46. }
  47. return same;
  48. }
  49. };
  50. for ( var i = +b || 0, l = a.length; i < l; i++) {
  51. if (_eq(a[i], v))
  52. return i;
  53. }
  54. return -1;
  55. },
  56. _findWithFunction = function(a, f) {
  57. for (var i = 0; i < a.length; i++) if (f(a[i])) return i;
  58. return -1;
  59. },
  60. _removeWithFunction = function(a, f) {
  61. var idx = _findWithFunction(a, f);
  62. if (idx > -1) a.splice(idx, 1);
  63. return idx != -1;
  64. };
  65. // for those browsers that dont have it. they still don't have it! but at least they won't crash.
  66. if (!window.console)
  67. window.console = { time:function(){}, timeEnd:function(){}, group:function(){}, groupEnd:function(){}, log:function(){} };
  68. /**
  69. * helper method to add an item to a list, creating the list if it does
  70. * not yet exist.
  71. */
  72. var _addToList = function(map, key, value) {
  73. var l = map[key];
  74. if (l == null) {
  75. l = [], map[key] = l;
  76. }
  77. l.push(value);
  78. return l;
  79. },
  80. _connectionBeingDragged = null,
  81. _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); },
  82. _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); },
  83. _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); },
  84. _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
  85. _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); },
  86. _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
  87. _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
  88. _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); },
  89. _logEnabled = true,
  90. _log = function() {
  91. if (_logEnabled && typeof console != "undefined") {
  92. try {
  93. var msg = arguments[arguments.length - 1];
  94. console.log(msg);
  95. }
  96. catch (e) {}
  97. }
  98. },
  99. _group = function(g) {
  100. if (_logEnabled && typeof console != "undefined") console.group(g);
  101. },
  102. _groupEnd = function(g) {
  103. if (_logEnabled && typeof console != "undefined") console.groupEnd(g);
  104. },
  105. _time = function(t) {
  106. if (_logEnabled && typeof console != "undefined") console.time(t);
  107. },
  108. _timeEnd = function(t) {
  109. if (_logEnabled && typeof console != "undefined") console.timeEnd(t);
  110. };
  111. /**
  112. * EventGenerator
  113. * Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
  114. */
  115. EventGenerator = function() {
  116. var _listeners = {}, self = this;
  117. // this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to
  118. // jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
  119. // listeners to bring down jsPlumb - or do we. i can't make up my mind about this, but i know i want to hear about it if the "ready"
  120. // event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
  121. // to hear what other people think.
  122. var eventsToDieOn = [ "ready" ];
  123. /*
  124. * Binds a listener to an event.
  125. *
  126. * Parameters:
  127. * event - name of the event to bind to.
  128. * listener - function to execute.
  129. */
  130. this.bind = function(event, listener) {
  131. _addToList(_listeners, event, listener);
  132. };
  133. /*
  134. * Fires an update for the given event.
  135. *
  136. * Parameters:
  137. * event - event to fire
  138. * value - value to pass to the event listener(s).
  139. * o riginalEvent - the original event from the browser
  140. */
  141. this.fire = function(event, value, originalEvent) {
  142. if (_listeners[event]) {
  143. for ( var i = 0; i < _listeners[event].length; i++) {
  144. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  145. // method will have the whole call stack available in the debugger.
  146. if (_findIndex(eventsToDieOn, event) != -1)
  147. _listeners[event][i](value, originalEvent);
  148. else {
  149. // for events we don't want to die on, catch and log.
  150. try {
  151. _listeners[event][i](value, originalEvent);
  152. } catch (e) {
  153. _log("jsPlumb: fire failed for event " + event + " : " + e);
  154. }
  155. }
  156. }
  157. }
  158. };
  159. /*
  160. * Clears either all listeners, or listeners for some specific event.
  161. *
  162. * Parameters:
  163. * event - optional. constrains the clear to just listeners for this event.
  164. */
  165. this.clearListeners = function(event) {
  166. if (event)
  167. delete _listeners[event];
  168. else {
  169. delete _listeners;
  170. _listeners = {};
  171. }
  172. };
  173. this.getListener = function(forEvent) {
  174. return _listeners[forEvent];
  175. };
  176. },
  177. /**
  178. * creates a timestamp, using milliseconds since 1970, but as a string.
  179. */
  180. _timestamp = function() { return "" + (new Date()).getTime(); },
  181. /*
  182. * Class:jsPlumbUIComponent
  183. * Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle,
  184. * and also extends EventGenerator to provide the bind and fire methods.
  185. */
  186. jsPlumbUIComponent = function(params) {
  187. var self = this, a = arguments, _hover = false, parameters = params.parameters || {}, idPrefix = self.idPrefix,
  188. id = idPrefix + (new Date()).getTime();
  189. self._jsPlumb = params["_jsPlumb"];
  190. self.getId = function() { return id; };
  191. self.tooltip = params.tooltip;
  192. self.hoverClass = params.hoverClass;
  193. // all components can generate events
  194. EventGenerator.apply(this);
  195. // all components get this clone function.
  196. // TODO issue 116 showed a problem with this - it seems 'a' that is in
  197. // the clone function's scope is shared by all invocations of it, the classic
  198. // JS closure problem. for now, jsPlumb does a version of this inline where
  199. // it used to call clone. but it would be nice to find some time to look
  200. // further at this.
  201. this.clone = function() {
  202. var o = new Object();
  203. self.constructor.apply(o, a);
  204. return o;
  205. };
  206. this.getParameter = function(name) { return parameters[name]; },
  207. this.getParameters = function() { return parameters; },
  208. this.setParameter = function(name, value) { parameters[name] = value; },
  209. this.setParameters = function(p) { parameters = p; },
  210. this.overlayPlacements = [],
  211. this.paintStyle = null,
  212. this.hoverPaintStyle = null;
  213. // user can supply a beforeDetach callback, which will be executed before a detach
  214. // is performed; returning false prevents the detach.
  215. var beforeDetach = params.beforeDetach;
  216. this.isDetachAllowed = function(connection) {
  217. var r = true;
  218. if (beforeDetach) {
  219. try {
  220. r = beforeDetach(connection);
  221. }
  222. catch (e) { _log("jsPlumb: beforeDetach callback failed", e); }
  223. }
  224. return r;
  225. };
  226. // user can supply a beforeDrop callback, which will be executed before a dropped
  227. // connection is confirmed. user can return false to reject connection.
  228. var beforeDrop = params.beforeDrop;
  229. this.isDropAllowed = function(sourceId, targetId, scope) {
  230. var r = self._jsPlumb.checkCondition("beforeDrop", { sourceId:sourceId, targetId:targetId, scope:scope });
  231. if (beforeDrop) {
  232. try {
  233. r = beforeDrop({ sourceId:sourceId, targetId:targetId, scope:scope });
  234. }
  235. catch (e) { _log("jsPlumb: beforeDrop callback failed", e); }
  236. }
  237. return r;
  238. };
  239. // helper method to update the hover style whenever it, or paintStyle, changes.
  240. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  241. // top.
  242. var _updateHoverStyle = function() {
  243. if (self.paintStyle && self.hoverPaintStyle) {
  244. var mergedHoverStyle = {};
  245. jsPlumb.extend(mergedHoverStyle, self.paintStyle);
  246. jsPlumb.extend(mergedHoverStyle, self.hoverPaintStyle);
  247. delete self["hoverPaintStyle"];
  248. // we want the fillStyle of paintStyle to override a gradient, if possible.
  249. if (mergedHoverStyle.gradient && self.paintStyle.fillStyle)
  250. delete mergedHoverStyle["gradient"];
  251. self.hoverPaintStyle = mergedHoverStyle;
  252. }
  253. };
  254. /*
  255. * Sets the paint style and then repaints the element.
  256. *
  257. * Parameters:
  258. * style - Style to use.
  259. */
  260. this.setPaintStyle = function(style, doNotRepaint) {
  261. self.paintStyle = style;
  262. self.paintStyleInUse = self.paintStyle;
  263. _updateHoverStyle();
  264. if (!doNotRepaint) self.repaint();
  265. };
  266. /*
  267. * Sets the paint style to use when the mouse is hovering over the element. This is null by default.
  268. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  269. * it. This is because people will most likely want to change just one thing when hovering, say the
  270. * color for example, but leave the rest of the appearance the same.
  271. *
  272. * Parameters:
  273. * style - Style to use when the mouse is hovering.
  274. * doNotRepaint - if true, the component will not be repainted. useful when setting things up initially.
  275. */
  276. this.setHoverPaintStyle = function(style, doNotRepaint) {
  277. self.hoverPaintStyle = style;
  278. _updateHoverStyle();
  279. if (!doNotRepaint) self.repaint();
  280. };
  281. /*
  282. * sets/unsets the hover state of this element.
  283. *
  284. * Parameters:
  285. * hover - hover state boolean
  286. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  287. */
  288. this.setHover = function(hover, ignoreAttachedElements, timestamp) {
  289. // while dragging, we ignore these events. this keeps the UI from flashing and
  290. // swishing and whatevering.
  291. if (!self._jsPlumb.currentlyDragging) {
  292. _hover = hover;
  293. if (self.hoverClass != null && self.canvas != null) {
  294. if (hover)
  295. jpcl.addClass(self.canvas, self.hoverClass);
  296. else
  297. jpcl.removeClass(self.canvas, self.hoverClass);
  298. }
  299. if (self.hoverPaintStyle != null) {
  300. self.paintStyleInUse = hover ? self.hoverPaintStyle : self.paintStyle;
  301. timestamp = timestamp || _timestamp();
  302. self.repaint({timestamp:timestamp, recalc:false});
  303. }
  304. // get the list of other affected elements, if supported by this component.
  305. // for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  306. if (self.getAttachedElements && !ignoreAttachedElements)
  307. _updateAttachedElements(hover, _timestamp(), self);
  308. }
  309. };
  310. this.isHover = function() { return _hover; };
  311. var jpcl = jsPlumb.CurrentLibrary,
  312. events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup" ],
  313. eventFilters = { "mouseout":"mouseexit" },
  314. bindOne = function(o, c, evt) {
  315. var filteredEvent = eventFilters[evt] || evt;
  316. jpcl.bind(o, evt, function(ee) {
  317. c.fire(filteredEvent, c, ee);
  318. });
  319. },
  320. unbindOne = function(o, evt) {
  321. var filteredEvent = eventFilters[evt] || evt;
  322. jpcl.unbind(o, evt);
  323. };
  324. this.attachListeners = function(o, c) {
  325. for (var i = 0; i < events.length; i++) {
  326. bindOne(o, c, events[i]);
  327. }
  328. };
  329. var _updateAttachedElements = function(state, timestamp, sourceElement) {
  330. var affectedElements = self.getAttachedElements(); // implemented in subclasses
  331. if (affectedElements) {
  332. for (var i = 0; i < affectedElements.length; i++) {
  333. if (!sourceElement || sourceElement != affectedElements[i])
  334. affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements.
  335. }
  336. }
  337. };
  338. this.reattachListenersForElement = function(o, c) {
  339. for (var i = 0; i < events.length; i++)
  340. unbindOne(o, events[i]);
  341. self.attachListeners(o, c);
  342. };
  343. };
  344. var jsPlumbInstance = function(_defaults) {
  345. /*
  346. * Property: Defaults
  347. *
  348. * These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
  349. * to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
  350. * by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
  351. *
  352. * Properties:
  353. * - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
  354. * - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
  355. * - *Connector* The default connector definition to use for all connections. Default is "Bezier".
  356. * - *Container* Optional selector or element id that instructs jsPlumb to append elements it creates to a specific element.
  357. * - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  358. * - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  359. * - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
  360. * - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
  361. * - *EndpointStyle* The default style definition to use for all endpoints. Default is fillStyle:"#456".
  362. * - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
  363. * - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
  364. * - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
  365. * - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
  366. * - *LabelStyle* The default style to use for label overlays on connections.
  367. * - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
  368. * - *Overlays* The default overlay definitions. Defaults to an empty list.
  369. * - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
  370. * - *MouseEventsEnabled* Whether or not mouse events are enabled when using the canvas renderer. Defaults to true.
  371. * The idea of this is just to give people a way to prevent all the mouse listeners from activating if they know they won't need mouse events.
  372. * - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
  373. * - *RenderMode* What mode to use to paint with. If you're on IE<9, you don't really get to choose this. You'll just get VML. Otherwise, the jsPlumb default is to use Canvas elements.
  374. * - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
  375. */
  376. this.Defaults = {
  377. Anchor : "BottomCenter",
  378. Anchors : [ null, null ],
  379. ConnectionsDetachable : true,
  380. Connector : "Bezier",
  381. Container : null,
  382. DragOptions : { },
  383. DropOptions : { },
  384. Endpoint : "Dot",
  385. Endpoints : [ null, null ],
  386. EndpointStyle : { fillStyle : "#456" },
  387. EndpointStyles : [ null, null ],
  388. EndpointHoverStyle : null,
  389. EndpointHoverStyles : [ null, null ],
  390. HoverPaintStyle : null,
  391. LabelStyle : { color : "black" },
  392. LogEnabled : false,
  393. Overlays : [ ],
  394. MaxConnections : 1,
  395. MouseEventsEnabled : true,
  396. PaintStyle : { lineWidth : 8, strokeStyle : "#456" },
  397. //Reattach:false,
  398. RenderMode : "svg",
  399. Scope : "jsPlumb_DefaultScope"
  400. };
  401. if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
  402. this.logEnabled = this.Defaults.LogEnabled;
  403. EventGenerator.apply(this);
  404. var _bb = this.bind;
  405. this.bind = function(event, fn) {
  406. if ("ready" === event && initialized) fn();
  407. else _bb(event, fn);
  408. };
  409. var _currentInstance = this,
  410. log = null,
  411. repaintFunction = function() {
  412. jsPlumb.repaintEverything();
  413. },
  414. automaticRepaint = true,
  415. repaintEverything = function() {
  416. if (automaticRepaint)
  417. repaintFunction();
  418. },
  419. resizeTimer = null,
  420. initialized = false,
  421. connectionsByScope = {},
  422. /**
  423. * map of element id -> endpoint lists. an element can have an arbitrary
  424. * number of endpoints on it, and not all of them have to be connected
  425. * to anything.
  426. */
  427. endpointsByElement = {},
  428. endpointsByUUID = {},
  429. offsets = {},
  430. offsetTimestamps = {},
  431. floatingConnections = {},
  432. draggableStates = {},
  433. _mouseEventsEnabled = this.Defaults.MouseEventsEnabled,
  434. canvasList = [],
  435. sizes = [],
  436. //listeners = {}, // a map: keys are event types, values are lists of listeners.
  437. DEFAULT_SCOPE = this.Defaults.Scope,
  438. renderMode = null, // will be set in init()
  439. /**
  440. * helper method to add an item to a list, creating the list if it does
  441. * not yet exist.
  442. */
  443. _addToList = function(map, key, value) {
  444. var l = map[key];
  445. if (l == null) {
  446. l = [];
  447. map[key] = l;
  448. }
  449. l.push(value);
  450. return l;
  451. },
  452. /**
  453. * appends an element to some other element, which is calculated as follows:
  454. *
  455. * 1. if _currentInstance.Defaults.Container exists, use that element.
  456. * 2. if the 'parent' parameter exists, use that.
  457. * 3. otherwise just use the document body.
  458. *
  459. */
  460. _appendElement = function(el, parent) {
  461. if (_currentInstance.Defaults.Container)
  462. jsPlumb.CurrentLibrary.appendElement(el, _currentInstance.Defaults.Container);
  463. else if (!parent)
  464. document.body.appendChild(el);
  465. else
  466. jsPlumb.CurrentLibrary.appendElement(el, parent);
  467. },
  468. _curIdStamp = 1,
  469. _idstamp = function() { return "" + _curIdStamp++; },
  470. /**
  471. * YUI, for some reason, put the result of a Y.all call into an object that contains
  472. * a '_nodes' array, instead of handing back an array-like object like the other
  473. * libraries do.
  474. */
  475. _convertYUICollection = function(c) {
  476. return c._nodes ? c._nodes : c;
  477. },
  478. /**
  479. * Draws an endpoint and its connections. this is the main entry point into drawing connections as well
  480. * as endpoints, since jsPlumb is endpoint-centric under the hood.
  481. *
  482. * @param element element to draw (of type library specific element object)
  483. * @param ui UI object from current library's event system. optional.
  484. * @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  485. */
  486. _draw = function(element, ui, timestamp) {
  487. var id = _getAttribute(element, "id");
  488. _currentInstance.anchorManager.redraw(id, ui, timestamp);
  489. },
  490. /**
  491. * executes the given function against the given element if the first
  492. * argument is an object, or the list of elements, if the first argument
  493. * is a list. the function passed in takes (element, elementId) as
  494. * arguments.
  495. */
  496. _elementProxy = function(element, fn) {
  497. var retVal = null;
  498. if (element.constructor == Array) {
  499. retVal = [];
  500. for ( var i = 0; i < element.length; i++) {
  501. var el = _getElementObject(element[i]), id = _getAttribute(el, "id");
  502. retVal.push(fn(el, id)); // append return values to what we will return
  503. }
  504. } else {
  505. var el = _getElementObject(element), id = _getAttribute(el, "id");
  506. retVal = fn(el, id);
  507. }
  508. return retVal;
  509. },
  510. /**
  511. * gets an Endpoint by uuid.
  512. */
  513. _getEndpoint = function(uuid) { return endpointsByUUID[uuid]; },
  514. /**
  515. * inits a draggable if it's not already initialised.
  516. */
  517. _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  518. var draggable = isDraggable == null ? false : isDraggable;
  519. if (draggable) {
  520. if (jsPlumb.CurrentLibrary.isDragSupported(element) && !jsPlumb.CurrentLibrary.isAlreadyDraggable(element)) {
  521. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  522. options = jsPlumb.extend( {}, options); // make a copy.
  523. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  524. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  525. options[dragEvent] = _wrap(options[dragEvent], function() {
  526. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  527. _draw(element, ui);
  528. _addClass(element, "jsPlumb_dragged");
  529. });
  530. options[stopEvent] = _wrap(options[stopEvent], function() {
  531. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  532. _draw(element, ui);
  533. _removeClass(element, "jsPlumb_dragged");
  534. });
  535. draggableStates[_getId(element)] = true;
  536. var draggable = draggableStates[_getId(element)];
  537. options.disabled = draggable == null ? false : !draggable;
  538. jsPlumb.CurrentLibrary.initDraggable(element, options, false);
  539. }
  540. }
  541. },
  542. /*
  543. * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc.
  544. */
  545. _prepareConnectionParams = function(params, referenceParams) {
  546. var _p = jsPlumb.extend( {}, params);
  547. if (referenceParams) jsPlumb.extend(_p, referenceParams);
  548. if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source;
  549. if (_p.source && _p.target.endpoint) _p.targetEndpoint = _p.target;
  550. // test for endpoint uuids to connect
  551. if (params.uuids) {
  552. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  553. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  554. }
  555. // now ensure that if we do have Endpoints already, they're not full.
  556. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  557. _log(_currentInstance, "could not add connection; source endpoint is full");
  558. return;
  559. }
  560. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  561. _log(_currentInstance, "could not add connection; target endpoint is full");
  562. return;
  563. }
  564. // copy in any connectorOverlays that were specified on the source endpoint.
  565. // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not.
  566. if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) {
  567. _p.overlays = _p.overlays || [];
  568. for (var i = 0; i < _p.sourceEndpoint.connectorOverlays.length; i++) {
  569. _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]);
  570. }
  571. }
  572. // tooltip. params.tooltip takes precedence, then sourceEndpoint.connectorTooltip.
  573. _p.tooltip = params.tooltip;
  574. if (!_p.tooltip && _p.sourceEndpoint && _p.sourceEndpoint.connectorTooltip)
  575. _p.tooltip = _p.sourceEndpoint.connectorTooltip;
  576. if (_p.target && !_p.target.endpoint) {
  577. var tid = _getId(_p.target),
  578. tep =_targetEndpointDefinitions[tid];
  579. var overrideOne = function(singlePropertyName, pluralPropertyName, tepProperty, tep) {
  580. if (tep[tepProperty]) {
  581. if (_p[pluralPropertyName]) _p[pluralPropertyName][1] = tep[tepProperty];
  582. else if (_p[singlePropertyName]) {
  583. _p[pluralPropertyName] = [ _p[singlePropertyName], tep[tepProperty] ];
  584. _p[singlePropertyName] = null;
  585. }
  586. else _p[pluralPropertyName] = [ null, tep[tepProperty] ];
  587. }
  588. };
  589. if (tep) {
  590. overrideOne("endpoint", "endpoints", "endpoint", tep);
  591. overrideOne("endpointStyle", "endpointStyles", "paintStyle", tep);
  592. overrideOne("endpointHoverStyle", "endpointHoverStyles", "hoverPaintStyle", tep);
  593. }
  594. }
  595. // dynamic anchors. backwards compatibility here: from 1.2.6 onwards you don't need to specify "dynamicAnchors". the fact that some anchor consists
  596. // of multiple definitions is enough to tell jsPlumb you want it to be dynamic.
  597. if (_p.dynamicAnchors) {
  598. // these can either be an array of anchor coords, which we will use for both source and target, or an object with {source:[anchors], target:[anchors]}, in which
  599. // case we will use a different set for each element.
  600. var a = _p.dynamicAnchors.constructor == Array,
  601. sourceId = _p.sourceEndpoint ? _p.sourceEndpoint.elementId : _getId(_p.source),
  602. targetId = _p.targetEndpoint ? _p.targetEndpoint.elementId : _getId(_p.target),
  603. sa = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors, sourceId, _currentInstance)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.source, sourceId, _currentInstance)),
  604. ta = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors, targetId, _currentInstance)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.target, targetId, _currentInstance));
  605. _p.anchors = [sa,ta];
  606. }
  607. return _p;
  608. },
  609. _newConnection = function(params) {
  610. var connectionFunc = jsPlumb.Defaults.ConnectionType || jsPlumb.getDefaultConnectionType(),
  611. endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint,
  612. parent = jsPlumb.CurrentLibrary.getParent;
  613. if (params.container)
  614. params["parent"] = params.container;
  615. else {
  616. if (params.sourceEndpoint)
  617. params["parent"] = params.sourceEndpoint.parent;
  618. else if (params.source.constructor == endpointFunc)
  619. params["parent"] = params.source.parent;
  620. else params["parent"] = parent(params.source);
  621. }
  622. params["_jsPlumb"] = _currentInstance;
  623. var con = new connectionFunc(params);
  624. con.id = "con_" + _idstamp();
  625. _eventFireProxy("click", "click", con);
  626. _eventFireProxy("dblclick", "dblclick", con);
  627. return con;
  628. },
  629. /**
  630. * adds the connection to the backing model, fires an event if necessary and then redraws
  631. */
  632. _finaliseConnection = function(jpc, params) {
  633. params = params || {};
  634. // add to list of connections (by scope).
  635. if (!jpc.suspendedEndpoint)
  636. _addToList(connectionsByScope, jpc.scope, jpc);
  637. // fire an event
  638. if (!params.doNotFireConnectionEvent && params.fireEvent !== false) {
  639. _currentInstance.fire("jsPlumbConnection", {
  640. connection:jpc,
  641. source : jpc.source, target : jpc.target,
  642. sourceId : jpc.sourceId, targetId : jpc.targetId,
  643. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  644. });
  645. }
  646. // always inform the anchor manager
  647. // except that if jpc has a suspended endpoint it's not true to say the
  648. // connection is new; it has just (possibly) moved. the question is whether
  649. // to make that call here or in the anchor manager. i think perhaps here.
  650. _currentInstance.anchorManager.newConnection(jpc);
  651. // force a paint
  652. _draw(jpc.source);
  653. },
  654. _eventFireProxy = function(event, proxyEvent, obj) {
  655. obj.bind(event, function(originalObject, originalEvent) {
  656. _currentInstance.fire(proxyEvent, obj, originalEvent);
  657. });
  658. },
  659. /**
  660. * for the given endpoint params, returns an appropriate parent element for the UI elements that will be added.
  661. * this function is used by _newEndpoint (directly below), and also in the makeSource function in jsPlumb.
  662. *
  663. * the logic is to first look for a "container" member of params, and pass that back if found. otherwise we
  664. * handoff to the 'getParent' function in the current library.
  665. */
  666. _getParentFromParams = function(params) {
  667. if (params.container)
  668. return params.container;
  669. else {
  670. var tag = jsPlumb.CurrentLibrary.getTagName(params.source),
  671. p = jsPlumb.CurrentLibrary.getParent(params.source);
  672. if (tag.toLowerCase() === "td")
  673. return jsPlumb.CurrentLibrary.getParent(p);
  674. else return p;
  675. }
  676. },
  677. /**
  678. factory method to prepare a new endpoint. this should always be used instead of creating Endpoints
  679. manually, since this method attaches event listeners and an id.
  680. */
  681. _newEndpoint = function(params) {
  682. var endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint;
  683. params.parent = _getParentFromParams(params);
  684. params["_jsPlumb"] = _currentInstance;
  685. var ep = new endpointFunc(params);
  686. ep.id = "ep_" + _idstamp();
  687. _eventFireProxy("click", "endpointClick", ep);
  688. _eventFireProxy("dblclick", "endpointDblClick", ep);
  689. return ep;
  690. },
  691. /**
  692. * performs the given function operation on all the connections found
  693. * for the given element id; this means we find all the endpoints for
  694. * the given element, and then for each endpoint find the connectors
  695. * connected to it. then we pass each connection in to the given
  696. * function.
  697. */
  698. _operation = function(elId, func, endpointFunc) {
  699. var endpoints = endpointsByElement[elId];
  700. if (endpoints && endpoints.length) {
  701. for ( var i = 0; i < endpoints.length; i++) {
  702. for ( var j = 0; j < endpoints[i].connections.length; j++) {
  703. var retVal = func(endpoints[i].connections[j]);
  704. // if the function passed in returns true, we exit.
  705. // most functions return false.
  706. if (retVal) return;
  707. }
  708. if (endpointFunc) endpointFunc(endpoints[i]);
  709. }
  710. }
  711. },
  712. /**
  713. * perform an operation on all elements.
  714. */
  715. _operationOnAll = function(func) {
  716. for ( var elId in endpointsByElement) {
  717. _operation(elId, func);
  718. }
  719. },
  720. /**
  721. * helper to remove an element from the DOM.
  722. */
  723. _removeElement = function(element, parent) {
  724. if (element != null && element.parentNode != null) {
  725. element.parentNode.removeChild(element);
  726. }
  727. },
  728. /**
  729. * helper to remove a list of elements from the DOM.
  730. */
  731. _removeElements = function(elements, parent) {
  732. for ( var i = 0; i < elements.length; i++)
  733. _removeElement(elements[i], parent);
  734. },
  735. /**
  736. * helper method to remove an item from a list.
  737. */
  738. _removeFromList = function(map, key, value) {
  739. if (key != null) {
  740. var l = map[key];
  741. if (l != null) {
  742. var i = _findIndex(l, value);
  743. if (i >= 0) {
  744. delete (l[i]);
  745. l.splice(i, 1);
  746. return true;
  747. }
  748. }
  749. }
  750. return false;
  751. },
  752. /**
  753. * Sets whether or not the given element(s) should be draggable,
  754. * regardless of what a particular plumb command may request.
  755. *
  756. * @param element
  757. * May be a string, a element objects, or a list of
  758. * strings/elements.
  759. * @param draggable
  760. * Whether or not the given element(s) should be draggable.
  761. */
  762. _setDraggable = function(element, draggable) {
  763. return _elementProxy(element, function(el, id) {
  764. draggableStates[id] = draggable;
  765. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  766. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  767. }
  768. });
  769. },
  770. /**
  771. * private method to do the business of hiding/showing.
  772. *
  773. * @param el
  774. * either Id of the element in question or a library specific
  775. * object for the element.
  776. * @param state
  777. * String specifying a value for the css 'display' property
  778. * ('block' or 'none').
  779. */
  780. _setVisible = function(el, state, alsoChangeEndpoints) {
  781. state = state === "block";
  782. var endpointFunc = null;
  783. if (alsoChangeEndpoints) {
  784. if (state) endpointFunc = function(ep) {
  785. ep.setVisible(true, true, true);
  786. };
  787. else endpointFunc = function(ep) {
  788. ep.setVisible(false, true, true);
  789. };
  790. }
  791. var id = _getAttribute(el, "id");
  792. _operation(id, function(jpc) {
  793. if (state && alsoChangeEndpoints) {
  794. // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
  795. // this block will only set a connection to be visible if the other endpoint in the connection is also visible.
  796. var oidx = jpc.sourceId === id ? 1 : 0;
  797. if (jpc.endpoints[oidx].isVisible()) jpc.setVisible(true);
  798. }
  799. else // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
  800. jpc.setVisible(state);
  801. }, endpointFunc);
  802. },
  803. /**
  804. * toggles the draggable state of the given element(s).
  805. *
  806. * @param el
  807. * either an id, or an element object, or a list of
  808. * ids/element objects.
  809. */
  810. _toggleDraggable = function(el) {
  811. return _elementProxy(el, function(el, elId) {
  812. var state = draggableStates[elId] == null ? false : draggableStates[elId];
  813. state = !state;
  814. draggableStates[elId] = state;
  815. jsPlumb.CurrentLibrary.setDraggable(el, state);
  816. return state;
  817. });
  818. },
  819. /**
  820. * private method to do the business of toggling hiding/showing.
  821. *
  822. * @param elId
  823. * Id of the element in question
  824. */
  825. _toggleVisible = function(elId, changeEndpoints) {
  826. var endpointFunc = null;
  827. if (changeEndpoints) {
  828. endpointFunc = function(ep) {
  829. var state = ep.isVisible();
  830. ep.setVisible(!state);
  831. };
  832. }
  833. _operation(elId, function(jpc) {
  834. var state = jpc.isVisible();
  835. jpc.setVisible(!state);
  836. }, endpointFunc);
  837. // todo this should call _elementProxy, and pass in the
  838. // _operation(elId, f) call as a function. cos _toggleDraggable does
  839. // that.
  840. },
  841. /**
  842. * updates the offset and size for a given element, and stores the
  843. * values. if 'offset' is not null we use that (it would have been
  844. * passed in from a drag call) because it's faster; but if it is null,
  845. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  846. */
  847. _updateOffset = function(params) {
  848. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId;
  849. if (!recalc) {
  850. if (timestamp && timestamp === offsetTimestamps[elId])
  851. return offsets[elId];
  852. }
  853. if (recalc || !offset) { // if forced repaint or no offset
  854. // available, we recalculate.
  855. // get the current size and offset, and store them
  856. var s = _getElementObject(elId);
  857. if (s != null) {
  858. sizes[elId] = _getSize(s);
  859. offsets[elId] = _getOffset(s);
  860. offsetTimestamps[elId] = timestamp;
  861. }
  862. } else {
  863. offsets[elId] = offset;
  864. if (sizes[elId] == null) {
  865. var s = _getElementObject(elId);
  866. if (s != null)
  867. sizes[elId] = _getSize(s);
  868. }
  869. }
  870. if(offsets[elId] && !offsets[elId].right) {
  871. offsets[elId].right = offsets[elId].left + sizes[elId][0];
  872. offsets[elId].bottom = offsets[elId].top + sizes[elId][1];
  873. offsets[elId].width = sizes[elId][0];
  874. offsets[elId].height = sizes[elId][1];
  875. offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2);
  876. offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2);
  877. }
  878. return offsets[elId];
  879. },
  880. _getCachedData = function(elId) {
  881. var o = offsets[elId];
  882. if (!o) o = _updateOffset(elId);
  883. return {o:o, s:sizes[elId]};
  884. },
  885. /**
  886. * gets an id for the given element, creating and setting one if
  887. * necessary.
  888. */
  889. _getId = function(element, uuid) {
  890. var ele = _getElementObject(element);
  891. var id = _getAttribute(ele, "id");
  892. if (!id || id == "undefined") {
  893. // check if fixed uuid parameter is given
  894. if (arguments.length == 2 && arguments[1] != undefined)
  895. id = uuid;
  896. else
  897. id = "jsPlumb_" + _idstamp();
  898. _setAttribute(ele, "id", id);
  899. }
  900. return id;
  901. },
  902. /**
  903. * wraps one function with another, creating a placeholder for the
  904. * wrapped function if it was null. this is used to wrap the various
  905. * drag/drop event functions - to allow jsPlumb to be notified of
  906. * important lifecycle events without imposing itself on the user's
  907. * drag/drop functionality. TODO: determine whether or not we should
  908. * support an error handler concept, if one of the functions fails.
  909. *
  910. * @param wrappedFunction original function to wrap; may be null.
  911. * @param newFunction function to wrap the original with.
  912. * @param returnOnThisValue Optional. Indicates that the wrappedFunction should
  913. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  914. * note that this is a simple comparison and only works for primitives right now.
  915. */
  916. _wrap = function(wrappedFunction, newFunction, returnOnThisValue) {
  917. wrappedFunction = wrappedFunction || function() { };
  918. newFunction = newFunction || function() { };
  919. return function() {
  920. var r = null;
  921. try {
  922. r = newFunction.apply(this, arguments);
  923. } catch (e) {
  924. _log(_currentInstance, 'jsPlumb function failed : ' + e);
  925. }
  926. if (returnOnThisValue == null || (r !== returnOnThisValue)) {
  927. try {
  928. wrappedFunction.apply(this, arguments);
  929. } catch (e) {
  930. _log(_currentInstance, 'wrapped function failed : ' + e);
  931. }
  932. }
  933. return r;
  934. };
  935. };
  936. /*
  937. * Property: connectorClass
  938. * The CSS class to set on Connection elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  939. */
  940. this.connectorClass = "_jsPlumb_connector";
  941. /*
  942. * Property: endpointClass
  943. * The CSS class to set on Endpoint elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  944. */
  945. this.endpointClass = "_jsPlumb_endpoint";
  946. /*
  947. * Property: overlayClass
  948. * The CSS class to set on an Overlay that is an HTML element. This value is a String and can have multiple classes; the entire String is appended as-is.
  949. */
  950. this.overlayClass = "_jsPlumb_overlay";
  951. this.Anchors = {};
  952. this.Connectors = {
  953. "canvas":{},
  954. "svg":{},
  955. "vml":{}
  956. };
  957. this.Endpoints = {
  958. "canvas":{},
  959. "svg":{},
  960. "vml":{}
  961. };
  962. this.Overlays = {
  963. "canvas":{},
  964. "svg":{},
  965. "vml":{}
  966. };
  967. // ************************ PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS *****************************************
  968. /*
  969. * Function: bind
  970. * Bind to an event on jsPlumb.
  971. *
  972. * Parameters:
  973. * event - the event to bind. Available events on jsPlumb are:
  974. * - *jsPlumbConnection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
  975. * - *jsPlumbConnectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
  976. * - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
  977. * - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
  978. * - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
  979. * - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
  980. *
  981. * callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
  982. */
  983. /*
  984. * Function: clearListeners
  985. * Clears either all listeners, or listeners for some specific event.
  986. *
  987. * Parameters:
  988. * event - optional. constrains the clear to just listeners for this event.
  989. */
  990. // *************** END OF PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS ***********************************************************
  991. /*
  992. Function: addClass
  993. Helper method to abstract out differences in setting css classes on the different renderer types.
  994. */
  995. this.addClass = function(el, clazz) {
  996. return jsPlumb.CurrentLibrary.addClass(el, clazz);
  997. };
  998. /*
  999. Function: removeClass
  1000. Helper method to abstract out differences in setting css classes on the different renderer types.
  1001. */
  1002. this.removeClass = function(el, clazz) {
  1003. return jsPlumb.CurrentLibrary.removeClass(el, clazz);
  1004. };
  1005. /*
  1006. Function: hasClass
  1007. Helper method to abstract out differences in testing for css classes on the different renderer types.
  1008. */
  1009. this.hasClass = function(el, clazz) {
  1010. return jsPlumb.CurrentLibrary.hasClass(el, clazz);
  1011. };
  1012. /*
  1013. Function: addEndpoint
  1014. Adds an <Endpoint> to a given element or elements.
  1015. Parameters:
  1016. el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  1017. params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
  1018. referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
  1019. shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
  1020. this object are anything that 'params' can contain. See <Endpoint>.
  1021. Returns:
  1022. The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
  1023. See Also:
  1024. <addEndpoints>
  1025. */
  1026. this.addEndpoint = function(el, params, referenceParams) {
  1027. referenceParams = referenceParams || {};
  1028. var p = jsPlumb.extend({}, referenceParams);
  1029. jsPlumb.extend(p, params);
  1030. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
  1031. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  1032. //p.scope="_jsPlumb_DefaultScope";
  1033. //p.scope="fff";
  1034. // YUI wrapper
  1035. el = _convertYUICollection(el);
  1036. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  1037. for (var i = 0; i < inputs.length; i++) {
  1038. var _el = _getElementObject(inputs[i]), id = _getId(_el);
  1039. p.source = _el;
  1040. //p.scope="f";
  1041. _updateOffset({ elId : id });
  1042. var e = _newEndpoint(p);
  1043. _addToList(endpointsByElement, id, e);
  1044. var myOffset = offsets[id], myWH = sizes[id];
  1045. var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e });
  1046. e.paint({ anchorLoc : anchorLoc });
  1047. results.push(e);
  1048. }
  1049. return results.length == 1 ? results[0] : results;
  1050. };
  1051. /*
  1052. Function: addEndpoints
  1053. Adds a list of <Endpoint>s to a given element or elements.
  1054. Parameters:
  1055. target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  1056. endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
  1057. referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some shared parameters that you wanted to reuse when you added Endpoints to a number of elements.
  1058. Returns:
  1059. List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
  1060. See Also:
  1061. <addEndpoint>
  1062. */
  1063. this.addEndpoints = function(el, endpoints, referenceParams) {
  1064. var results = [];
  1065. for ( var i = 0; i < endpoints.length; i++) {
  1066. var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
  1067. if (e.constructor == Array)
  1068. Array.prototype.push.apply(results, e);
  1069. else results.push(e);
  1070. }
  1071. return results;
  1072. };
  1073. /*
  1074. Function: animate
  1075. This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
  1076. the 'step' function if necessary). This only supports the two-arg version of the animate call in jQuery, the one that takes an 'options' object as
  1077. the second arg. MooTools has only one method, a two arg one. Which is handy. YUI has a one-arg method, so jsPlumb merges 'properties' and 'options' together for YUI.
  1078. Parameters:
  1079. el - Element to animate. Either an id, or a selector representing the element.
  1080. properties - The 'properties' argument you want passed to the library's animate call.
  1081. options - The 'options' argument you want passed to the library's animate call.
  1082. Returns:
  1083. void
  1084. */
  1085. this.animate = function(el, properties, options) {
  1086. var ele = _getElementObject(el), id = _getAttribute(el, "id");
  1087. options = options || {};
  1088. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  1089. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  1090. options[stepFunction] = _wrap(options[stepFunction], function() {
  1091. _currentInstance.repaint(id);
  1092. });
  1093. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  1094. options[completeFunction] = _wrap(options[completeFunction],
  1095. function() {
  1096. _currentInstance.repaint(id);
  1097. });
  1098. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  1099. };
  1100. /**
  1101. * checks for a listener for the given condition, executing it if found, passing in the given value.
  1102. * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since
  1103. * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition"
  1104. * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these
  1105. * condition events anyway.
  1106. */
  1107. this.checkCondition = function(conditionName, value) {
  1108. var l = _currentInstance.getListener(conditionName);
  1109. var r = true;
  1110. if (l && l.length > 0) {
  1111. try {
  1112. for (var i = 0 ; i < l.length; i++) {
  1113. r = r && l[i](value);
  1114. }
  1115. }
  1116. catch (e) {
  1117. _log(_currentInstance, "cannot check condition [" + conditionName + "]" + e);
  1118. }
  1119. }
  1120. return r;
  1121. };
  1122. /*
  1123. Function: connect
  1124. Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
  1125. Parameters:
  1126. params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
  1127. referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
  1128. Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
  1129. Returns:
  1130. The newly created <Connection>.
  1131. */
  1132. this.connect = function(params, referenceParams) {
  1133. // prepare a final set of parameters to create connection with
  1134. var _p = _prepareConnectionParams(params, referenceParams);
  1135. // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams
  1136. // will return null (and log something) if either endpoint was full. what would be nicer is to
  1137. // create a dedicated 'error' object.
  1138. if (_p) {
  1139. // a connect call will delete its created endpoints on detach, unless otherwise specified.
  1140. // this is because the endpoints belong to this connection only, and are no use to
  1141. // anyone else, so they hang around like a bad smell.
  1142. if (_p.deleteEndpointsOnDetach == null)
  1143. _p.deleteEndpointsOnDetach = true;
  1144. // create the connection. it is not yet registered
  1145. var jpc = _newConnection(_p);
  1146. // now add it the model, fire an event, and redraw
  1147. _finaliseConnection(jpc, _p);
  1148. return jpc;
  1149. }
  1150. };
  1151. /*
  1152. Function: deleteEndpoint
  1153. Deletes an Endpoint and removes all Connections it has (which removes the Connections from the other Endpoints involved too)
  1154. Parameters:
  1155. object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
  1156. Returns:
  1157. void
  1158. */
  1159. this.deleteEndpoint = function(object) {
  1160. var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object;
  1161. if (endpoint) {
  1162. var uuid = endpoint.getUuid();
  1163. if (uuid) endpointsByUUID[uuid] = null;
  1164. endpoint.detachAll();
  1165. _removeElement(endpoint.canvas, endpoint.parent);
  1166. // remove from endpointsbyElement
  1167. // DEPRECATED. SHOULD NOT BE NECESSARY ONCE THE ANCHOR MANAGER IS WORKING PROPERLY.
  1168. _currentInstance.anchorManager.deleteEndpoint(endpoint);
  1169. for (var e in endpointsByElement) {
  1170. var endpoints = endpointsByElement[e];
  1171. if (endpoints) {
  1172. var newEndpoints = [];
  1173. for (var i = 0; i < endpoints.length; i++)
  1174. if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
  1175. endpointsByElement[e] = newEndpoints;
  1176. }
  1177. }
  1178. delete endpoint;
  1179. }
  1180. };
  1181. /*
  1182. Function: deleteEveryEndpoint
  1183. Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
  1184. between this method and jsPlumb.reset).
  1185. Returns:
  1186. void
  1187. */
  1188. this.deleteEveryEndpoint = function() {
  1189. for ( var id in endpointsByElement) {
  1190. var endpoints = endpointsByElement[id];
  1191. if (endpoints && endpoints.length) {
  1192. for ( var i = 0; i < endpoints.length; i++) {
  1193. _currentInstance.deleteEndpoint(endpoints[i]);
  1194. }
  1195. }
  1196. }
  1197. delete endpointsByElement;
  1198. endpointsByElement = {};
  1199. delete endpointsByUUID;
  1200. endpointsByUUID = {};
  1201. };
  1202. var fireDetachEvent = function(jpc, doFireEvent) {
  1203. // may have been given a connection, or in special cases, an object
  1204. var connType = jsPlumb.Defaults.ConnectionType || jsPlumb.getDefaultConnectionType(),
  1205. argIsConnection = jpc.constructor == connType,
  1206. params = argIsConnection ? {
  1207. connection:jpc,
  1208. source : jpc.source, target : jpc.target,
  1209. sourceId : jpc.sourceId, targetId : jpc.targetId,
  1210. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  1211. } : jpc;
  1212. if (doFireEvent) _currentInstance.fire("jsPlumbConnectionDetached", params);
  1213. _currentInstance.anchorManager.connectionDetached(params);
  1214. };
  1215. /*
  1216. Function: detach
  1217. Detaches and then removes a <Connection>. From 1.3.5 this method has been altered to remove support for
  1218. specifying Connections by various parameters; you can now pass in a Connection as the first argument and
  1219. an optional parameters object as a second argument. If you need the functionality this method provided
  1220. before 1.3.5 then you should use the getConnections method to get the list of Connections to detach, and
  1221. then iterate through them, calling this for each one.
  1222. Parameters:
  1223. connection - the <Connection> to detach
  1224. params - optional parameters to the detach call. valid values here are
  1225. fireEvent : defaults to false; indicates you want jsPlumb to fire a connection
  1226. detached event. The thinking behind this is that if you made a programmatic
  1227. call to detach an event, you probably don't need the callback.
  1228. forceDetach : defaults to false. allows you to override any beforeDetach listeners that may be registered.
  1229. Returns:
  1230. true if successful, false if not.
  1231. */
  1232. this.detach = function() {
  1233. if (arguments.length == 0) return;
  1234. var connType = jsPlumb.Defaults.ConnectionType || jsPlumb.getDefaultConnectionType(),
  1235. firstArgIsConnection = arguments[0].constructor == connType,
  1236. params = arguments.length == 2 ? firstArgIsConnection ? (arguments[1] || {}) : arguments[0] : arguments[0],
  1237. fireEvent = (params.fireEvent !== false),
  1238. forceDetach = params.forceDetach,
  1239. connection = firstArgIsConnection ? arguments[0] : params.connection;
  1240. if (connection) {
  1241. if (forceDetach || (connection.isDetachAllowed(connection)
  1242. && connection.endpoints[0].isDetachAllowed(connection)
  1243. && connection.endpoints[1].isDetachAllowed(connection))) {
  1244. if (forceDetach || _currentInstance.checkCondition("beforeDetach", connection))
  1245. connection.endpoints[0].detach(connection, false, true, fireEvent); // TODO check this param iscorrect for endpoint's detach method
  1246. }
  1247. }
  1248. else {
  1249. var _p = jsPlumb.extend( {}, params); // a backwards compatibility hack: source should be thought of as 'params' in this case.
  1250. // test for endpoint uuids to detach
  1251. if (_p.uuids) {
  1252. _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]), fireEvent);
  1253. } else if (_p.sourceEndpoint && _p.targetEndpoint) {
  1254. _p.sourceEndpoint.detachFrom(_p.targetEndpoint);
  1255. } else {
  1256. var sourceId = _getId(_p.source),
  1257. targetId = _getId(_p.target);
  1258. _operation(sourceId, function(jpc) {
  1259. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  1260. if (_currentInstance.checkCondition("beforeDetach", jpc)) {
  1261. jpc.endpoints[0].detach(jpc, false, true, fireEvent);
  1262. }
  1263. }
  1264. });
  1265. }
  1266. }
  1267. };
  1268. /*
  1269. Function: detachAllConnections
  1270. Removes all an element's Connections.
  1271. Parameters:
  1272. el - either the id of the element, or a selector for the element.
  1273. params - optional parameters. alowed values:
  1274. fireEvent : defaults to true, whether or not to fire the detach event.
  1275. Returns:
  1276. void
  1277. */
  1278. this.detachAllConnections = function(el, params) {
  1279. params = params || {};
  1280. el = _getElementObject(el);
  1281. var id = _getAttribute(el, "id"),
  1282. endpoints = endpointsByElement[id];
  1283. if (endpoints && endpoints.length) {
  1284. for ( var i = 0; i < endpoints.length; i++) {
  1285. endpoints[i].detachAll(params.fireEvent);
  1286. }
  1287. }
  1288. };
  1289. /*
  1290. Function: detachEveryConnection
  1291. Remove all Connections from all elements, but leaves Endpoints in place.
  1292. Parameters:
  1293. params - optional params object containing:
  1294. fireEvent : whether or not to fire detach events. defaults to true.
  1295. Returns:
  1296. void
  1297. See Also:
  1298. <removeEveryEndpoint>
  1299. */
  1300. this.detachEveryConnection = function(params) {
  1301. params = params || {};
  1302. for ( var id in endpointsByElement) {
  1303. var endpoints = endpointsByElement[id];
  1304. if (endpoints && endpoints.length) {
  1305. for ( var i = 0; i < endpoints.length; i++) {
  1306. endpoints[i].detachAll(params.fireEvent);
  1307. }
  1308. }
  1309. }
  1310. delete connectionsByScope;
  1311. connectionsByScope = {};
  1312. };
  1313. /*
  1314. Function: draggable
  1315. Initialises the draggability of some element or elements. You should use this instead of y
  1316. our library's draggable method so that jsPlumb can setup the appropriate callbacks. Your
  1317. underlying library's drag method is always called from this method.
  1318. Parameters:
  1319. el - either an element id, a list of element ids, or a selector.
  1320. options - options to pass through to the underlying library
  1321. Returns:
  1322. void
  1323. */
  1324. // TODO it would be nice if this supported a selector string, instead of an id.
  1325. this.draggable = function(el, options) {
  1326. if (typeof el == 'object' && el.length) {
  1327. for ( var i = 0; i < el.length; i++) {
  1328. var ele = _getElementObject(el[i]);
  1329. if (ele) _initDraggableIfNecessary(ele, true, options);
  1330. }
  1331. }
  1332. else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced
  1333. // into the library adapters (for jquery and mootools aswell)
  1334. for ( var i = 0; i < el._nodes.length; i++) {
  1335. var ele = _getElementObject(el._nodes[i]);
  1336. if (ele) _initDraggableIfNecessary(ele, true, options);
  1337. }
  1338. }
  1339. else {
  1340. var ele = _getElementObject(el);
  1341. if (ele) _initDraggableIfNecessary(ele, true, options);
  1342. }
  1343. };
  1344. /*
  1345. Function: extend
  1346. Wraps the underlying library's extend functionality.
  1347. Parameters:
  1348. o1 - object to extend
  1349. o2 - object to extend o1 with
  1350. Returns:
  1351. o1, extended with all properties from o2.
  1352. */
  1353. this.extend = function(o1, o2) {
  1354. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1355. };
  1356. /*
  1357. * Function: getDefaultEndpointType
  1358. * Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
  1359. * you would make a call like this in your class's constructor:
  1360. * jsPlumb.getDefaultEndpointType().apply(this, arguments);
  1361. *
  1362. * Returns:
  1363. * the default Endpoint function used by jsPlumb.
  1364. */
  1365. this.getDefaultEndpointType = function() {
  1366. return Endpoint;
  1367. };
  1368. /*
  1369. * Function: getDefaultConnectionType
  1370. * Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
  1371. * you would make a call like this in your class's constructor:
  1372. * jsPlumb.getDefaultConnectionType().apply(this, arguments);
  1373. *
  1374. * Returns:
  1375. * the default Connection function used by jsPlumb.
  1376. */
  1377. this.getDefaultConnectionType = function() {
  1378. return Connection;
  1379. };
  1380. /*
  1381. * Function: getConnections
  1382. * Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
  1383. * the result will be a list of connections having that scope (passing in no scope at all will result in jsPlumb assuming you want the
  1384. * default scope). If multiple scopes are passed in, the return value will be a map of { scope -> [ connection... ] }.
  1385. *
  1386. * Parameters
  1387. * scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
  1388. * of connections that are in the given scope.
  1389. * options - if the argument is a JS object, you can specify a finer-grained filter:
  1390. *
  1391. * - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes.
  1392. * - *source* either a string representing an element id, or a selector. constrains the result to connections having this source.
  1393. * - *target* either a string representing an element id, or a selector. constrains the result to connections having this target.
  1394. *
  1395. */
  1396. this.getConnections = function(options) {
  1397. if (!options) {
  1398. options = {};
  1399. } else if (options.constructor == String) {
  1400. options = { "scope": options };
  1401. }
  1402. var prepareList = function(input) {
  1403. var r = [];
  1404. if (input) {
  1405. if (typeof input == 'string')
  1406. r.push(input);
  1407. else
  1408. r = input;
  1409. }
  1410. return r;
  1411. };
  1412. var scope = options.scope || jsPlumb.getDefaultScope(),
  1413. scopes = prepareList(scope),
  1414. sources = prepareList(options.source),
  1415. targets = prepareList(options.target),
  1416. filter = function(list, value) {
  1417. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1418. },
  1419. results = scopes.length > 1 ? {} : [],
  1420. _addOne = function(scope, obj) {
  1421. if (scopes.length > 1) {
  1422. var ss = results[scope];
  1423. if (ss == null) {
  1424. ss = []; results[scope] = ss;
  1425. }
  1426. ss.push(obj);
  1427. } else results.push(obj);
  1428. };
  1429. for ( var i in connectionsByScope) {
  1430. if (filter(scopes, i)) {
  1431. for ( var j = 0; j < connectionsByScope[i].length; j++) {
  1432. var c = connectionsByScope[i][j];
  1433. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1434. _addOne(i, c);
  1435. }
  1436. }
  1437. }
  1438. return results;
  1439. };
  1440. /*
  1441. * Function: getAllConnections
  1442. * Gets all connections, as a map of { scope -> [ connection... ] }.
  1443. */
  1444. this.getAllConnections = function() {
  1445. return connectionsByScope;
  1446. };
  1447. /*
  1448. * Function: getDefaultScope
  1449. * Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a
  1450. * scope to an endpoint or connection allows you to support different
  1451. * types of connections in the same UI. but if you're only interested in
  1452. * one type of connection, you don't need to supply a scope. this method
  1453. * will probably be used by very few people; it's good for testing
  1454. * though.
  1455. */
  1456. this.getDefaultScope = function() {
  1457. return DEFAULT_SCOPE;
  1458. };
  1459. /*
  1460. Function: getEndpoint
  1461. Gets an Endpoint by UUID
  1462. Parameters:
  1463. uuid - the UUID for the Endpoint
  1464. Returns:
  1465. Endpoint with the given UUID, null if nothing found.
  1466. */
  1467. this.getEndpoint = _getEndpoint;
  1468. /**
  1469. * Function:getEndpoints
  1470. * Gets the list of Endpoints for a given selector, or element id.
  1471. * @param el
  1472. * @return
  1473. */
  1474. this.getEndpoints = function(el) {
  1475. return endpointsByElement[_getId(el)];
  1476. };
  1477. /*
  1478. * Gets an element's id, creating one if necessary. really only exposed
  1479. * for the lib-specific functionality to access; would be better to pass
  1480. * the current instance into the lib-specific code (even though this is
  1481. * a static call. i just don't want to expose it to the public API).
  1482. */
  1483. this.getId = _getId;
  1484. this.getOffset = function(id) {
  1485. var o = offsets[id];
  1486. return _updateOffset({elId:id});
  1487. };
  1488. this.getSelector = function(spec) {
  1489. return jsPlumb.CurrentLibrary.getSelector(spec);
  1490. };
  1491. this.getSize = function(id) {
  1492. var s = sizes[id];
  1493. if (!s) _updateOffset({elId:id});
  1494. return sizes[id];
  1495. };
  1496. this.appendElement = _appendElement;
  1497. /*
  1498. Function: hide
  1499. Sets an element's connections to be hidden.
  1500. Parameters:
  1501. el - either the id of the element, or a selector for the element.
  1502. changeEndpoints - whether not to also hide endpoints on the element. by default this is false.
  1503. Returns:
  1504. void
  1505. */
  1506. this.hide = function(el, changeEndpoints) {
  1507. _setVisible(el, "none", changeEndpoints);
  1508. };
  1509. // exposed for other objects to use to get a unique id.
  1510. this.idstamp = _idstamp;
  1511. /**
  1512. * callback from the current library to tell us to prepare ourselves (attach
  1513. * mouse listeners etc; can't do that until the library has provided a bind method)
  1514. * @return
  1515. */
  1516. this.init = function() {
  1517. if (!initialized) {
  1518. _currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run.
  1519. var bindOne = function(event) {
  1520. jsPlumb.CurrentLibrary.bind(document, event, function(e) {
  1521. if (!_currentInstance.currentlyDragging && _mouseEventsEnabled && renderMode == jsPlumb.CANVAS) {
  1522. // try connections first
  1523. for (var scope in connectionsByScope) {
  1524. var c = connectionsByScope[scope];
  1525. for (var i = 0; i < c.length; i++) {
  1526. var t = c[i].connector[event](e);
  1527. if (t) return;
  1528. }
  1529. }
  1530. for (var el in endpointsByElement) {
  1531. var ee = endpointsByElement[el];
  1532. for (var i = 0; i < ee.length; i++) {
  1533. if (ee[i].endpoint[event](e)) return;
  1534. }
  1535. }
  1536. }
  1537. });
  1538. };
  1539. bindOne("click");bindOne("dblclick");bindOne("mousemove");bindOne("mousedown");bindOne("mouseup");
  1540. initialized = true;
  1541. _currentInstance.fire("ready");
  1542. }
  1543. };
  1544. this.log = log;
  1545. this.jsPlumbUIComponent = jsPlumbUIComponent;
  1546. this.EventGenerator = EventGenerator;
  1547. /*
  1548. * Creates an anchor with the given params.
  1549. *
  1550. *
  1551. * Returns: The newly created Anchor.
  1552. */
  1553. this.makeAnchor = function() {
  1554. if (arguments.length == 0) return null;
  1555. var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null;
  1556. if (!jsPlumbInstance)
  1557. throw "NO JSPLUMB SET";
  1558. // if it appears to be an anchor already...
  1559. if (specimen.compute && specimen.getOrientation) return specimen; //TODO hazy here about whether it should be added or is already added somehow.
  1560. // is it the name of an anchor type?
  1561. else if (typeof specimen == "string") {
  1562. newAnchor = _currentInstance.Anchors[arguments[0]]({elementId:elementId, jsPlumbInstance:_currentInstance});
  1563. }
  1564. // is it an array? it will be one of:
  1565. // an array of [name, params] - this defines a single anchor
  1566. // an array of arrays - this defines some dynamic anchors
  1567. // an array of numbers - this defines a single anchor.
  1568. else if (specimen.constructor == Array) {
  1569. if (specimen[0].constructor == Array || specimen[0].constructor == String) {
  1570. if (specimen.length == 2 && specimen[0].constructor == String && specimen[1].constructor == Object) {
  1571. var pp = jsPlumb.extend({elementId:elementId, jsPlumbInstance:_currentInstance}, specimen[1]);
  1572. newAnchor = _currentInstance.Anchors[specimen[0]](pp);
  1573. }
  1574. else
  1575. newAnchor = new DynamicAnchor(specimen, null, elementId);
  1576. }
  1577. else {
  1578. var anchorParams = {
  1579. x:specimen[0], y:specimen[1],
  1580. orientation : (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0,0],
  1581. offsets : (specimen.length == 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ],
  1582. elementId:elementId
  1583. };
  1584. newAnchor = new Anchor(anchorParams);
  1585. newAnchor.clone = function() { return new Anchor(anchorParams); };
  1586. }
  1587. }
  1588. if (!newAnchor.id) newAnchor.id = "anchor_" + _idstamp();
  1589. return newAnchor;
  1590. };
  1591. /**
  1592. * makes a list of anchors from the given list of types or coords, eg
  1593. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  1594. */
  1595. this.makeAnchors = function(types, elementId, jsPlumbInstance) {
  1596. var r = [];
  1597. for ( var i = 0; i < types.length; i++) {
  1598. if (typeof types[i] == "string")
  1599. r.push(_currentInstance.Anchors[types[i]]({elementId:elementId, jsPlumbInstance:jsPlumbInstance}));
  1600. else if (types[i].constructor == Array)
  1601. r.push(jsPlumb.makeAnchor(types[i], elementId, jsPlumbInstance));
  1602. }
  1603. return r;
  1604. };
  1605. /**
  1606. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  1607. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  1608. * not need to provide this - i think).
  1609. */
  1610. this.makeDynamicAnchor = function(anchors, anchorSelector) {
  1611. return new DynamicAnchor(anchors, anchorSelector);
  1612. };
  1613. /**
  1614. * Function: makeTarget
  1615. * Makes some DOM element a Connection target, allowing you to drag connections to it
  1616. * without having to register any Endpoints on it first. When a Connection is established,
  1617. * the endpoint spec that was passed in to this method is used to create a suitable
  1618. * Endpoint (the default will be used if you do not provide one).
  1619. *
  1620. * Parameters:
  1621. * el - string id or element selector for the element to make a target.
  1622. * params - JS object containing parameters:
  1623. * endpoint optional. specification of an endpoint to create when a connection is created.
  1624. * scope optional. scope for the drop zone.
  1625. * dropOptions optional. same stuff as you would pass to dropOptions of an Endpoint definition.
  1626. * deleteEndpointsOnDetach optional, defaults to true. whether or not to delete
  1627. * any Endpoints created by a connection to this target if
  1628. * the connection is subsequently detached. this will not
  1629. * remove Endpoints that have had more Connections attached
  1630. * to them after they were created.
  1631. *
  1632. *
  1633. */
  1634. var _targetEndpointDefinitions = {};
  1635. this.makeTarget = function(el, params, referenceParams) {
  1636. var p = jsPlumb.extend({}, referenceParams);
  1637. jsPlumb.extend(p, params);
  1638. var jpcl = jsPlumb.CurrentLibrary,
  1639. targetScope = p.scope || _currentInstance.Defaults.Scope,
  1640. deleteEndpointsOnDetach = p.deleteEndpointsOnDetach || true,
  1641. _doOne = function(_el) {
  1642. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  1643. // and use the endpoint definition if found.
  1644. var elid = _getId(_el);
  1645. _targetEndpointDefinitions[elid] = p.endpoint;
  1646. var dropOptions = jsPlumb.extend({}, p.dropOptions || {}),
  1647. _drop = function() {
  1648. _currentInstance.currentlyDragging = false;
  1649. var draggable = _getElementObject(jpcl.getDragObject(arguments)),
  1650. id = _getAttribute(draggable, "dragId"),
  1651. // restore the original scope if necessary (issue 57)
  1652. scope = _getAttribute(draggable, "originalScope"),
  1653. jpc = floatingConnections[id],
  1654. source = jpc.endpoints[0],
  1655. _endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : {};
  1656. // use defaults for endpoint style, if not present..this either uses EndpointStyle, or EndpointStyles[1],
  1657. // if it is present, since this is a target endpoint.
  1658. // TODO - this should be a helper method. makeTarget should use it too. give it an endpoint
  1659. _endpoint.paintStyle = _endpoint.paintStyle ||
  1660. _currentInstance.Defaults.EndpointStyles[1] ||
  1661. _currentInstance.Defaults.EndpointStyle ||
  1662. jsPlumb.Defaults.EndpointStyles[1] ||
  1663. jsPlumb.Defaults.EndpointStyle;
  1664. _endpoint.hoverPaintStyle = _endpoint.hoverPaintStyle ||
  1665. _currentInstance.Defaults.EndpointHoverStyles[1] ||
  1666. _currentInstance.Defaults.EndpointHoverStyle ||
  1667. jsPlumb.Defaults.EndpointHoverStyles[1] ||
  1668. jsPlumb.Defaults.EndpointHoverStyle;
  1669. _endpoint.anchor = _endpoint.anchor ||
  1670. _currentInstance.Defaults.Anchors[1] ||
  1671. _currentInstance.Defaults.Anchor ||
  1672. jsPlumb.Defaults.Anchors[1] ||
  1673. jsPlumb.Defaults.Anchor;
  1674. // unlock the source anchor to allow it to refresh its position if necessary
  1675. source.anchor.locked = false;
  1676. // if (!jpcl.hasClass(draggable, _currentInstance.endpointClass)) return;
  1677. if (scope) jpcl.setDragScope(draggable, scope);
  1678. // check if drop is allowed here.
  1679. var _continue = jpc.isDropAllowed(jpc.sourceId, _getId(_el), jpc.scope);
  1680. // regardless of whether the connection is ok, reconfigure the existing connection to
  1681. // point at the current info. we need this to be correct for the detach event that will follow.
  1682. // clear the source endpoint from the list to detach. we will detach this connection at this
  1683. // point, but we want to keep the source endpoint. the target is a floating endpoint and should
  1684. // be removed. TODO need to figure out whether this code can result in endpoints kicking around
  1685. // when they shouldnt be. like is this a full detach of a connection? can it be?
  1686. if (jpc.endpointsToDeleteOnDetach) {
  1687. if (source === jpc.endpointsToDeleteOnDetach[0])
  1688. jpc.endpointsToDeleteOnDetach[0] = null;
  1689. else if (source === jpc.endpointsToDeleteOnDetach[1])
  1690. jpc.endpointsToDeleteOnDetach[1] = null;
  1691. }
  1692. // reinstate any suspended endpoint; this just puts the connection back into
  1693. // a state in which it will report sensible values if someone asks it about
  1694. // its target. we're going to throw this connection away shortly so it doesnt matter
  1695. // if we manipulate it a bit.
  1696. if (jpc.suspendedEndpoint) {
  1697. jpc.targetId = jpc.suspendedEndpoint.elementId;
  1698. jpc.target = jpcl.getElementObject(jpc.suspendedEndpoint.elementId);
  1699. jpc.endpoints[1] = jpc.suspendedEndpoint;
  1700. }
  1701. if (_continue) {
  1702. // detach this connection from the source.
  1703. source.detach(jpc, false, true, true);//source.endpointWillMoveAfterConnection);
  1704. // make a new Endpoint for the target
  1705. var newEndpoint = jsPlumb.addEndpoint(_el, _endpoint);
  1706. // if the anchor has a 'positionFinder' set, then delegate to that function to find
  1707. // out where to locate the anchor.
  1708. if (newEndpoint.anchor.positionFinder != null) {
  1709. var dropPosition = jpcl.getUIPosition(arguments),
  1710. elPosition = jpcl.getOffset(_el),
  1711. elSize = jpcl.getSize(_el),
  1712. ap = newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor);
  1713. newEndpoint.anchor.x = ap[0];
  1714. newEndpoint.anchor.y = ap[1];
  1715. // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to
  1716. // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation
  1717. // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be
  1718. // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which
  1719. // the target is furthest away from the source.
  1720. }
  1721. var c = jsPlumb.connect({
  1722. source:source,
  1723. target:newEndpoint,
  1724. scope:scope,
  1725. previousConnection:jpc,
  1726. container:jpc.parent,
  1727. // 'endpointWillMoveAfterConnection' is set by the makeSource function, and it indicates that the
  1728. // given endpoint will actually transfer from the element it is currently attached to to some other
  1729. // element after a connection has been established. in that case, we do not want to fire the
  1730. // connection event, since it will have the wrong data in it; makeSource will do it for us.
  1731. // this is controlled by the 'parent' parameter on a makeSource call.
  1732. doNotFireConnectionEvent:source.endpointWillMoveAfterConnection
  1733. });
  1734. if (deleteEndpointsOnDetach)
  1735. c.endpointsToDeleteOnDetach = [ source, newEndpoint ];
  1736. }
  1737. // if not allowed to drop...
  1738. else {
  1739. // TODO this code is identical (pretty much) to what happens when a connection
  1740. // dragged from a normal endpoint is in this situation. refactor.
  1741. // is this an existing connection, and will we reattach?
  1742. if (jpc.suspendedEndpoint) {
  1743. if (source.isReattach) {
  1744. jpc.setHover(false);
  1745. jpc.floatingAnchorIndex = null;
  1746. jpc.suspendedEndpoint.addConnection(jpc);
  1747. jsPlumb.repaint(source.elementId);
  1748. }
  1749. else
  1750. source.detach(jpc, false, true, true); // otherwise, detach the connection and tell everyone about it.
  1751. }
  1752. }
  1753. };
  1754. var dropEvent = jpcl.dragEvents['drop'];
  1755. dropOptions["scope"] = dropOptions["scope"] || targetScope;
  1756. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop);
  1757. jpcl.initDroppable(_el, dropOptions, true);
  1758. };
  1759. el = _convertYUICollection(el);
  1760. var inputs = el.length && el.constructor != String ? el : [ el ];
  1761. for (var i = 0; i < inputs.length; i++) {
  1762. _doOne(_getElementObject(inputs[i]));
  1763. }
  1764. };
  1765. /**
  1766. * helper method to make a list of elements drop targets.
  1767. * @param els
  1768. * @param params
  1769. * @param referenceParams
  1770. * @return
  1771. */
  1772. this.makeTargets = function(els, params, referenceParams) {
  1773. for ( var i = 0; i < els.length; i++) {
  1774. _currentInstance.makeTarget(els[i], params, referenceParams);
  1775. }
  1776. };
  1777. /**
  1778. * Function: makeSource
  1779. * Makes some DOM element a Connection source, allowing you to drag connections from it
  1780. * without having to register any Endpoints on it first. When a Connection is established,
  1781. * the endpoint spec that was passed in to this method is used to create a suitable
  1782. * Endpoint (the default will be used if you do not provide one).
  1783. *
  1784. * Parameters:
  1785. * el - string id or element selector for the element to make a source.
  1786. * params - JS object containing parameters:
  1787. * endpoint optional. specification of an endpoint to create when a connection is created.
  1788. * parent optional. the element to add Endpoints to when a Connection is established. if you omit this,
  1789. * Endpoints will be added to 'el'.
  1790. * scope optional. scope for the connections dragged from this element.
  1791. * dragOptions optional. same stuff as you would pass to dragOptions of an Endpoint definition.
  1792. * deleteEndpointsOnDetach optional, defaults to false. whether or not to delete
  1793. * any Endpoints created by a connection from this source if
  1794. * the connection is subsequently detached. this will not
  1795. * remove Endpoints that have had more Connections attached
  1796. * to them after they were created.
  1797. *
  1798. *
  1799. */
  1800. var _sourceEndpointDefinitions = {};
  1801. this.makeSource = function(el, params, referenceParams) {
  1802. var p = jsPlumb.extend({}, referenceParams);
  1803. jsPlumb.extend(p, params);
  1804. var jpcl = jsPlumb.CurrentLibrary,
  1805. _doOne = function(_el) {
  1806. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  1807. // and use the endpoint definition if found.
  1808. var elid = _getId(_el);
  1809. _sourceEndpointDefinitions[elid] = p.endpoint || {};
  1810. var stopEvent = jpcl.dragEvents["stop"],
  1811. dragEvent = jpcl.dragEvents["drag"],
  1812. dragOptions = jsPlumb.extend({ }, _sourceEndpointDefinitions[elid].dragOptions || {}),
  1813. ep = null,
  1814. endpointAddedButNoDragYet = false;
  1815. // make sure this method honours whatever defaults have been set for Endpoint.
  1816. _sourceEndpointDefinitions[elid].endpoint = _sourceEndpointDefinitions[elid].endpoint || _currentInstance.Defaults.Endpoints[0] || _currentInstance.Defaults.Endpoint;
  1817. // TODO this, and the makeTarget equivalent, and probably elsewhere, should all be handed off to
  1818. // some helper method that can make this decision for us.
  1819. _sourceEndpointDefinitions[elid].paintStyle = _sourceEndpointDefinitions[elid].paintStyle ||
  1820. _currentInstance.Defaults.EndpointStyles[0] ||
  1821. _currentInstance.Defaults.EndpointStyle ||
  1822. jsPlumb.Defaults.EndpointStyles[0] ||
  1823. jsPlumb.Defaults.EndpointStyle;
  1824. _sourceEndpointDefinitions[elid].hoverPaintStyle = _sourceEndpointDefinitions[elid].hoverPaintStyle ||
  1825. _currentInstance.Defaults.EndpointHoverStyles[0] ||
  1826. _currentInstance.Defaults.EndpointHoverStyle ||
  1827. jsPlumb.Defaults.EndpointHoverStyles[0] ||
  1828. jsPlumb.Defaults.EndpointHoverStyle;
  1829. _sourceEndpointDefinitions[elid].anchor = _sourceEndpointDefinitions[elid].anchor ||
  1830. _currentInstance.Defaults.Anchors[0] ||
  1831. _currentInstance.Defaults.Anchor ||
  1832. jsPlumb.Defaults.Anchors[0] ||
  1833. jsPlumb.Defaults.Anchor;
  1834. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() {
  1835. endpointAddedButNoDragYet = false;
  1836. });
  1837. dragOptions[stopEvent] = function() {
  1838. // here we need to do a couple of things;
  1839. // first determine whether or not a connection was dragged. if not, just delete this endpoint.
  1840. // ...if so, though, then we need to check to see if a 'parent' was specified in the
  1841. // options to makeSource. a 'parent' is a reference to an element other than the one from
  1842. // which the connection is dragged, and it indicates that after a successful connection, the
  1843. // endpoint should be moved off of this element and onto 'parent', using all of the
  1844. // options passed in to the makeSource call.
  1845. //
  1846. // one thing that occurs to me right now is that we dont really want the first
  1847. // connection to have fired a connection event. but how can we prevent it from doing so?
  1848. //
  1849. //
  1850. //_currentlyDown = false;
  1851. _currentInstance.currentlyDragging = false;
  1852. if (ep.connections.length == 0)
  1853. jsPlumb.deleteEndpoint(ep);
  1854. else {
  1855. jpcl.unbind(ep.canvas, "mousedown");
  1856. // reset the anchor to the anchor that was initially provided. the one we were using to drag
  1857. // the connection was just a placeholder that was located at the place the user pressed the
  1858. // mouse button to initiate the drag.
  1859. var anchorDef = _sourceEndpointDefinitions[elid].anchor || _currentInstance.Defaults.Anchor;
  1860. ep.anchor = jsPlumb.makeAnchor(anchorDef, elid, _currentInstance);
  1861. if (p.parent) {
  1862. var parent = jpcl.getElementObject(p.parent);
  1863. if (parent) {
  1864. var currentId = ep.elementId;
  1865. ep.setElement(parent);
  1866. ep.endpointWillMoveAfterConnection = false;
  1867. _currentInstance.anchorManager.rehomeEndpoint(currentId, parent);
  1868. var jpc = ep.connections[0]; // TODO will this always be correct?
  1869. _finaliseConnection(jpc);
  1870. _currentInstance.repaintEverything();
  1871. }
  1872. }
  1873. _currentInstance.repaint(elid);
  1874. }
  1875. };
  1876. // when the user presses the mouse, add an Endpoint
  1877. var mouseDownListener = function(e) {
  1878. // make sure we have the latest offset for this div
  1879. _updateOffset({elId:elid});
  1880. // and get it, and the div's size
  1881. var myOffset = offsets[elid], myWH = sizes[elid];
  1882. // if there is a parent, the endpoint will actually be added to it now, rather than the div
  1883. // that was the source. in that case, we have to adjust the anchor position so it refers to
  1884. // the parent.
  1885. if (p.parent) {
  1886. var pEl = jsPlumb.CurrentLibrary.getElementObject(p.parent),
  1887. pId = _getId(pEl);
  1888. _updateOffset({elId:pId});
  1889. myOffset = offsets[pId];
  1890. myWH = sizes[pId];
  1891. }
  1892. var x = ((e.pageX || e.page.x) - myOffset.left) / myWH[0],
  1893. y = ((e.pageY || e.page.y) - myOffset.top) / myWH[1];
  1894. // we need to override the anchor in here, and force 'isSource', but we don't want to mess with
  1895. // the params passed in, because after a connection is established we're going to reset the endpoint
  1896. // to have the anchor we were given.
  1897. var tempEndpointParams = {};
  1898. jsPlumb.extend(tempEndpointParams, _sourceEndpointDefinitions[elid]);
  1899. tempEndpointParams.isSource = true;
  1900. tempEndpointParams.anchor = [x,y,0,0];
  1901. tempEndpointParams.dragOptions = dragOptions;
  1902. // if a parent was given we need to turn that into a "container" argument. this is, by default,
  1903. // the parent of the element we will move to, so parent of p.parent in this case. however, if
  1904. // the user has specified a 'container' on the endpoint definition or on
  1905. // the defaults, we should use that.
  1906. if (p.parent) {
  1907. var potentialParent = tempEndpointParams.container || jsPlumb.Defaults.Container;
  1908. if (potentialParent)
  1909. tempEndpointParams.container = potentialParent;
  1910. else
  1911. tempEndpointParams.container = jsPlumb.CurrentLibrary.getParent(p.parent);
  1912. }
  1913. ep = jsPlumb.addEndpoint(elid, tempEndpointParams);
  1914. endpointAddedButNoDragYet = true;
  1915. // we set this to prevent connections from firing attach events before this function has had a chance
  1916. // to move the endpoint.
  1917. ep.endpointWillMoveAfterConnection = p.parent != null;
  1918. ep.endpointWillMoveTo = p.parent ? jpcl.getElementObject(p.parent) : null;
  1919. var _delTempEndpoint = function() {
  1920. // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools
  1921. // it is fired even if dragging has occurred, in which case we would blow away a perfectly
  1922. // legitimate endpoint, were it not for this check. the flag is set after adding an
  1923. // endpoint and cleared in a drag listener we set in the dragOptions above.
  1924. if(endpointAddedButNoDragYet) {
  1925. jsPlumb.deleteEndpoint(ep);
  1926. }
  1927. };
  1928. _currentInstance.registerListener(ep.canvas, "mouseup", _delTempEndpoint);
  1929. _currentInstance.registerListener(_el, "mouseup", _delTempEndpoint);
  1930. // and then trigger its mousedown event, which will kick off a drag, which will start dragging
  1931. // a new connection from this endpoint.
  1932. jpcl.trigger(ep.canvas, "mousedown", e);
  1933. };
  1934. // jpcl.bind(_el, "mousedown", mouseDownListener);
  1935. // register this on jsPlumb so that it can be cleared by a reset.
  1936. _currentInstance.registerListener(_el, "mousedown", mouseDownListener);
  1937. };
  1938. el = _convertYUICollection(el);
  1939. var inputs = el.length && el.constructor != String ? el : [ el ];
  1940. for (var i = 0; i < inputs.length; i++) {
  1941. _doOne(_getElementObject(inputs[i]));
  1942. }
  1943. };
  1944. /**
  1945. * helper method to make a list of elements connection sources.
  1946. * @param els
  1947. * @param params
  1948. * @param referenceParams
  1949. * @return
  1950. */
  1951. this.makeSources = function(els, params, referenceParams) {
  1952. for ( var i = 0; i < els.length; i++) {
  1953. _currentInstance.makeSource(els[i], params, referenceParams);
  1954. }
  1955. };
  1956. /*
  1957. Function: ready
  1958. Helper method to bind a function to jsPlumb's ready event.
  1959. */
  1960. this.ready = function(fn) {
  1961. _currentInstance.bind("ready", fn);
  1962. },
  1963. /*
  1964. Function: repaint
  1965. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1966. Parameters:
  1967. el - either the id of the element or a selector representing the element.
  1968. Returns:
  1969. void
  1970. See Also:
  1971. <repaintEverything>
  1972. */
  1973. this.repaint = function(el) {
  1974. var _processElement = function(el) { _draw(_getElementObject(el)); };
  1975. // support both lists...
  1976. if (typeof el == 'object')
  1977. for ( var i = 0; i < el.length; i++) _processElement(el[i]);
  1978. else // ...and single strings.
  1979. _processElement(el);
  1980. };
  1981. /*
  1982. Function: repaintEverything
  1983. Repaints all connections.
  1984. Returns:
  1985. void
  1986. See Also:
  1987. <repaint>
  1988. */
  1989. this.repaintEverything = function() {
  1990. var timestamp = _timestamp();
  1991. for ( var elId in endpointsByElement) {
  1992. _draw(_getElementObject(elId), null, timestamp);
  1993. }
  1994. };
  1995. /*
  1996. Function: removeAllEndpoints
  1997. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1998. Parameters:
  1999. el - either an element id, or a selector for an element.
  2000. Returns:
  2001. void
  2002. See Also:
  2003. <removeEndpoint>
  2004. */
  2005. this.removeAllEndpoints = function(el) {
  2006. var elId = _getAttribute(el, "id"),
  2007. ebe = endpointsByElement[elId];
  2008. if (ebe) {
  2009. for ( var i = 0; i < ebe.length; i++)
  2010. _currentInstance.deleteEndpoint(ebe[i]);
  2011. }
  2012. endpointsByElement[elId] = [];
  2013. };
  2014. /*
  2015. Removes every Endpoint in this instance of jsPlumb.
  2016. @deprecated use deleteEveryEndpoint instead
  2017. */
  2018. this.removeEveryEndpoint = this.deleteEveryEndpoint;
  2019. /*
  2020. Removes the given Endpoint from the given element.
  2021. @deprecated Use jsPlumb.deleteEndpoint instead (and note you dont need to supply the element. it's irrelevant).
  2022. */
  2023. this.removeEndpoint = function(el, endpoint) {
  2024. _currentInstance.deleteEndpoint(endpoint);
  2025. };
  2026. var _registeredListeners = {},
  2027. _unbindRegisteredListeners = function() {
  2028. for (var i in _registeredListeners) {
  2029. for (var j = 0; j < _registeredListeners[i].length; j++) {
  2030. var info = _registeredListeners[i][j];
  2031. jsPlumb.CurrentLibrary.unbind(info.el, info.event, info.listener);
  2032. }
  2033. }
  2034. _registeredListeners = {};
  2035. };
  2036. // internal register listener method. gives us a hook to clean things up
  2037. // with if the user calls jsPlumb.reset.
  2038. this.registerListener = function(el, type, listener) {
  2039. jsPlumb.CurrentLibrary.bind(el, type, listener);
  2040. _addToList(_registeredListeners, type, {el:el, event:type, listener:listener});
  2041. };
  2042. /*
  2043. Function:reset
  2044. Removes all endpoints and connections and clears the listener list. To keep listeners call jsPlumb.deleteEveryEndpoint instead of this.
  2045. */
  2046. this.reset = function() {
  2047. this.deleteEveryEndpoint();
  2048. this.clearListeners();
  2049. _unbindRegisteredListeners();
  2050. this.anchorManager.reset();
  2051. };
  2052. /*
  2053. Function: setAutomaticRepaint
  2054. Sets/unsets automatic repaint on window resize.
  2055. Parameters:
  2056. value - whether or not to automatically repaint when the window is resized.
  2057. Returns: void
  2058. */
  2059. this.setAutomaticRepaint = function(value) {
  2060. automaticRepaint = value;
  2061. };
  2062. /*
  2063. * Function: setDefaultScope
  2064. * Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
  2065. * scope to an Endpoint or Connection allows you to support different
  2066. * types of Connections in the same UI. If you're only interested in
  2067. * one type of Connection, you don't need to supply a scope. This method
  2068. * will probably be used by very few people; it just instructs jsPlumb
  2069. * to use a different key for the default scope.
  2070. *
  2071. * Parameters:
  2072. * scope - scope to set as default.
  2073. */
  2074. this.setDefaultScope = function(scope) {
  2075. DEFAULT_SCOPE = scope;
  2076. };
  2077. /*
  2078. * Function: setDraggable
  2079. * Sets whether or not a given element is
  2080. * draggable, regardless of what any jsPlumb command may request.
  2081. *
  2082. * Parameters:
  2083. * el - either the id for the element, or a selector representing the element.
  2084. *
  2085. * Returns:
  2086. * void
  2087. */
  2088. this.setDraggable = _setDraggable;
  2089. this.setDebugLog = function(debugLog) {
  2090. log = debugLog;
  2091. };
  2092. /*
  2093. * Function: setRepaintFunction
  2094. * Sets the function to fire when the window size has changed and a repaint was fired.
  2095. *
  2096. * Parameters:
  2097. * f - Function to execute.
  2098. *
  2099. * Returns: void
  2100. */
  2101. this.setRepaintFunction = function(f) {
  2102. repaintFunction = f;
  2103. };
  2104. /*
  2105. * Function: setMouseEventsEnabled
  2106. * Sets whether or not mouse events are enabled. Default is true.
  2107. *
  2108. * Parameters:
  2109. * enabled - whether or not mouse events should be enabled.
  2110. *
  2111. * Returns:
  2112. * void
  2113. */
  2114. this.setMouseEventsEnabled = function(enabled) {
  2115. _mouseEventsEnabled = enabled;
  2116. };
  2117. /*
  2118. * Constant for use with the setRenderMode method
  2119. */
  2120. this.CANVAS = "canvas";
  2121. /*
  2122. * Constant for use with the setRenderMode method
  2123. */
  2124. this.SVG = "svg";
  2125. this.VML = "vml";
  2126. /*
  2127. * Function: setRenderMode
  2128. * Sets render mode: jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that
  2129. * what you asked for is not supported (and that VML is). If you asked for VML but the browser does
  2130. * not support it, jsPlumb uses SVG.
  2131. *
  2132. * Returns:
  2133. * the render mode that jsPlumb set, which of course may be different from that requested.
  2134. */
  2135. this.setRenderMode = function(mode) {
  2136. if (mode)
  2137. mode = mode.toLowerCase();
  2138. else
  2139. return;
  2140. if (mode !== jsPlumb.CANVAS && mode !== jsPlumb.SVG && mode !== jsPlumb.VML) throw new Error("render mode must be one of jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML");
  2141. // now test we actually have the capability to do this.
  2142. if (mode === jsPlumb.CANVAS && canvasAvailable)
  2143. renderMode = jsPlumb.CANVAS;
  2144. else if (mode === jsPlumb.SVG && svgAvailable)
  2145. renderMode = jsPlumb.SVG;
  2146. else if (vmlAvailable)
  2147. renderMode = jsPlumb.VML;
  2148. return renderMode;
  2149. };
  2150. this.getRenderMode = function() { return renderMode; };
  2151. /*
  2152. * Function: show
  2153. * Sets an element's connections to be visible.
  2154. *
  2155. * Parameters:
  2156. * el - either the id of the element, or a selector for the element.
  2157. * changeEndpoints - whether or not to also change the visible state of the endpoints on the element. this also has a bearing on
  2158. * other connections on those endpoints: if their other endpoint is also visible, the connections are made visible.
  2159. *
  2160. * Returns:
  2161. * void
  2162. */
  2163. this.show = function(el, changeEndpoints) {
  2164. _setVisible(el, "block", changeEndpoints);
  2165. };
  2166. /*
  2167. * Function: sizeCanvas
  2168. * Helper to size a canvas. You would typically use
  2169. * this when writing your own Connector or Endpoint implementation.
  2170. *
  2171. * Parameters:
  2172. * x - [int] x position for the Canvas origin
  2173. * y - [int] y position for the Canvas origin
  2174. * w - [int] width of the canvas
  2175. * h - [int] height of the canvas
  2176. *
  2177. * Returns:
  2178. * void
  2179. */
  2180. this.sizeCanvas = function(canvas, x, y, w, h) {
  2181. if (canvas) {
  2182. canvas.style.height = h + "px";
  2183. canvas.height = h;
  2184. canvas.style.width = w + "px";
  2185. canvas.width = w;
  2186. canvas.style.left = x + "px";
  2187. canvas.style.top = y + "px";
  2188. }
  2189. };
  2190. /**
  2191. * gets some test hooks. nothing writable.
  2192. */
  2193. this.getTestHarness = function() {
  2194. return {
  2195. endpointsByElement : endpointsByElement,
  2196. endpointCount : function(elId) {
  2197. var e = endpointsByElement[elId];
  2198. return e ? e.length : 0;
  2199. },
  2200. connectionCount : function(scope) {
  2201. scope = scope || DEFAULT_SCOPE;
  2202. var c = connectionsByScope[scope];
  2203. return c ? c.length : 0;
  2204. },
  2205. findIndex : _findIndex,
  2206. getId : _getId,
  2207. makeAnchor:self.makeAnchor,
  2208. makeDynamicAnchor:self.makeDynamicAnchor
  2209. };
  2210. };
  2211. /**
  2212. * Toggles visibility of an element's connections. kept for backwards
  2213. * compatibility
  2214. */
  2215. this.toggle = _toggleVisible;
  2216. /*
  2217. * Function: toggleVisible
  2218. * Toggles visibility of an element's Connections.
  2219. *
  2220. * Parameters:
  2221. * el - either the element's id, or a selector representing the element.
  2222. * changeEndpoints - whether or not to also toggle the endpoints on the element.
  2223. *
  2224. * Returns:
  2225. * void, but should be updated to return the current state
  2226. */
  2227. // TODO: update this method to return the current state.
  2228. this.toggleVisible = _toggleVisible;
  2229. /*
  2230. * Function: toggleDraggable
  2231. * Toggles draggability (sic?) of an element's Connections.
  2232. *
  2233. * Parameters:
  2234. * el - either the element's id, or a selector representing the element.
  2235. *
  2236. * Returns:
  2237. * The current draggable state.
  2238. */
  2239. this.toggleDraggable = _toggleDraggable;
  2240. /*
  2241. * Function: unload
  2242. * Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element.
  2243. *
  2244. * Returns:
  2245. * void
  2246. */
  2247. this.unload = function() {
  2248. delete endpointsByElement;
  2249. delete endpointsByUUID;
  2250. delete offsets;
  2251. delete sizes;
  2252. delete floatingConnections;
  2253. delete draggableStates;
  2254. delete canvasList;
  2255. };
  2256. /*
  2257. * Helper method to wrap an existing function with one of
  2258. * your own. This is used by the various implementations to wrap event
  2259. * callbacks for drag/drop etc; it allows jsPlumb to be transparent in
  2260. * its handling of these things. If a user supplies their own event
  2261. * callback, for anything, it will always be called.
  2262. */
  2263. this.wrap = _wrap;
  2264. this.addListener = this.bind;
  2265. var adjustForParentOffsetAndScroll = function(xy, el) {
  2266. var offsetParent = null, result = xy;
  2267. if (el.tagName.toLowerCase() === "svg" && el.parentNode) {
  2268. offsetParent = el.parentNode;
  2269. }
  2270. else if (el.offsetParent) {
  2271. offsetParent = el.offsetParent;
  2272. }
  2273. if (offsetParent != null) {
  2274. var po = offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(offsetParent),
  2275. so = offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : {left:offsetParent.scrollLeft, top:offsetParent.scrollTop};
  2276. // i thought it might be cool to do this:
  2277. // lastReturnValue[0] = lastReturnValue[0] - offsetParent.offsetLeft + offsetParent.scrollLeft;
  2278. // lastReturnValue[1] = lastReturnValue[1] - offsetParent.offsetTop + offsetParent.scrollTop;
  2279. // but i think it ignores margins. my reasoning was that it's quicker to not hand off to some underlying
  2280. // library.
  2281. result[0] = xy[0] - po.left + so.left;
  2282. result[1] = xy[1] - po.top + so.top;
  2283. }
  2284. return result;
  2285. };
  2286. /**
  2287. * Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user
  2288. * was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"),
  2289. * or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the
  2290. * creation of Anchors without user intervention.
  2291. */
  2292. var Anchor = function(params) {
  2293. var self = this;
  2294. this.x = params.x || 0;
  2295. this.y = params.y || 0;
  2296. this.elementId = params.elementId;
  2297. var orientation = params.orientation || [ 0, 0 ];
  2298. var lastTimestamp = null, lastReturnValue = null;
  2299. this.offsets = params.offsets || [ 0, 0 ];
  2300. self.timestamp = null;
  2301. this.compute = function(params) {
  2302. var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
  2303. if (timestamp && timestamp === self.timestamp)
  2304. return lastReturnValue;
  2305. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  2306. // adjust loc if there is an offsetParent
  2307. lastReturnValue = adjustForParentOffsetAndScroll(lastReturnValue, element.canvas);
  2308. self.timestamp = timestamp;
  2309. return lastReturnValue;
  2310. };
  2311. this.getOrientation = function() { return orientation; };
  2312. this.equals = function(anchor) {
  2313. if (!anchor) return false;
  2314. var ao = anchor.getOrientation();
  2315. var o = this.getOrientation();
  2316. return this.x == anchor.x && this.y == anchor.y
  2317. && this.offsets[0] == anchor.offsets[0]
  2318. && this.offsets[1] == anchor.offsets[1]
  2319. && o[0] == ao[0] && o[1] == ao[1];
  2320. };
  2321. this.getCurrentLocation = function() { return lastReturnValue; };
  2322. };
  2323. /**
  2324. * An Anchor that floats. its orientation is computed dynamically from
  2325. * its position relative to the anchor it is floating relative to. It is used when creating
  2326. * a connection through drag and drop.
  2327. *
  2328. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  2329. */
  2330. var FloatingAnchor = function(params) {
  2331. // this is the anchor that this floating anchor is referenced to for
  2332. // purposes of calculating the orientation.
  2333. var ref = params.reference,
  2334. // the canvas this refers to.
  2335. refCanvas = params.referenceCanvas,
  2336. size = _getSize(_getElementObject(refCanvas)),
  2337. // these are used to store the current relative position of our
  2338. // anchor wrt the reference anchor. they only indicate
  2339. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  2340. // values are written by the compute method, and read
  2341. // by the getOrientation method.
  2342. xDir = 0, yDir = 0,
  2343. // temporary member used to store an orientation when the floating
  2344. // anchor is hovering over another anchor.
  2345. orientation = null,
  2346. _lastResult = null;
  2347. this.compute = function(params) {
  2348. var xy = params.xy, element = params.element,
  2349. result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
  2350. // adjust loc if there is an offsetParent
  2351. result = adjustForParentOffsetAndScroll(result, element.canvas);
  2352. _lastResult = result;
  2353. return result;
  2354. };
  2355. this.getOrientation = function() {
  2356. if (orientation) return orientation;
  2357. else {
  2358. var o = ref.getOrientation();
  2359. // here we take into account the orientation of the other
  2360. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  2361. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  2362. return [ Math.abs(o[0]) * xDir * -1,
  2363. Math.abs(o[1]) * yDir * -1 ];
  2364. }
  2365. };
  2366. /**
  2367. * notification the endpoint associated with this anchor is hovering
  2368. * over another anchor; we want to assume that anchor's orientation
  2369. * for the duration of the hover.
  2370. */
  2371. this.over = function(anchor) { orientation = anchor.getOrientation(); };
  2372. /**
  2373. * notification the endpoint associated with this anchor is no
  2374. * longer hovering over another anchor; we should resume calculating
  2375. * orientation as we normally do.
  2376. */
  2377. this.out = function() { orientation = null; };
  2378. this.getCurrentLocation = function() { return _lastResult; };
  2379. };
  2380. /*
  2381. * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
  2382. * through at compute time to find the one that is located closest to
  2383. * the center of the target element, and returns that Anchor's compute
  2384. * method result. this causes endpoints to follow each other with
  2385. * respect to the orientation of their target elements, which is a useful
  2386. * feature for some applications.
  2387. *
  2388. */
  2389. var DynamicAnchor = function(anchors, anchorSelector, elementId) {
  2390. this.isSelective = true;
  2391. this.isDynamic = true;
  2392. var _anchors = [],
  2393. _convert = function(anchor) { return anchor.constructor == Anchor ? anchor: jsPlumb.makeAnchor(anchor, elementId, _currentInstance); };
  2394. for (var i = 0; i < anchors.length; i++) _anchors[i] = _convert(anchors[i]);
  2395. this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
  2396. this.getAnchors = function() { return _anchors; };
  2397. this.locked = false;
  2398. var _curAnchor = _anchors.length > 0 ? _anchors[0] : null,
  2399. _curIndex = _anchors.length > 0 ? 0 : -1,
  2400. self = this,
  2401. // helper method to calculate the distance between the centers of the two elements.
  2402. _distance = function(anchor, cx, cy, xy, wh) {
  2403. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
  2404. return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
  2405. },
  2406. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  2407. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  2408. // xy - xy loc of the anchor's element
  2409. // wh - anchor's element's dimensions
  2410. // txy - xy loc of the element of the other anchor in the connection
  2411. // twh - dimensions of the element of the other anchor in the connection.
  2412. // anchors - the list of selectable anchors
  2413. _anchorSelector = anchorSelector || function(xy, wh, txy, twh, anchors) {
  2414. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  2415. var minIdx = -1, minDist = Infinity;
  2416. for ( var i = 0; i < anchors.length; i++) {
  2417. var d = _distance(anchors[i], cx, cy, xy, wh);
  2418. if (d < minDist) {
  2419. minIdx = i + 0;
  2420. minDist = d;
  2421. }
  2422. }
  2423. return anchors[minIdx];
  2424. };
  2425. this.compute = function(params) {
  2426. var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
  2427. // if anchor is locked or an opposite element was not given, we
  2428. // maintain our state. anchor will be locked
  2429. // if it is the source of a drag and drop.
  2430. if (self.locked || txy == null || twh == null)
  2431. return _curAnchor.compute(params);
  2432. else
  2433. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  2434. _curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
  2435. return _curAnchor.compute(params);
  2436. };
  2437. this.getCurrentLocation = function() {
  2438. return _curAnchor != null ? _curAnchor.getCurrentLocation() : null;
  2439. };
  2440. this.getOrientation = function() { return _curAnchor != null ? _curAnchor.getOrientation() : [ 0, 0 ]; };
  2441. this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
  2442. this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
  2443. };
  2444. /*
  2445. manages anchors for all elements.
  2446. */
  2447. // "continuous" anchors: anchors that pick their location based on how many connections the given element has.
  2448. // this requires looking at a lot more elements than normal - anything that has had a Continuous anchor applied has
  2449. // to be recalculated. so this manager is used as a reference point. the first time, with a new timestamp, that
  2450. // a continuous anchor is asked to compute, it calls this guy. or maybe, even, this guy gets called somewhere else
  2451. // and compute only ever returns pre-computed values. either way, this is the central point, and we want it to
  2452. // be called as few times as possible.
  2453. var continuousAnchors = {},
  2454. continuousAnchorLocations = {},
  2455. continuousAnchorOrientations = {},
  2456. Orientation = { HORIZONTAL : "horizontal", VERTICAL : "vertical", DIAGONAL : "diagonal", IDENTITY:"identity" },
  2457. // TODO this functions uses a crude method of determining orientation between two elements.
  2458. // 'diagonal' should be chosen when the angle of the line between the two centers is around
  2459. // one of 45, 135, 225 and 315 degrees. maybe +- 15 degrees.
  2460. calculateOrientation = function(sourceId, targetId, sd, td) {
  2461. if (sourceId === targetId) return {
  2462. orientation:Orientation.IDENTITY,
  2463. a:["top", "top"]
  2464. };
  2465. var theta = Math.atan2((td.centery - sd.centery) , (td.centerx - sd.centerx)),
  2466. theta2 = Math.atan2((sd.centery - td.centery) , (sd.centerx - td.centerx)),
  2467. h = ((sd.left <= td.left && sd.right >= td.left) || (sd.left <= td.right && sd.right >= td.right) ||
  2468. (sd.left <= td.left && sd.right >= td.right) || (td.left <= sd.left && td.right >= sd.right)),
  2469. v = ((sd.top <= td.top && sd.bottom >= td.top) || (sd.top <= td.bottom && sd.bottom >= td.bottom) ||
  2470. (sd.top <= td.top && sd.bottom >= td.bottom) || (td.top <= sd.top && td.bottom >= sd.bottom));
  2471. if (! (h || v)) {
  2472. var a = null, rls = false, rrs = false, sortValue = null;
  2473. if (td.left > sd.left && td.top > sd.top)
  2474. a = ["right", "top"];
  2475. else if (td.left > sd.left && sd.top > td.top)
  2476. a = [ "top", "left"];
  2477. else if (td.left < sd.left && td.top < sd.top)
  2478. a = [ "top", "right"];
  2479. else if (td.left < sd.left && td.top > sd.top)
  2480. a = ["left", "top" ];
  2481. return { orientation:Orientation.DIAGONAL, a:a, theta:theta, theta2:theta2 };
  2482. }
  2483. else if (h) return {
  2484. orientation:Orientation.HORIZONTAL,
  2485. a:sd.top < td.top ? ["bottom", "top"] : ["top", "bottom"],
  2486. theta:theta, theta2:theta2
  2487. }
  2488. else return {
  2489. orientation:Orientation.VERTICAL,
  2490. a:sd.left < td.left ? ["right", "left"] : ["left", "right"],
  2491. theta:theta, theta2:theta2
  2492. }
  2493. },
  2494. placeAnchorsOnLine = function(desc, elementDimensions, elementPosition,
  2495. connections, horizontal, otherMultiplier, reverse) {
  2496. var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
  2497. for (var i = 0; i < connections.length; i++) {
  2498. var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
  2499. if (reverse)
  2500. val = elementDimensions[horizontal ? 0 : 1] - val;
  2501. var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
  2502. dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
  2503. a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
  2504. }
  2505. return a;
  2506. },
  2507. standardEdgeSort = function(a, b) { return a[0] > b[0] ? 1 : -1 },
  2508. currySort = function(reverseAngles) {
  2509. return function(a,b) {
  2510. var r = true;
  2511. if (reverseAngles) {
  2512. if (a[0][0] < b[0][0])
  2513. r = true;
  2514. else
  2515. r = a[0][1] > b[0][1];
  2516. }
  2517. else {
  2518. if (a[0][0] > b[0][0])
  2519. r= true;
  2520. else
  2521. r =a[0][1] > b[0][1];
  2522. }
  2523. return r === false ? -1 : 1;
  2524. };
  2525. },
  2526. leftSort = function(a,b) {
  2527. // first get adjusted values
  2528. var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
  2529. p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
  2530. if (p1 > p2) return 1;
  2531. else return a[0][1] > b[0][1] ? 1 : -1;
  2532. },
  2533. edgeSortFunctions = {
  2534. "top":standardEdgeSort,
  2535. "right":currySort(true),
  2536. "bottom":currySort(true),
  2537. "left":leftSort
  2538. },
  2539. _sortHelper = function(_array, _fn) {
  2540. return _array.sort(_fn);
  2541. },
  2542. placeAnchors = function(elementId, _anchorLists) {
  2543. var sS = sizes[elementId], sO = offsets[elementId],
  2544. placeSomeAnchors = function(desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier) {
  2545. if (unsortedConnections.length > 0) {
  2546. var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
  2547. //sc = unsortedConnections.sort(edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
  2548. reverse = desc === "right" || desc === "top",
  2549. anchors = placeAnchorsOnLine(desc, elementDimensions,
  2550. elementPosition, sc,
  2551. isHorizontal, otherMultiplier, reverse );
  2552. // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
  2553. var _setAnchorLocation = function(endpoint, anchorPos) {
  2554. var a = adjustForParentOffsetAndScroll([anchorPos[0], anchorPos[1]], endpoint.canvas);
  2555. continuousAnchorLocations[endpoint.id] = [ a[0], a[1], anchorPos[2], anchorPos[3] ];
  2556. };
  2557. for (var i = 0; i < anchors.length; i++) {
  2558. var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
  2559. if (weAreSource)
  2560. _setAnchorLocation(c.endpoints[0], anchors[i]);
  2561. else if (weAreTarget)
  2562. _setAnchorLocation(c.endpoints[1], anchors[i]);
  2563. }
  2564. }
  2565. };
  2566. placeSomeAnchors("bottom", sS, [sO.left,sO.top], _anchorLists.bottom, true, 1);
  2567. placeSomeAnchors("top", sS, [sO.left,sO.top], _anchorLists.top, true, 0);
  2568. placeSomeAnchors("left", sS, [sO.left,sO.top], _anchorLists.left, false, 0);
  2569. placeSomeAnchors("right", sS, [sO.left,sO.top], _anchorLists.right, false, 1);
  2570. },
  2571. AnchorManager = function() {
  2572. var _amEndpoints = {},
  2573. endpointConnectionsByElementId = {},
  2574. continuousAnchorConnectionsByElementId = {},
  2575. continuousAnchorEndpoints = [],
  2576. self = this,
  2577. anchorLists = {};
  2578. this.reset = function() {
  2579. endpointConnectionsByElementId = {};
  2580. continuousAnchorConnectionsByElementId = {};
  2581. continuousAnchorEndpoints = [];
  2582. anchorLists = {};
  2583. };
  2584. this.newConnection = function(conn) {
  2585. var sourceId = conn.sourceId, targetId = conn.targetId,
  2586. ep = conn.endpoints,
  2587. doRegisterTarget = true,
  2588. registerConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) {
  2589. if (otherAnchor.constructor == DynamicAnchor || otherAnchor.constructor == Anchor) {
  2590. _addToList(endpointConnectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor == DynamicAnchor]);
  2591. }
  2592. else {
  2593. // continuous. if they are the same element, just assign the same anchor
  2594. // to both.
  2595. if (sourceId == targetId) {
  2596. // remove the target endpoint's canvas. we dont need it.
  2597. jsPlumb.CurrentLibrary.removeElement(ep[1].canvas);
  2598. doRegisterTarget = false;
  2599. }
  2600. _addToList(continuousAnchorConnectionsByElementId, elId, c);
  2601. }
  2602. };
  2603. registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
  2604. if (doRegisterTarget)
  2605. registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
  2606. };
  2607. this.connectionDetached = function(connInfo) {
  2608. var sourceId = connInfo.sourceId,
  2609. targetId = connInfo.targetId,
  2610. ep = connInfo.connection.endpoints,
  2611. removeConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) {
  2612. if (otherAnchor.constructor == FloatingAnchor) {
  2613. // no-op
  2614. }
  2615. else if (otherAnchor.constructor == DynamicAnchor || otherAnchor.constructor == Anchor) {
  2616. var _conns = endpointConnectionsByElementId[elId];
  2617. if (_conns) {
  2618. _removeWithFunction(_conns, function(e) { return e[0].id == c.id; });
  2619. }
  2620. }
  2621. else // continuous.
  2622. _removeFromList(continuousAnchorConnectionsByElementId, elId, c);
  2623. };
  2624. removeConnection(1, ep[1], ep[1].anchor, sourceId, connInfo.connection);
  2625. removeConnection(0, ep[0], ep[0].anchor, targetId, connInfo.connection);
  2626. // remove from anchorLists
  2627. var sEl = connInfo.connection.sourceId,
  2628. tEl = connInfo.connection.targetId,
  2629. sE = connInfo.connection.endpoints[0].id,
  2630. tE = connInfo.connection.endpoints[1].id,
  2631. _remove = function(list, eId) {
  2632. if (list) { // transient anchors dont get entries in this list.
  2633. var f = function(e) { return e[4] == eId; };
  2634. _removeWithFunction(list["top"], f);
  2635. _removeWithFunction(list["left"], f);
  2636. _removeWithFunction(list["bottom"], f);
  2637. _removeWithFunction(list["right"], f);
  2638. }
  2639. };
  2640. _remove(anchorLists[sEl], sE);
  2641. _remove(anchorLists[tEl], tE);
  2642. self.redraw(sEl);
  2643. self.redraw(tEl);
  2644. };
  2645. this.add = function(endpoint, elementId) {
  2646. _addToList(_amEndpoints, elementId, endpoint);
  2647. };
  2648. this.get = function(elementId) {
  2649. return {
  2650. "standard":endpointConnectionsByElementId[elementId] || [],
  2651. "continuous":continuousAnchorConnectionsByElementId[elementId] || [],
  2652. "endpoints":_amEndpoints[elementId],
  2653. "continuousAnchorEndpoints":continuousAnchorEndpoints
  2654. };
  2655. };
  2656. this.deleteEndpoint = function(endpoint) {
  2657. var cIdx = _findIndex(continuousAnchorEndpoints, endpoint);
  2658. if (cIdx > -1)
  2659. continuousAnchorEndpoints.splice(cIdx, 1);
  2660. else
  2661. _removeFromList(_amEndpoints, endpoint.elementId, endpoint);
  2662. };
  2663. this.clearFor = function(elementId) {
  2664. delete _amEndpoints[elementId];
  2665. _amEndpoints[elementId] = [];
  2666. };
  2667. // updates the given anchor list by either updating an existing anchor's info, or adding it. this function
  2668. // also removes the anchor from its previous list, if the edge it is on has changed.
  2669. // all connections found along the way (those that are connected to one of the faces this function
  2670. // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
  2671. // them wthout having to calculate anything else about them.
  2672. var _updateAnchorList = function(lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
  2673. // first try to find the exact match, but keep track of the first index of a matching element id along the way.s
  2674. var exactIdx = -1,
  2675. firstMatchingElIdx = -1,
  2676. endpoint = conn.endpoints[idx],
  2677. endpointId = endpoint.id,
  2678. oIdx = [1,0][idx],
  2679. values = [ [ theta, order ], conn, aBoolean, otherElId, endpointId ],
  2680. listToAddTo = lists[edgeId],
  2681. listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null;
  2682. if (listToRemoveFrom) {
  2683. var rIdx = _findWithFunction(listToRemoveFrom, function(e) { return e[4] == endpointId });
  2684. if (rIdx != -1) {
  2685. listToRemoveFrom.splice(rIdx, 1);
  2686. // get all connections from this list
  2687. for (var i = 0; i < listToRemoveFrom.length; i++) {
  2688. connsToPaint.push(listToRemoveFrom[i][1]);
  2689. endpointsToPaint.push(listToRemoveFrom[i][1].endpoints[idx]);
  2690. }
  2691. }
  2692. }
  2693. for (var i = 0; i < listToAddTo.length; i++) {
  2694. if (idx == 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx == -1)
  2695. firstMatchingElIdx = i;
  2696. connsToPaint.push(listToAddTo[i][1]);
  2697. endpointsToPaint.push(listToAddTo[i][1].endpoints[idx]);
  2698. }
  2699. if (exactIdx != -1) {
  2700. listToAddTo[exactIdx] = values;
  2701. }
  2702. else {
  2703. var insertIdx = reverse ? firstMatchingElIdx != -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
  2704. listToAddTo.splice(insertIdx, 0, values);
  2705. }
  2706. // store this for next time.
  2707. endpoint._continuousAnchorEdge = edgeId;
  2708. };
  2709. this.redraw = function(elementId, ui, timestamp) {
  2710. // get all the endpoints for this element
  2711. var ep = _amEndpoints[elementId] || [],
  2712. endpointConnections = endpointConnectionsByElementId[elementId] || [],
  2713. continuousAnchorConnections = continuousAnchorConnectionsByElementId[elementId] || [],
  2714. connectionsToPaint = [],
  2715. endpointsToPaint = [];
  2716. timestamp = timestamp || _timestamp();
  2717. _updateOffset( { elId : elementId, offset : ui, recalc : false, timestamp : timestamp });
  2718. // valid for one paint cycle.
  2719. var myOffset = offsets[elementId],
  2720. myWH = sizes[elementId],
  2721. orientationCache = {};
  2722. // actually, first we should compute the orientation of this element to all other elements to which
  2723. // this element is connected with a continuous anchor (whether both ends of the connection have
  2724. // a continuous anchor or just one)
  2725. for (var i = 0; i < continuousAnchorConnections.length; i++) {
  2726. var conn = continuousAnchorConnections[i],
  2727. sourceId = conn.sourceId,
  2728. targetId = conn.targetId,
  2729. oKey = sourceId + "_" + targetId,
  2730. oKey2 = targetId + "_" + sourceId,
  2731. o = orientationCache[oKey],
  2732. td = _getCachedData(targetId),
  2733. sd = _getCachedData(sourceId),
  2734. oIdx = conn.sourceId == elementId ? 1 : 0;
  2735. if (!anchorLists[sourceId]) anchorLists[sourceId] = { top:[], right:[], bottom:[], left:[] };
  2736. if (!anchorLists[targetId]) anchorLists[targetId] = { top:[], right:[], bottom:[], left:[] };
  2737. if (targetId == sourceId) {
  2738. // here we may want to improve this by somehow determining the face we'd like
  2739. // to put the connector on. ideally, when drawing, the face should be calculated
  2740. // by determining which face is closest to the point at which the mouse button
  2741. // was released. for now, we're putting it on the top face.
  2742. _updateAnchorList(anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint)
  2743. }
  2744. else {
  2745. if (!o) {
  2746. o = calculateOrientation(sourceId, targetId, sd.o, td.o);
  2747. orientationCache[oKey] = o;
  2748. // this would be a performance enhancement, but the computed angles need to be clamped to
  2749. //the (-PI/2 -> PI/2) range in order for the sorting to work properly.
  2750. /* orientationCache[oKey2] = {
  2751. orientation:o.orientation,
  2752. a:[o.a[1], o.a[0]],
  2753. theta:o.theta + Math.PI,
  2754. theta2:o.theta2 + Math.PI
  2755. };*/
  2756. }
  2757. _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
  2758. _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
  2759. }
  2760. connectionsToPaint.push(conn);
  2761. endpointsToPaint.push(conn.endpoints[oIdx]);
  2762. }
  2763. // now place all the continuous anchors;
  2764. for (var anElement in anchorLists) {
  2765. placeAnchors(anElement, anchorLists[anElement]);
  2766. }
  2767. // now that continuous anchors have been placed, paint all the endpoints for this element
  2768. for (var i = 0; i < ep.length; i++) {
  2769. ep[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  2770. }
  2771. // ... and any other endpoints we came across as a result of the continuous anchors.
  2772. for (var i = 0; i < endpointsToPaint.length; i++) {
  2773. endpointsToPaint[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  2774. }
  2775. // paint all the standard and "dynamic connections", which are connections whose other anchor is
  2776. // static and therefore does need to be recomputed; we make sure that happens only one time.
  2777. for (var i = 0; i < endpointConnections.length; i++) {
  2778. var otherEndpoint = endpointConnections[i][1];
  2779. if (otherEndpoint.anchor.constructor == DynamicAnchor) {
  2780. // _updateOffset( { elId : otherEndpoint.elementId, timestamp : timestamp });
  2781. otherEndpoint.paint({ elementWithPrecedence:elementId });
  2782. connectionsToPaint.push(endpointConnections[i][0]);
  2783. // all the connections for the other endpoint now need to be repainted
  2784. for (var k = 0; k < otherEndpoint.connections.length; k++) {
  2785. if (otherEndpoint.connections[k] !== endpointConnections[i][0])
  2786. connectionsToPaint.push(otherEndpoint.connections[k]);
  2787. }
  2788. } else if (otherEndpoint.anchor.constructor == Anchor) {
  2789. connectionsToPaint.push(endpointConnections[i][0]);
  2790. }
  2791. }
  2792. // paint current floating connection for this element, if there is one.
  2793. var fc = floatingConnections[elementId];
  2794. if (fc)
  2795. fc.paint({timestamp:timestamp, recalc:false, elId:elementId});
  2796. // paint all the connections
  2797. for (var i = 0; i < connectionsToPaint.length; i++) {
  2798. connectionsToPaint[i].paint({elId:elementId, timestamp:timestamp, recalc:false});
  2799. }
  2800. };
  2801. this.rehomeEndpoint = function(currentId, element) {
  2802. var eps = _amEndpoints[currentId] || [], //,
  2803. elementId = _currentInstance.getId(element);
  2804. for (var i = 0; i < eps.length; i++) {
  2805. self.add(eps[i], elementId);
  2806. }
  2807. eps.splice(0, eps.length);
  2808. };
  2809. };
  2810. _currentInstance.anchorManager = new AnchorManager();
  2811. //_currentInstance.bind("jsPlumbConnection", _currentInstance.anchorManager.connectionListener);
  2812. //_currentInstance.bind("jsPlumbConnectionDetached", _currentInstance.anchorManager.connectionDetachedListener);
  2813. _currentInstance.continuousAnchorFactory = {
  2814. get:function(params) {
  2815. var existing = continuousAnchors[params.elementId];
  2816. if (!existing) {
  2817. existing = {
  2818. type:"Continuous",
  2819. compute : function(params) {
  2820. return continuousAnchorLocations[params.element.id] || [0,0];
  2821. },
  2822. getCurrentLocation : function(endpoint) {
  2823. return continuousAnchorLocations[endpoint.id] || [0,0];
  2824. },
  2825. getOrientation : function(endpoint) {
  2826. return continuousAnchorOrientations[endpoint.id] || [0,0];
  2827. },
  2828. isDynamic : true,
  2829. isContinuous : true
  2830. };
  2831. continuousAnchors[params.elementId] = existing;
  2832. }
  2833. return existing;
  2834. }
  2835. };
  2836. /*
  2837. * Class: Connection
  2838. * The connecting line between two Endpoints.
  2839. */
  2840. /*
  2841. * Function: Connection
  2842. * Connection constructor.
  2843. *
  2844. * Parameters:
  2845. * source - either an element id, a selector for an element, or an Endpoint.
  2846. * target - either an element id, a selector for an element, or an Endpoint
  2847. * scope - scope descriptor for this connection. optional.
  2848. * container - optional id or selector instructing jsPlumb where to attach all the elements it creates for this connection. you should read the documentation for a full discussion of this.
  2849. * endpoint - Optional. Endpoint definition to use for both ends of the connection.
  2850. * endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  2851. * endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
  2852. * endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  2853. * paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
  2854. * hoverPaintStyle - Parameters defining the appearance of the Connection when the mouse is hovering over it. Optional; jsPlumb will use the defaults if you supply nothing here (note that the default hoverPaintStyle is null).
  2855. * overlays - Optional array of Overlay definitions to appear on this Connection.
  2856. * drawEndpoints - if false, instructs jsPlumb to not draw the endpoints for this Connection. Be careful with this: it only really works when you tell jsPlumb to attach elements to the document body. Read the documentation for a full discussion of this.
  2857. */
  2858. var Connection = function(params) {
  2859. var self = this, visible = true;
  2860. self.idPrefix = "_jsplumb_c_";
  2861. jsPlumbUIComponent.apply(this, arguments);
  2862. // ************** get the source and target and register the connection. *******************
  2863. /**
  2864. Function:isVisible
  2865. Returns whether or not the Connection is currently visible.
  2866. */
  2867. this.isVisible = function() { return visible; };
  2868. /**
  2869. Function: setVisible
  2870. Sets whether or not the Connection should be visible.
  2871. Parameters:
  2872. visible - boolean indicating desired visible state.
  2873. */
  2874. this.setVisible = function(v) {
  2875. visible = v;
  2876. if (self.connector && self.connector.canvas) self.connector.canvas.style.display = v ? "block" : "none";
  2877. };
  2878. this.parent = params.parent;
  2879. /**
  2880. Property: source
  2881. The source element for this Connection.
  2882. */
  2883. this.source = _getElementObject(params.source);
  2884. /**
  2885. Property:target
  2886. The target element for this Connection.
  2887. */
  2888. this.target = _getElementObject(params.target);
  2889. // sourceEndpoint and targetEndpoint override source/target, if they are present. but
  2890. // source is not overridden if the Endpoint has declared it is not the final target of a connection;
  2891. // instead we use the source that the Endpoint declares will be the final source element.
  2892. if (params.sourceEndpoint) {
  2893. this.source = params.sourceEndpoint.endpointWillMoveTo || params.sourceEndpoint.getElement();
  2894. }
  2895. if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
  2896. // if a new connection is the result of moving some existing connection, params.previousConnection
  2897. // will have that Connection in it. listeners for the jsPlumbConnection event can look for that
  2898. // member and take action if they need to.
  2899. self.previousConnection = params.previousConnection;
  2900. /*
  2901. * Property: sourceId
  2902. * Id of the source element in the connection.
  2903. */
  2904. this.sourceId = _getAttribute(this.source, "id");
  2905. /*
  2906. * Property: targetId
  2907. * Id of the target element in the connection.
  2908. */
  2909. this.targetId = _getAttribute(this.target, "id");
  2910. /**
  2911. * implementation of abstract method in EventGenerator
  2912. * @return list of attached elements. in our case, a list of Endpoints.
  2913. */
  2914. this.getAttachedElements = function() {
  2915. return self.endpoints;
  2916. };
  2917. /*
  2918. * Property: scope
  2919. * Optional scope descriptor for the connection.
  2920. */
  2921. this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints.
  2922. /*
  2923. * Property: endpoints
  2924. * Array of [source, target] Endpoint objects.
  2925. */
  2926. this.endpoints = [];
  2927. this.endpointStyles = [];
  2928. // wrapped the main function to return null if no input given. this lets us cascade defaults properly.
  2929. var _makeAnchor = function(anchorParams, elementId) {
  2930. if (anchorParams)
  2931. return jsPlumb.makeAnchor(anchorParams, elementId, _currentInstance);
  2932. },
  2933. prepareEndpoint = function(existing, index, params, element, elementId, connectorPaintStyle, connectorHoverPaintStyle) {
  2934. if (existing) {
  2935. self.endpoints[index] = existing;
  2936. existing.addConnection(self);
  2937. } else {
  2938. if (!params.endpoints) params.endpoints = [ null, null ];
  2939. var ep = params.endpoints[index]
  2940. || params.endpoint
  2941. || _currentInstance.Defaults.Endpoints[index]
  2942. || jsPlumb.Defaults.Endpoints[index]
  2943. || _currentInstance.Defaults.Endpoint
  2944. || jsPlumb.Defaults.Endpoint;
  2945. if (!params.endpointStyles) params.endpointStyles = [ null, null ];
  2946. if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
  2947. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  2948. // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
  2949. if (es.fillStyle == null && connectorPaintStyle != null)
  2950. es.fillStyle = connectorPaintStyle.strokeStyle;
  2951. // TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
  2952. //*
  2953. if (es.outlineColor == null && connectorPaintStyle != null)
  2954. es.outlineColor = connectorPaintStyle.outlineColor;
  2955. if (es.outlineWidth == null && connectorPaintStyle != null)
  2956. es.outlineWidth = connectorPaintStyle.outlineWidth;
  2957. //*/
  2958. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _currentInstance.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
  2959. // endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
  2960. if (connectorHoverPaintStyle != null) {
  2961. if (ehs == null) ehs = {};
  2962. if (ehs.fillStyle == null) {
  2963. ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
  2964. }
  2965. }
  2966. var a = params.anchors ? params.anchors[index] :
  2967. params.anchor ? params.anchor :
  2968. _makeAnchor(_currentInstance.Defaults.Anchors[index], elementId) ||
  2969. _makeAnchor(jsPlumb.Defaults.Anchors[index], elementId) ||
  2970. _makeAnchor(_currentInstance.Defaults.Anchor, elementId) ||
  2971. _makeAnchor(jsPlumb.Defaults.Anchor, elementId),
  2972. u = params.uuids ? params.uuids[index] : null,
  2973. e = _newEndpoint({
  2974. paintStyle : es,
  2975. hoverPaintStyle:ehs,
  2976. endpoint : ep,
  2977. connections : [ self ],
  2978. uuid : u,
  2979. anchor : a,
  2980. source : element,
  2981. container:params.container,
  2982. reattach:params.reattach,
  2983. detachable:params.detachable
  2984. });
  2985. self.endpoints[index] = e;
  2986. if (params.drawEndpoints === false) e.setVisible(false, true, true);
  2987. return e;
  2988. }
  2989. };
  2990. var eS = prepareEndpoint(params.sourceEndpoint,
  2991. 0,
  2992. params,
  2993. self.source,
  2994. self.sourceId,
  2995. params.paintStyle,
  2996. params.hoverPaintStyle);
  2997. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  2998. // if there were no endpoints supplied and the source element is the target element, we will reuse the source
  2999. // endpoint that was just created.
  3000. var existingTargetEndpoint = ((self.sourceId == self.targetId) && params.targetEndpoint == null) ? eS : params.targetEndpoint,
  3001. eT = prepareEndpoint(existingTargetEndpoint,
  3002. 1,
  3003. params,
  3004. self.target,
  3005. self.targetId,
  3006. params.paintStyle,
  3007. params.hoverPaintStyle);
  3008. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  3009. // if scope not set, set it to be the scope for the source endpoint.
  3010. if (!this.scope) this.scope = this.endpoints[0].scope;
  3011. // if delete endpoints on detach, keep a record of just exactly which endpoints they are.
  3012. if (params.deleteEndpointsOnDetach)
  3013. self.endpointsToDeleteOnDetach = [eS, eT];
  3014. var _detachable = _currentInstance.Defaults.ConnectionsDetachable;
  3015. if (params.detachable === false) _detachable = false;
  3016. if(self.endpoints[0].connectionsDetachable === false) _detachable = false;
  3017. if(self.endpoints[1].connectionsDetachable === false) _detachable = false;
  3018. /*
  3019. Function: isDetachable
  3020. Returns whether or not this connection can be detached from its target/source endpoint. by default this
  3021. is false; use it in conjunction with the 'reattach' parameter.
  3022. */
  3023. this.isDetachable = function() {
  3024. return _detachable === true;
  3025. };
  3026. /*
  3027. Function: setDetachable
  3028. Sets whether or not this connection is detachable.
  3029. */
  3030. this.setDetachable = function(detachable) {
  3031. _detachable = detachable === true;
  3032. };
  3033. // merge all the parameters objects into the connection. parameters set
  3034. // on the connection take precedence; then target endpoint params, then
  3035. // finally source endpoint params.
  3036. var _p = jsPlumb.CurrentLibrary.extend({}, this.endpoints[0].getParameters());
  3037. jsPlumb.CurrentLibrary.extend(_p, this.endpoints[1].getParameters());
  3038. jsPlumb.CurrentLibrary.extend(_p, self.getParameters());
  3039. self.setParameters(_p);
  3040. var _bindConnectorEvents = function() {
  3041. // add mouse events
  3042. self.connector.bind("click", function(con, e) {
  3043. self.fire("click", self, e);
  3044. });
  3045. self.connector.bind("dblclick", function(con, e) {
  3046. self.fire("dblclick", self, e); });
  3047. self.connector.bind("mouseenter", function(con, e) {
  3048. if (!self.isHover()) {
  3049. if (_connectionBeingDragged == null) {
  3050. self.setHover(true, false);
  3051. }
  3052. self.fire("mouseenter", self, e);
  3053. }
  3054. });
  3055. self.connector.bind("mouseexit", function(con, e) {
  3056. if (self.isHover()) {
  3057. if (_connectionBeingDragged == null) {
  3058. self.setHover(false, false);
  3059. }
  3060. self.fire("mouseexit", self, e);
  3061. }
  3062. });
  3063. };
  3064. /*
  3065. * Function: setConnector
  3066. * Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method - the same
  3067. * thing that you would set as the 'connector' property on a jsPlumb.connect call.
  3068. *
  3069. * Parameters:
  3070. * connector - Connector definition
  3071. */
  3072. this.setConnector = function(connector, doNotRepaint) {
  3073. if (self.connector != null) _removeElements(self.connector.getDisplayElements(), self.parent);
  3074. var connectorArgs = {
  3075. _jsPlumb:self._jsPlumb,
  3076. parent:params.parent,
  3077. cssClass:params.cssClass,
  3078. container:params.container,
  3079. tooltip:self.tooltip
  3080. };
  3081. if (connector.constructor == String)
  3082. this.connector = new jsPlumb.Connectors[renderMode][connector](connectorArgs); // lets you use a string as shorthand.
  3083. else if (connector.constructor == Array)
  3084. this.connector = new jsPlumb.Connectors[renderMode][connector[0]](jsPlumb.extend(connector[1], connectorArgs));
  3085. self.canvas = self.connector.canvas;
  3086. _bindConnectorEvents();
  3087. if (!doNotRepaint) self.repaint();
  3088. };
  3089. /*
  3090. * Property: connector
  3091. * The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
  3092. */
  3093. self.setConnector(this.endpoints[0].connector ||
  3094. this.endpoints[1].connector ||
  3095. params.connector ||
  3096. _currentInstance.Defaults.Connector ||
  3097. jsPlumb.Defaults.Connector, true);
  3098. // override setHover to pass it down to the underlying connector
  3099. var _sh = self.setHover;
  3100. self.setHover = function() {
  3101. self.connector.setHover.apply(self.connector, arguments);
  3102. _sh.apply(self, arguments);
  3103. };
  3104. this.setPaintStyle(this.endpoints[0].connectorStyle ||
  3105. this.endpoints[1].connectorStyle ||
  3106. params.paintStyle ||
  3107. _currentInstance.Defaults.PaintStyle ||
  3108. jsPlumb.Defaults.PaintStyle, true);
  3109. this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
  3110. this.endpoints[1].connectorHoverStyle ||
  3111. params.hoverPaintStyle ||
  3112. _currentInstance.Defaults.HoverPaintStyle ||
  3113. jsPlumb.Defaults.HoverPaintStyle, true);
  3114. this.paintStyleInUse = this.paintStyle;
  3115. /*
  3116. * Property: overlays
  3117. * List of Overlays for this Connection.
  3118. */
  3119. this.overlays = [];
  3120. var processOverlay = function(o) {
  3121. var _newOverlay = null;
  3122. if (o.constructor == Array) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  3123. // there's also a three arg version:
  3124. // ["Arrow", { width:50 }, {location:0.7}]
  3125. // which merges the 3rd arg into the 2nd.
  3126. var type = o[0],
  3127. // make a copy of the object so as not to mess up anyone else's reference...
  3128. p = jsPlumb.CurrentLibrary.extend({connection:self, _jsPlumb:_currentInstance}, o[1]);
  3129. if (o.length == 3) jsPlumb.CurrentLibrary.extend(p, o[2]);
  3130. _newOverlay = new jsPlumb.Overlays[renderMode][type](p);
  3131. if (p.events) {
  3132. for (var evt in p.events) {
  3133. _newOverlay.bind(evt, p.events[evt]);
  3134. }
  3135. }
  3136. } else if (o.constructor == String) {
  3137. _newOverlay = new jsPlumb.Overlays[renderMode][o]({connection:self, _jsPlumb:_currentInstance});
  3138. } else {
  3139. _newOverlay = o;
  3140. }
  3141. self.overlays.push(_newOverlay);
  3142. };
  3143. var _overlays = params.overlays || _currentInstance.Defaults.Overlays;
  3144. if (_overlays) {
  3145. for (var i = 0; i < _overlays.length; i++) {
  3146. processOverlay(_overlays[i]);
  3147. }
  3148. }
  3149. this.moveParent = function(newParent) {
  3150. var jpcl = jsPlumb.CurrentLibrary, curParent = jpcl.getParent(self.connector.canvas);
  3151. jpcl.removeElement(self.connector.canvas, curParent);
  3152. jpcl.appendElement(self.connector.canvas, newParent);
  3153. if (self.connector.bgCanvas) {
  3154. jpcl.removeElement(self.connector.bgCanvas, curParent);
  3155. jpcl.appendElement(self.connector.bgCanvas, newParent);
  3156. }
  3157. // this only applies for DOMOverlays
  3158. for (var i = 0; i < self.overlays.length; i++) {
  3159. if (self.overlays[i].isAppendedAtTopLevel) {
  3160. jpcl.removeElement(self.overlays[i].canvas, curParent);
  3161. jpcl.appendElement(self.overlays[i].canvas, newParent);
  3162. if (self.overlays[i].reattachListeners) self.overlays[i].reattachListeners();
  3163. }
  3164. }
  3165. if (self.connector.reattachListeners) // this is for SVG/VML; change an element's parent and you have to reinit its listeners.
  3166. self.connector.reattachListeners(); // the Canvas implementation doesn't have to care about this
  3167. };
  3168. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3169. /*
  3170. * Function: bind
  3171. * Bind to an event on the Connection.
  3172. *
  3173. * Parameters:
  3174. * event - the event to bind. Available events on a Connection are:
  3175. * - *click* : notification that a Connection was clicked.
  3176. * - *dblclick* : notification that a Connection was double clicked.
  3177. * - *mouseenter* : notification that the mouse is over a Connection.
  3178. * - *mouseexit* : notification that the mouse exited a Connection.
  3179. *
  3180. * callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
  3181. */
  3182. /*
  3183. * Function: setPaintStyle
  3184. * Sets the Connection's paint style and then repaints the Connection.
  3185. *
  3186. * Parameters:
  3187. * style - Style to use.
  3188. */
  3189. /*
  3190. * Function: setHoverPaintStyle
  3191. * Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
  3192. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  3193. * it. This is because people will most likely want to change just one thing when hovering, say the
  3194. * color for example, but leave the rest of the appearance the same.
  3195. *
  3196. * Parameters:
  3197. * style - Style to use when the mouse is hovering.
  3198. * doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
  3199. */
  3200. /*
  3201. * Function: setHover
  3202. * Sets/unsets the hover state of this Connection.
  3203. *
  3204. * Parameters:
  3205. * hover - hover state boolean
  3206. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  3207. */
  3208. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3209. // overlay finder helper method
  3210. var _getOverlayIndex = function(id) {
  3211. var idx = -1;
  3212. for (var i = 0; i < self.overlays.length; i++) {
  3213. if (id === self.overlays[i].id) {
  3214. idx = i;
  3215. break;
  3216. }
  3217. }
  3218. return idx;
  3219. };
  3220. /*
  3221. * Function: addOverlay
  3222. * Adds an Overlay to the Connection.
  3223. *
  3224. * Parameters:
  3225. * overlay - Overlay to add.
  3226. */
  3227. this.addOverlay = function(overlay) {
  3228. processOverlay(overlay);
  3229. self.repaint();
  3230. };
  3231. /*
  3232. * Function: getOverlay
  3233. * Gets an overlay, by ID. Note: by ID. You would pass an 'id' parameter
  3234. * in to the Overlay's constructor arguments, and then use that to retrieve
  3235. * it via this method.
  3236. */
  3237. this.getOverlay = function(id) {
  3238. var idx = _getOverlayIndex(id);
  3239. return idx >= 0 ? self.overlays[idx] : null;
  3240. };
  3241. /*
  3242. * Function: hideOverlay
  3243. * Hides the overlay specified by the given id.
  3244. */
  3245. this.hideOverlay = function(id) {
  3246. var o = self.getOverlay(id);
  3247. if (o) o.hide();
  3248. };
  3249. /*
  3250. * Function: showOverlay
  3251. * Shows the overlay specified by the given id.
  3252. */
  3253. this.showOverlay = function(id) {
  3254. var o = self.getOverlay(id);
  3255. if (o) o.show();
  3256. };
  3257. /**
  3258. * Function: removeAllOverlays
  3259. * Removes all overlays from the Connection, and then repaints.
  3260. */
  3261. this.removeAllOverlays = function() {
  3262. self.overlays.splice(0, self.overlays.length);
  3263. self.repaint();
  3264. };
  3265. /**
  3266. * Function:removeOverlay
  3267. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  3268. * Parameters:
  3269. * overlayId - id of the overlay to remove.
  3270. */
  3271. this.removeOverlay = function(overlayId) {
  3272. var idx = _getOverlayIndex(overlayId);
  3273. if (idx != -1) {
  3274. var o = self.overlays[idx];
  3275. o.cleanup();
  3276. self.overlays.splice(idx, 1);
  3277. }
  3278. };
  3279. /**
  3280. * Function:removeOverlays
  3281. * Removes a set of overlays by ID. Note: by ID. this is a string you set in the overlay spec.
  3282. * Parameters:
  3283. * overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
  3284. */
  3285. this.removeOverlays = function() {
  3286. for (var i = 0; i < arguments.length; i++)
  3287. self.removeOverlay(arguments[i]);
  3288. };
  3289. // this is a shortcut helper method to let people add a label as
  3290. // overlay.
  3291. this.labelStyle = params.labelStyle || _currentInstance.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;
  3292. this.label = params.label;
  3293. if (this.label) {
  3294. this.overlays.push(new jsPlumb.Overlays[renderMode].Label( {
  3295. cssClass:params.cssClass,
  3296. labelStyle : this.labelStyle,
  3297. label : this.label,
  3298. connection:self,
  3299. _jsPlumb:_currentInstance
  3300. }));
  3301. }
  3302. _updateOffset( { elId : this.sourceId });
  3303. _updateOffset( { elId : this.targetId });
  3304. /*
  3305. * Function: setLabel
  3306. * Sets the Connection's label.
  3307. *
  3308. * Parameters:
  3309. * l - label to set. May be a String or a Function that returns a String.
  3310. */
  3311. this.setLabel = function(l) {
  3312. self.label = l;
  3313. _currentInstance.repaint(self.source);
  3314. };
  3315. // paint the endpoints
  3316. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId],
  3317. otherOffset = offsets[this.targetId],
  3318. otherWH = sizes[this.targetId],
  3319. initialTimestamp = _timestamp(),
  3320. anchorLoc = this.endpoints[0].anchor.compute( {
  3321. xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
  3322. elementId:this.endpoints[0].elementId,
  3323. txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1],
  3324. timestamp:initialTimestamp
  3325. });
  3326. this.endpoints[0].paint( { anchorLoc : anchorLoc, timestamp:initialTimestamp });
  3327. anchorLoc = this.endpoints[1].anchor.compute( {
  3328. xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
  3329. elementId:this.endpoints[1].elementId,
  3330. txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0],
  3331. timestamp:initialTimestamp
  3332. });
  3333. this.endpoints[1].paint({ anchorLoc : anchorLoc, timestamp:initialTimestamp });
  3334. /*
  3335. * Paints the Connection. Not exposed for public usage.
  3336. *
  3337. * Parameters:
  3338. * elId - Id of the element that is in motion.
  3339. * ui - current library's event system ui object (present if we came from a drag to get here).
  3340. * recalc - whether or not to recalculate all anchors etc before painting.
  3341. * timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
  3342. */
  3343. this.paint = function(params) {
  3344. params = params || {};
  3345. var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp,
  3346. // if the moving object is not the source we must transpose the two references.
  3347. swap = false,
  3348. tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
  3349. tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  3350. _updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp });
  3351. _updateOffset( { elId : tId, timestamp : timestamp }); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  3352. var sE = this.endpoints[sIdx], tE = this.endpoints[tIdx],
  3353. sAnchorP = sE.anchor.getCurrentLocation(sE),
  3354. tAnchorP = tE.anchor.getCurrentLocation(tE);
  3355. /* paint overlays*/
  3356. var maxSize = 0;
  3357. for ( var i = 0; i < self.overlays.length; i++) {
  3358. var o = self.overlays[i];
  3359. if (o.isVisible()) maxSize = Math.max(maxSize, o.computeMaxSize(self.connector));
  3360. }
  3361. var dim = this.connector.compute(sAnchorP, tAnchorP,
  3362. this.endpoints[sIdx], this.endpoints[tIdx],
  3363. this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor,
  3364. self.paintStyleInUse.lineWidth, maxSize);
  3365. self.connector.paint(dim, self.paintStyleInUse);
  3366. /* paint overlays*/
  3367. for ( var i = 0; i < self.overlays.length; i++) {
  3368. var o = self.overlays[i];
  3369. if (o.isVisible) self.overlayPlacements[i] = o.draw(self.connector, self.paintStyleInUse, dim);
  3370. }
  3371. };
  3372. /*
  3373. * Function: repaint
  3374. * Repaints the Connection.
  3375. */
  3376. this.repaint = function(params) {
  3377. params = params || {};
  3378. var recalc = !(params.recalc === false);
  3379. this.paint({ elId : this.sourceId, recalc : recalc, timestamp:params.timestamp });
  3380. };
  3381. // resizing (using the jquery.ba-resize plugin). todo: decide
  3382. // whether to include or not.
  3383. if (this.source.resize) {
  3384. this.source.resize(function(e) {
  3385. jsPlumb.repaint(self.sourceId);
  3386. });
  3387. }
  3388. // just to make sure the UI gets initialised fully on all browsers.
  3389. self.repaint();
  3390. };
  3391. // ENDPOINT HELPER FUNCTIONS
  3392. var _makeConnectionDragHandler = function(placeholder) {
  3393. var stopped = false;
  3394. return function() {
  3395. if (stopped) return true;
  3396. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments),
  3397. el = placeholder.element;
  3398. if (el) {
  3399. jsPlumb.CurrentLibrary.setOffset(el, _ui);
  3400. _draw(_getElementObject(el), _ui);
  3401. }
  3402. this.stopDrag = function() {
  3403. stopped = true;
  3404. };
  3405. };
  3406. };
  3407. var _makeFloatingEndpoint = function(paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement) {
  3408. var floatingAnchor = new FloatingAnchor( { reference : referenceAnchor, referenceCanvas : referenceCanvas });
  3409. //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
  3410. // adding the floating endpoint as a droppable. that makes more sense anyway!
  3411. return _newEndpoint({ paintStyle : paintStyle, endpoint : endpoint, anchor : floatingAnchor, source : sourceElement, scope:"__floating" });
  3412. };
  3413. /**
  3414. * creates a placeholder div for dragging purposes, adds it to the DOM, and pre-computes its offset. then returns
  3415. * both the element id and a selector for the element.
  3416. */
  3417. var _makeDraggablePlaceholder = function(placeholder, parent) {
  3418. var n = document.createElement("div");
  3419. n.style.position = "absolute";
  3420. var placeholderDragElement = _getElementObject(n);
  3421. _appendElement(n, parent);
  3422. var id = _getId(placeholderDragElement);
  3423. _updateOffset( { elId : id });
  3424. // create and assign an id, and initialize the offset.
  3425. placeholder.id = id;
  3426. placeholder.element = placeholderDragElement;
  3427. };
  3428. /*
  3429. * Class: Endpoint
  3430. *
  3431. * Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
  3432. * to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
  3433. * actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
  3434. * do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
  3435. * 'target' Endpoints for Connections.
  3436. *
  3437. *
  3438. */
  3439. /*
  3440. * Function: Endpoint
  3441. *
  3442. * Endpoint constructor.
  3443. *
  3444. * Parameters:
  3445. * anchor - definition of the Anchor for the endpoint. You can include one or more Anchor definitions here; if you include more than one, jsPlumb creates a 'dynamic' Anchor, ie. an Anchor which changes position relative to the other elements in a Connection. Each Anchor definition can be either a string nominating one of the basic Anchors provided by jsPlumb (eg. "TopCenter"), or a four element array that designates the Anchor's location and orientation (eg, and this is equivalent to TopCenter, [ 0.5, 0, 0, -1 ]). To provide more than one Anchor definition just put them all in an array. You can mix string definitions with array definitions.
  3446. * endpoint - optional Endpoint definition. This takes the form of either a string nominating one of the basic Endpoints provided by jsPlumb (eg. "Rectangle"), or an array containing [name,params] for those cases where you don't wish to use the default values, eg. [ "Rectangle", { width:5, height:10 } ].
  3447. * paintStyle - endpoint style, a js object. may be null.
  3448. * hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
  3449. * source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
  3450. * canvas - canvas element to use. may be, and most often is, null.
  3451. * container - optional id or selector instructing jsPlumb where to attach the element it creates for this endpoint. you should read the documentation for a full discussion of this.
  3452. * connections - optional list of Connections to configure the Endpoint with.
  3453. * isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
  3454. * maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
  3455. * dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
  3456. * connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
  3457. * connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
  3458. * connector - optional Connector type to use. Like 'endpoint', this may be either a single string nominating a known Connector type (eg. "Bezier", "Straight"), or an array containing [name, params], eg. [ "Bezier", { curviness:160 } ].
  3459. * connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
  3460. * isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
  3461. * dropOptions - if isTarget is set to true, you can supply arguments for the underlying library's drop method with this parameter. Optional; defaults to null.
  3462. * reattach - optional boolean that determines whether or not the Connections reattach after they have been dragged off an Endpoint and left floating. defaults to false: Connections dropped in this way will just be deleted.
  3463. */
  3464. var Endpoint = function(params) {
  3465. var self = this;
  3466. self.idPrefix = "_jsplumb_e_";
  3467. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  3468. params = params || {};
  3469. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3470. /*
  3471. * Function: bind
  3472. * Bind to an event on the Endpoint.
  3473. *
  3474. * Parameters:
  3475. * event - the event to bind. Available events on an Endpoint are:
  3476. * - *click* : notification that a Endpoint was clicked.
  3477. * - *dblclick* : notification that a Endpoint was double clicked.
  3478. * - *mouseenter* : notification that the mouse is over a Endpoint.
  3479. * - *mouseexit* : notification that the mouse exited a Endpoint.
  3480. *
  3481. * callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
  3482. */
  3483. /*
  3484. * Function: setPaintStyle
  3485. * Sets the Endpoint's paint style and then repaints the Endpoint.
  3486. *
  3487. * Parameters:
  3488. * style - Style to use.
  3489. */
  3490. /*
  3491. * Function: setHoverPaintStyle
  3492. * Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
  3493. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  3494. * it. This is because people will most likely want to change just one thing when hovering, say the
  3495. * color for example, but leave the rest of the appearance the same.
  3496. *
  3497. * Parameters:
  3498. * style - Style to use when the mouse is hovering.
  3499. * doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
  3500. */
  3501. /*
  3502. * Function: setHover
  3503. * Sets/unsets the hover state of this Endpoint.
  3504. *
  3505. * Parameters:
  3506. * hover - hover state boolean
  3507. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  3508. */
  3509. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  3510. var visible = true;
  3511. /*
  3512. Function: isVisible
  3513. Returns whether or not the Endpoint is currently visible.
  3514. */
  3515. this.isVisible = function() { return visible; };
  3516. /*
  3517. Function: setVisible
  3518. Sets whether or not the Endpoint is currently visible.
  3519. Parameters:
  3520. visible - whether or not the Endpoint should be visible.
  3521. doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
  3522. doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
  3523. */
  3524. this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  3525. visible = v;
  3526. if (self.canvas) self.canvas.style.display = v ? "block" : "none";
  3527. if (!doNotChangeConnections) {
  3528. for (var i = 0; i < self.connections.length; i++) {
  3529. self.connections[i].setVisible(v);
  3530. if (!doNotNotifyOtherEndpoint) {
  3531. var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
  3532. // only change the other endpoint if this is its only connection.
  3533. if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
  3534. }
  3535. }
  3536. }
  3537. };
  3538. var _element = params.source, _uuid = params.uuid, floatingEndpoint = null, inPlaceCopy = null;
  3539. if (_uuid) endpointsByUUID[_uuid] = self;
  3540. var _elementId = _getAttribute(_element, "id");
  3541. this.elementId = _elementId;
  3542. this.element = _element;
  3543. if (params.dynamicAnchors)
  3544. self.anchor = new DynamicAnchor(jsPlumb.makeAnchors(params.dynamicAnchors));
  3545. else
  3546. self.anchor = params.anchor ? jsPlumb.makeAnchor(params.anchor, _elementId, _currentInstance) : params.anchors ? jsPlumb.makeAnchor(params.anchors, _elementId, _currentInstance) : jsPlumb.makeAnchor("TopCenter", _elementId, _currentInstance);
  3547. // ANCHOR MANAGER
  3548. if (!params._transient) // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted.
  3549. _currentInstance.anchorManager.add(self, _elementId);
  3550. var _endpoint = params.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot",
  3551. endpointArgs = {
  3552. _jsPlumb:self._jsPlumb,
  3553. parent:params.parent,
  3554. container:params.container,
  3555. tooltip:params.tooltip,
  3556. connectorTooltip:params.connectorTooltip,
  3557. endpoint:self
  3558. };
  3559. if (_endpoint.constructor == String)
  3560. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint](endpointArgs);
  3561. else if (_endpoint.constructor == Array) {
  3562. endpointArgs = jsPlumb.extend(_endpoint[1], endpointArgs);
  3563. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint[0]](endpointArgs);
  3564. }
  3565. else
  3566. _endpoint = _endpoint.clone();
  3567. // assign a clone function using our derived endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
  3568. // and the clone is left in its place while the original one goes off on a magical journey.
  3569. this.clone = function() {
  3570. var o = new Object();
  3571. _endpoint.constructor.apply(o, [endpointArgs]);
  3572. return o;
  3573. };
  3574. self.endpoint = _endpoint;
  3575. self.type = self.endpoint.type;
  3576. // override setHover to pass it down to the underlying endpoint
  3577. var _sh = self.setHover;
  3578. self.setHover = function() {
  3579. self.endpoint.setHover.apply(self.endpoint, arguments);
  3580. _sh.apply(self, arguments);
  3581. };
  3582. // endpoint delegates to first connection for hover, if there is one.
  3583. var internalHover = function(state) {
  3584. if (self.connections.length > 0)
  3585. self.connections[0].setHover(state, false);
  3586. else
  3587. self.setHover(state);
  3588. };
  3589. // TODO this event listener registration code is identical to what Connection does: it should be refactored.
  3590. this.endpoint.bind("click", function(e) { self.fire("click", self, e); });
  3591. this.endpoint.bind("dblclick", function(e) { self.fire("dblclick", self, e); });
  3592. // this method is different; endpoint delegates hover to the first connection if there is one.
  3593. // that allows the connection to notify all its endpoint and avoids a circular loop
  3594. this.endpoint.bind("mouseenter", function(con, e) {
  3595. if (!self.isHover()) {
  3596. internalHover(true);
  3597. self.fire("mouseenter", self, e);
  3598. }
  3599. });
  3600. // this method is different; endpoint delegates hover to the first connection if there is one.
  3601. // that allows the connection to notify all its endpoint and avoids a circular loop
  3602. this.endpoint.bind("mouseexit", function(con, e) {
  3603. if (self.isHover()) {
  3604. internalHover(false);
  3605. self.fire("mouseexit", self, e);
  3606. }
  3607. });
  3608. this.setPaintStyle(params.paintStyle ||
  3609. params.style ||
  3610. _currentInstance.Defaults.EndpointStyle ||
  3611. jsPlumb.Defaults.EndpointStyle, true);
  3612. this.setHoverPaintStyle(params.hoverPaintStyle ||
  3613. _currentInstance.Defaults.EndpointHoverStyle ||
  3614. jsPlumb.Defaults.EndpointHoverStyle, true);
  3615. this.paintStyleInUse = this.paintStyle;
  3616. this.connectorStyle = params.connectorStyle;
  3617. this.connectorHoverStyle = params.connectorHoverStyle;
  3618. this.connectorOverlays = params.connectorOverlays;
  3619. this.connector = params.connector;
  3620. this.connectorTooltip = params.connectorTooltip;
  3621. this.parent = params.parent;
  3622. this.isSource = params.isSource || false;
  3623. this.isTarget = params.isTarget || false;
  3624. var _maxConnections = params.maxConnections || _currentInstance.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
  3625. this.getAttachedElements = function() {
  3626. return self.connections;
  3627. };
  3628. /*
  3629. * Property: canvas
  3630. * The Endpoint's Canvas.
  3631. */
  3632. this.canvas = this.endpoint.canvas;
  3633. /*
  3634. * Property: connections
  3635. * List of Connections this Endpoint is attached to.
  3636. */
  3637. this.connections = params.connections || [];
  3638. /*
  3639. * Property: scope
  3640. * Scope descriptor for this Endpoint.
  3641. */
  3642. this.scope = params.scope || DEFAULT_SCOPE;
  3643. this.timestamp = null;
  3644. self.isReattach = params.reattach || false;
  3645. self.connectionsDetachable = _currentInstance.Defaults.ConnectionsDetachable;
  3646. if (params.connectionsDetachable === false || params.detachable === false)
  3647. self.connectionsDetachable = false;
  3648. var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
  3649. this.computeAnchor = function(params) {
  3650. return self.anchor.compute(params);
  3651. };
  3652. /*
  3653. * Function: addConnection
  3654. * Adds a Connection to this Endpoint.
  3655. *
  3656. * Parameters:
  3657. * connection - the Connection to add.
  3658. */
  3659. this.addConnection = function(connection) {
  3660. self.connections.push(connection);
  3661. };
  3662. /*
  3663. * Function: detach
  3664. * Detaches the given Connection from this Endpoint.
  3665. *
  3666. * Parameters:
  3667. * connection - the Connection to detach.
  3668. * ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
  3669. */
  3670. this.detach = function(connection, ignoreTarget, forceDetach, fireEvent) {
  3671. var idx = _findIndex(self.connections, connection), actuallyDetached = false;
  3672. fireEvent = (fireEvent !== false);
  3673. if (idx >= 0) {
  3674. // 1. does the connection have a before detach (note this also checks jsPlumb's bound
  3675. // detach handlers; but then Endpoint's check will, too, hmm.)
  3676. if (forceDetach || connection._forceDetach || connection.isDetachable() || connection.isDetachAllowed(connection)) {
  3677. // get the target endpoint
  3678. var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
  3679. // it would be nice to check with both endpoints that it is ok to detach. but
  3680. // for this we'll have to get a bit fancier: right now if you use the same beforeDetach
  3681. // interceptor for two endpoints (which is kind of common, because it's part of the
  3682. // endpoint definition), then it gets fired twice. so in fact we need to loop through
  3683. // each beforeDetach and see if it returns false, at which point we exit. but if it
  3684. // returns true, we have to check the next one. however we need to track which ones
  3685. // have already been run, and not run them again.
  3686. if (forceDetach || connection._forceDetach || (self.isDetachAllowed(connection) /*&& t.isDetachAllowed(connection)*/)) {
  3687. self.connections.splice(idx, 1);
  3688. // this avoids a circular loop
  3689. if (!ignoreTarget) {
  3690. t.detach(connection, true, forceDetach);
  3691. // check connection to see if we want to delete the endpoints associated with it.
  3692. // we only detach those that have just this connection; this scenario is most
  3693. // likely if we got to this bit of code because it is set by the methods that
  3694. // create their own endpoints, like .connect or .makeTarget. the user is
  3695. // not likely to have interacted with those endpoints.
  3696. if (connection.endpointsToDeleteOnDetach){
  3697. for (var i = 0; i < connection.endpointsToDeleteOnDetach.length; i++) {
  3698. var cde = connection.endpointsToDeleteOnDetach[i];
  3699. if (cde && cde.connections.length == 0)
  3700. jsPlumb.deleteEndpoint(cde);
  3701. }
  3702. }
  3703. }
  3704. _removeElements(connection.connector.getDisplayElements(), connection.parent);
  3705. _removeFromList(connectionsByScope, connection.scope, connection);
  3706. actuallyDetached = true;
  3707. var doFireEvent = (!ignoreTarget && fireEvent)
  3708. fireDetachEvent(connection, doFireEvent);
  3709. }
  3710. }
  3711. }
  3712. return actuallyDetached;
  3713. };
  3714. /*
  3715. * Function: detachAll
  3716. * Detaches all Connections this Endpoint has.
  3717. *
  3718. * Parameters:
  3719. * fireEvent - whether or not to fire the detach event. defaults to false.
  3720. */
  3721. this.detachAll = function(fireEvent) {
  3722. while (self.connections.length > 0) {
  3723. self.detach(self.connections[0], false, true, fireEvent);
  3724. }
  3725. };
  3726. /*
  3727. * Function: detachFrom
  3728. * Removes any connections from this Endpoint that are connected to the given target endpoint.
  3729. *
  3730. * Parameters:
  3731. * targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
  3732. * fireEvent - whether or not to fire the detach event. defaults to false.
  3733. */
  3734. this.detachFrom = function(targetEndpoint, fireEvent) {
  3735. var c = [];
  3736. for ( var i = 0; i < self.connections.length; i++) {
  3737. if (self.connections[i].endpoints[1] == targetEndpoint
  3738. || self.connections[i].endpoints[0] == targetEndpoint) {
  3739. c.push(self.connections[i]);
  3740. }
  3741. }
  3742. for ( var i = 0; i < c.length; i++) {
  3743. if (self.detach(c[i], false, true, fireEvent))
  3744. c[i].setHover(false, false);
  3745. }
  3746. };
  3747. /*
  3748. * Function: detachFromConnection
  3749. * Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
  3750. *
  3751. * Parameters:
  3752. * connection - Connection to detach from.
  3753. */
  3754. this.detachFromConnection = function(connection) {
  3755. var idx = _findIndex(self.connections, connection);
  3756. if (idx >= 0) {
  3757. self.connections.splice(idx, 1);
  3758. }
  3759. };
  3760. /*
  3761. * Function: getElement
  3762. * Returns the DOM element this Endpoint is attached to.
  3763. */
  3764. this.getElement = function() {
  3765. return _element;
  3766. };
  3767. /*
  3768. * Function: setElement
  3769. * Sets the DOM element this Endpoint is attached to.
  3770. */
  3771. this.setElement = function(el) {
  3772. // TODO possibly have this object take charge of moving the UI components into the appropriate
  3773. // parent. this is used only by makeSource right now, and that function takes care of
  3774. // moving the UI bits and pieces. however it would s
  3775. var parentId = _getId(el);
  3776. // remove the endpoint from the list for the current endpoint's element
  3777. _removeFromList(endpointsByElement, _elementId, self);
  3778. _element = _getElementObject(el);
  3779. _elementId = _getId(_element);
  3780. self.elementId = _elementId;
  3781. // need to get the new parent now
  3782. var newParentElement = _getParentFromParams({source:parentId}),
  3783. curParent = jpcl.getParent(self.canvas);
  3784. jpcl.removeElement(self.canvas, curParent);
  3785. jpcl.appendElement(self.canvas, newParentElement);
  3786. // now move connection(s)...i would expect there to be only one but we will iterate.
  3787. for (var i = 0; i < self.connections.length; i++) {
  3788. self.connections[i].moveParent(newParentElement);
  3789. self.connections[i].sourceId = _elementId;
  3790. self.connections[i].source = _element;
  3791. }
  3792. _addToList(endpointsByElement, parentId, self);
  3793. _currentInstance.repaint(parentId);
  3794. };
  3795. /*
  3796. * Function: getUuid
  3797. * Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
  3798. */
  3799. this.getUuid = function() {
  3800. return _uuid;
  3801. };
  3802. /**
  3803. * private but must be exposed.
  3804. */
  3805. this.makeInPlaceCopy = function() {
  3806. return _newEndpoint( {
  3807. anchor : self.anchor,
  3808. source : _element,
  3809. paintStyle : this.paintStyle,
  3810. endpoint : _endpoint,
  3811. _transient:true,
  3812. scope:self.scope
  3813. });
  3814. };
  3815. /*
  3816. * Function: isConnectedTo
  3817. * Returns whether or not this endpoint is connected to the given Endpoint.
  3818. *
  3819. * Parameters:
  3820. * endpoint - Endpoint to test.
  3821. */
  3822. this.isConnectedTo = function(endpoint) {
  3823. var found = false;
  3824. if (endpoint) {
  3825. for ( var i = 0; i < self.connections.length; i++) {
  3826. if (self.connections[i].endpoints[1] == endpoint) {
  3827. found = true;
  3828. break;
  3829. }
  3830. }
  3831. }
  3832. return found;
  3833. };
  3834. /**
  3835. * private but needs to be exposed.
  3836. */
  3837. this.isFloating = function() {
  3838. return floatingEndpoint != null;
  3839. };
  3840. /**
  3841. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  3842. */
  3843. this.connectorSelector = function() {
  3844. var candidate = self.connections[0];
  3845. if (self.isTarget && candidate) return candidate;
  3846. else {
  3847. return (self.connections.length < _maxConnections) || _maxConnections == -1 ? null : candidate;
  3848. }
  3849. };
  3850. /*
  3851. * Function: isFull
  3852. * Returns whether or not the Endpoint can accept any more Connections.
  3853. */
  3854. this.isFull = function() {
  3855. return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
  3856. };
  3857. /*
  3858. * Function: setDragAllowedWhenFull
  3859. * Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
  3860. * which you're going to provide some other way of breaking connections, if you need to break them at all. This property
  3861. * is by default true; use it in conjunction with the 'reattach' option on a connect call.
  3862. *
  3863. * Parameters:
  3864. * allowed - whether drag is allowed or not when the Endpoint is full.
  3865. */
  3866. this.setDragAllowedWhenFull = function(allowed) {
  3867. dragAllowedWhenFull = allowed;
  3868. };
  3869. /*
  3870. * Function: setStyle
  3871. * Sets the paint style of the Endpoint. This is a JS object of the same form you supply to a jsPlumb.addEndpoint or jsPlumb.connect call.
  3872. * TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
  3873. * setStyle and deprecate it if so.
  3874. *
  3875. * Parameters:
  3876. * style - Style object to set, for example {fillStyle:"blue"}.
  3877. *
  3878. * @deprecated use setPaintStyle instead.
  3879. */
  3880. this.setStyle = self.setPaintStyle;
  3881. /**
  3882. * a deep equals check. everything must match, including the anchor,
  3883. * styles, everything. TODO: finish Endpoint.equals
  3884. */
  3885. this.equals = function(endpoint) {
  3886. return this.anchor.equals(endpoint.anchor);
  3887. };
  3888. // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
  3889. // or no connection to it is found, we return the first connection in our list.
  3890. var findConnectionToUseForDynamicAnchor = function(elementWithPrecedence) {
  3891. var idx = 0;
  3892. if (elementWithPrecedence != null) {
  3893. for (var i = 0; i < self.connections.length; i++) {
  3894. if (self.connections[i].sourceId == elementWithPrecedence || self.connections[i].targetId == elementWithPrecedence) {
  3895. idx = i;
  3896. break;
  3897. }
  3898. }
  3899. }
  3900. return self.connections[idx];
  3901. };
  3902. /*
  3903. * Function: paint
  3904. * Paints the Endpoint, recalculating offset and anchor positions if necessary. This does NOT paint
  3905. * any of the Endpoint's connections.
  3906. *
  3907. * Parameters:
  3908. * timestamp - optional timestamp advising the Endpoint of the current paint time; if it has painted already once for this timestamp, it will not paint again.
  3909. * canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
  3910. * connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
  3911. */
  3912. this.paint = function(params) {
  3913. params = params || {};
  3914. var timestamp = params.timestamp,
  3915. recalc = !(params.recalc === false);
  3916. if (!timestamp || self.timestamp !== timestamp) {
  3917. _updateOffset({ elId:_elementId, timestamp:timestamp, recalc:recalc });
  3918. var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle;
  3919. if (ap == null) {
  3920. var xy = params.offset || offsets[_elementId],
  3921. wh = params.dimensions || sizes[_elementId];
  3922. if (xy == null || wh == null) {
  3923. _updateOffset( { elId : _elementId, timestamp : timestamp });
  3924. xy = offsets[_elementId];
  3925. wh = sizes[_elementId];
  3926. }
  3927. var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
  3928. if (recalc && self.anchor.isDynamic && self.connections.length > 0) {
  3929. var c = findConnectionToUseForDynamicAnchor(params.elementWithPrecedence),
  3930. oIdx = c.endpoints[0] == self ? 1 : 0,
  3931. oId = oIdx == 0 ? c.sourceId : c.targetId,
  3932. oOffset = offsets[oId], oWH = sizes[oId];
  3933. anchorParams.txy = [ oOffset.left, oOffset.top ];
  3934. anchorParams.twh = oWH;
  3935. anchorParams.tElement = c.endpoints[oIdx];
  3936. }
  3937. ap = self.anchor.compute(anchorParams);
  3938. }
  3939. var d = _endpoint.compute(ap, self.anchor.getOrientation(_endpoint), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
  3940. _endpoint.paint(d, self.paintStyleInUse, self.anchor);
  3941. self.timestamp = timestamp;
  3942. }
  3943. };
  3944. this.repaint = this.paint;
  3945. /**
  3946. * @deprecated
  3947. */
  3948. this.removeConnection = this.detach; // backwards compatibility
  3949. // is this a connection source? we make it draggable and have the
  3950. // drag listener maintain a connection with a floating endpoint.
  3951. if (jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  3952. var placeholderInfo = {
  3953. id:null,
  3954. element:null
  3955. },
  3956. jpc = null,
  3957. existingJpc = false,
  3958. existingJpcParams = null,
  3959. _dragHandler = _makeConnectionDragHandler(placeholderInfo);
  3960. var start = function() {
  3961. // drag might have started on an endpoint that is not actually a source, but which has
  3962. // one or more connections.
  3963. jpc = self.connectorSelector();
  3964. var _continue = true;
  3965. // if no connection and we're not a source, return.
  3966. if (jpc == null && !params.isSource) _continue = false;
  3967. // otherwise if we're full and not allowed to drag, also return false.
  3968. if (params.isSource && self.isFull() && !dragAllowedWhenFull) _continue = false;
  3969. // if the connection was setup as not detachable (or one of its endpoints
  3970. // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
  3971. // is set to false...
  3972. if (jpc != null && !jpc.isDetachable()) _continue = false;
  3973. if (_continue === false) {
  3974. // this is for mootools and yui. returning false from this causes jquery to stop drag.
  3975. // the events are wrapped in both mootools and yui anyway, but i don't think returning
  3976. // false from the start callback would stop a drag.
  3977. if (jsPlumb.CurrentLibrary.stopDrag) jsPlumb.CurrentLibrary.stopDrag();
  3978. _dragHandler.stopDrag();
  3979. return false;
  3980. }
  3981. // if we're not full but there was a connection, make it null. we'll create a new one.
  3982. if (jpc && !self.isFull() && params.isSource) jpc = null;
  3983. _updateOffset( { elId : _elementId });
  3984. inPlaceCopy = self.makeInPlaceCopy();
  3985. inPlaceCopy.paint();
  3986. _makeDraggablePlaceholder(placeholderInfo, self.parent);
  3987. // set the offset of this div to be where 'inPlaceCopy' is, to start with.
  3988. // TODO merge this code with the code in both Anchor and FloatingAnchor, because it
  3989. // does the same stuff.
  3990. var ipcoel = _getElementObject(inPlaceCopy.canvas),
  3991. ipco = jsPlumb.CurrentLibrary.getOffset(ipcoel),
  3992. po = adjustForParentOffsetAndScroll([ipco.left, ipco.top], inPlaceCopy.canvas);
  3993. jsPlumb.CurrentLibrary.setOffset(placeholderInfo.element, {left:po[0], top:po[1]});
  3994. // store the id of the dragging div and the source element. the drop function will pick these up.
  3995. _setAttribute(_getElementObject(self.canvas), "dragId", placeholderInfo.id);
  3996. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  3997. // create a floating anchor
  3998. floatingEndpoint = _makeFloatingEndpoint(self.paintStyle, self.anchor, _endpoint, self.canvas, placeholderInfo.element);
  3999. if (jpc == null) {
  4000. self.anchor.locked = true;
  4001. self.setHover(false, false);
  4002. // TODO the hover call above does not reset any target endpoint's hover
  4003. // states.
  4004. // create a connection. one end is this endpoint, the other is a floating endpoint.
  4005. jpc = _newConnection({
  4006. sourceEndpoint : self,
  4007. targetEndpoint : floatingEndpoint,
  4008. source : self.endpointWillMoveTo || _getElementObject(_element), // for makeSource with parent option. ensure source element is represented correctly.
  4009. target : placeholderInfo.element,
  4010. anchors : [ self.anchor, floatingEndpoint.anchor ],
  4011. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  4012. hoverPaintStyle:params.connectorHoverStyle,
  4013. connector : params.connector, // this can also be null. Connection will use the default.
  4014. overlays : params.connectorOverlays
  4015. });
  4016. } else {
  4017. existingJpc = true;
  4018. jpc.connector.setHover(false, false);
  4019. // jpc.endpoints[0].setHover(false, false);
  4020. //jpc.endpoints[1].setHover(false, false);
  4021. // if existing connection, allow to be dropped back on the source endpoint (issue 51).
  4022. _initDropTarget(_getElementObject(inPlaceCopy.canvas), false, true);
  4023. //var anchorIdx = jpc.sourceId == _elementId ? 0 : 1; // are we the source or the target?
  4024. // new anchor idx
  4025. var anchorIdx = jpc.endpoints[0].id == self.id ? 0 : 1;
  4026. jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
  4027. self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
  4028. // store the original scope (issue 57)
  4029. var c = _getElementObject(self.canvas),
  4030. dragScope = jsPlumb.CurrentLibrary.getDragScope(c);
  4031. _setAttribute(c, "originalScope", dragScope);
  4032. // now we want to get this endpoint's DROP scope, and set it for now: we can only be dropped on drop zones
  4033. // that have our drop scope (issue 57).
  4034. var dropScope = jsPlumb.CurrentLibrary.getDropScope(c);
  4035. jsPlumb.CurrentLibrary.setDragScope(c, dropScope);
  4036. // now we replace ourselves with the temporary div we created above:
  4037. if (anchorIdx == 0) {
  4038. existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
  4039. jpc.source = placeholderInfo.element;
  4040. jpc.sourceId = placeholderInfo.id;
  4041. } else {
  4042. existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
  4043. jpc.target = placeholderInfo.element;
  4044. jpc.targetId = placeholderInfo.id;
  4045. }
  4046. // lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
  4047. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
  4048. // store the original endpoint and assign the new floating endpoint for the drag.
  4049. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  4050. jpc.suspendedEndpoint.setHover(false);
  4051. jpc.endpoints[anchorIdx] = floatingEndpoint;
  4052. }
  4053. // register it and register connection on it.
  4054. floatingConnections[placeholderInfo.id] = jpc;
  4055. floatingEndpoint.addConnection(jpc);
  4056. // only register for the target endpoint; we will not be dragging the source at any time
  4057. // before this connection is either discarded or made into a permanent connection.
  4058. _addToList(endpointsByElement, placeholderInfo.id, floatingEndpoint);
  4059. // tell jsplumb about it
  4060. _currentInstance.currentlyDragging = true;
  4061. };
  4062. var jpcl = jsPlumb.CurrentLibrary,
  4063. dragOptions = params.dragOptions || {},
  4064. defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
  4065. startEvent = jpcl.dragEvents["start"],
  4066. stopEvent = jpcl.dragEvents["stop"],
  4067. dragEvent = jpcl.dragEvents["drag"];
  4068. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  4069. dragOptions.scope = dragOptions.scope || self.scope;
  4070. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  4071. // extracted drag handler function so can be used by makeSource
  4072. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], _dragHandler);
  4073. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  4074. function() {
  4075. _currentInstance.currentlyDragging = false;
  4076. _removeFromList(endpointsByElement, placeholderInfo.id, floatingEndpoint);
  4077. _removeElements( [ placeholderInfo.element[0], floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
  4078. _removeElement(inPlaceCopy.canvas, _element);
  4079. _currentInstance.anchorManager.clearFor(placeholderInfo.id);
  4080. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  4081. jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
  4082. if (jpc.endpoints[idx] == floatingEndpoint) {
  4083. // if the connection was an existing one:
  4084. if (existingJpc && jpc.suspendedEndpoint) {
  4085. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  4086. // floating endpoint has been replaced.
  4087. if (idx == 0) {
  4088. jpc.source = existingJpcParams[0];
  4089. jpc.sourceId = existingJpcParams[1];
  4090. } else {
  4091. jpc.target = existingJpcParams[0];
  4092. jpc.targetId = existingJpcParams[1];
  4093. }
  4094. // restore the original scope (issue 57)
  4095. jsPlumb.CurrentLibrary.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  4096. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  4097. if (self.isReattach || jpc._forceDetach || !jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc)) {
  4098. jpc.setHover(false);
  4099. jpc.floatingAnchorIndex = null;
  4100. jpc.suspendedEndpoint.addConnection(jpc);
  4101. jsPlumb.repaint(existingJpcParams[1]);
  4102. }
  4103. jpc._forceDetach = null;
  4104. } else {
  4105. // TODO this looks suspiciously kind of like an Endpoint.detach call too.
  4106. // i wonder if this one should post an event though. maybe this is good like this.
  4107. _removeElements(jpc.connector.getDisplayElements(), self.parent);
  4108. self.detachFromConnection(jpc);
  4109. }
  4110. }
  4111. self.anchor.locked = false;
  4112. self.paint({recalc:false});
  4113. jpc.setHover(false, false);
  4114. jpc = null;
  4115. inPlaceCopy = null;
  4116. delete endpointsByElement[floatingEndpoint.elementId];
  4117. floatingEndpoint.anchor = null;
  4118. floatingEndpoint = null;
  4119. _currentInstance.currentlyDragging = false;
  4120. });
  4121. var i = _getElementObject(self.canvas);
  4122. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions, true);
  4123. }
  4124. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  4125. // back onto the endpoint you detached it from.
  4126. var _initDropTarget = function(canvas, forceInit, isTransient) {
  4127. if ((params.isTarget || forceInit) && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  4128. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  4129. dropOptions = jsPlumb.extend( {}, dropOptions);
  4130. dropOptions.scope = dropOptions.scope || self.scope;
  4131. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'],
  4132. overEvent = jsPlumb.CurrentLibrary.dragEvents['over'],
  4133. outEvent = jsPlumb.CurrentLibrary.dragEvents['out'],
  4134. drop = function() {
  4135. var draggable = _getElementObject(jsPlumb.CurrentLibrary.getDragObject(arguments)),
  4136. id = _getAttribute(draggable, "dragId"),
  4137. elId = _getAttribute(draggable, "elId"),
  4138. scope = _getAttribute(draggable, "originalScope"),
  4139. jpc = floatingConnections[id],
  4140. idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
  4141. // restore the original scope if necessary (issue 57)
  4142. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  4143. if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
  4144. var _doContinue = true;
  4145. // the second check here is for the case that the user is dropping it back
  4146. // where it came from.
  4147. if (jpc.suspendedEndpoint && jpc.suspendedEndpoint.id != self.id) {
  4148. if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_currentInstance.checkCondition("beforeDetach", jpc))
  4149. _doContinue = false;
  4150. }
  4151. // these have to be set before testing for beforeDrop.
  4152. if (idx == 0) {
  4153. jpc.source = _element;
  4154. jpc.sourceId = _elementId;
  4155. } else {
  4156. jpc.target = _element;
  4157. jpc.targetId = _elementId;
  4158. }
  4159. // now check beforeDrop. this will be available only on Endpoints that are setup to
  4160. // have a beforeDrop condition (although, secretly, under the hood all Endpoints and
  4161. // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
  4162. // it only makes sense to have it on a target endpoint.
  4163. _doContinue = _doContinue && self.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope);
  4164. if (_doContinue) {
  4165. // remove this jpc from the current endpoint
  4166. jpc.endpoints[idx].detachFromConnection(jpc);
  4167. if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
  4168. jpc.endpoints[idx] = self;
  4169. self.addConnection(jpc);
  4170. if (!jpc.suspendedEndpoint) {
  4171. //_addToList(connectionsByScope, jpc.scope, jpc);
  4172. _initDraggableIfNecessary(_element, params.draggable, {});
  4173. }
  4174. else {
  4175. var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
  4176. // fire a detach event
  4177. fireDetachEvent({
  4178. source : idx == 0 ? suspendedElement : jpc.source,
  4179. target : idx == 1 ? suspendedElement : jpc.target,
  4180. sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
  4181. targetId : idx == 1 ? suspendedElementId : jpc.targetId,
  4182. sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  4183. targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  4184. connection : jpc
  4185. }, true);
  4186. }
  4187. // finalise will inform the anchor manager and also add to
  4188. // connectionsByScope if necessary.
  4189. _finaliseConnection(jpc);
  4190. }
  4191. else {
  4192. // otherwise just put it back on the endpoint it was on before the drag.
  4193. if (jpc.suspendedEndpoint) {
  4194. // self.detachFrom(jpc);
  4195. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  4196. jpc.setHover(false);
  4197. jpc._forceDetach = true;
  4198. if (idx == 0) {
  4199. jpc.source = jpc.suspendedEndpoint.element;
  4200. jpc.sourceId = jpc.suspendedEndpoint.elementId;
  4201. } else {
  4202. jpc.target = jpc.suspendedEndpoint.element;
  4203. jpc.targetId = jpc.suspendedEndpoint.elementId;;
  4204. }
  4205. jpc.suspendedEndpoint.addConnection(jpc);
  4206. jpc.endpoints[0].repaint();
  4207. jpc.repaint();
  4208. jsPlumb.repaint(jpc.source.elementId);
  4209. jpc._forceDetach = false;
  4210. }
  4211. }
  4212. jpc.floatingAnchorIndex = null;
  4213. }
  4214. _currentInstance.currentlyDragging = false;
  4215. delete floatingConnections[id];
  4216. };
  4217. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], drop);
  4218. dropOptions[overEvent] = _wrap(dropOptions[overEvent], function() {
  4219. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  4220. id = _getAttribute( _getElementObject(draggable), "dragId"),
  4221. jpc = floatingConnections[id];
  4222. if (jpc != null) {
  4223. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  4224. jpc.endpoints[idx].anchor.over(self.anchor);
  4225. }
  4226. });
  4227. dropOptions[outEvent] = _wrap(dropOptions[outEvent], function() {
  4228. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  4229. id = _getAttribute( _getElementObject(draggable), "dragId"),
  4230. jpc = floatingConnections[id];
  4231. if (jpc != null) {
  4232. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  4233. jpc.endpoints[idx].anchor.out();
  4234. }
  4235. });
  4236. jsPlumb.CurrentLibrary.initDroppable(canvas, dropOptions, true, isTransient);
  4237. }
  4238. };
  4239. // initialise the endpoint's canvas as a drop target. this will be ignored if the endpoint is not a target or drag is not supported.
  4240. _initDropTarget(_getElementObject(self.canvas), true, !(params._transient || self.anchor.isFloating));
  4241. return self;
  4242. };
  4243. };
  4244. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  4245. jsPlumb.getInstance = function(_defaults) {
  4246. var j = new jsPlumbInstance(_defaults);
  4247. j.init();
  4248. return j;
  4249. };
  4250. jsPlumb.util = {
  4251. convertStyle : function(s, ignoreAlpha) {
  4252. // TODO: jsPlumb should support a separate 'opacity' style member.
  4253. if ("transparent" === s) return s;
  4254. var o = s,
  4255. pad = function(n) { return n.length == 1 ? "0" + n : n; },
  4256. hex = function(k) { return pad(Number(k).toString(16)); },
  4257. pattern = /(rgb[a]?\()(.*)(\))/;
  4258. if (s.match(pattern)) {
  4259. var parts = s.match(pattern)[2].split(",");
  4260. o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
  4261. if (!ignoreAlpha && parts.length == 4)
  4262. o = o + hex(parts[3]);
  4263. }
  4264. return o;
  4265. },
  4266. gradient : function(p1, p2) {
  4267. p1 = p1.constructor == Array ? p1 : [p1.x, p1.y];
  4268. p2 = p2.constructor == Array ? p2 : [p2.x, p2.y];
  4269. return (p2[1] - p1[1]) / (p2[0] - p1[0]);
  4270. },
  4271. normal : function(p1, p2) {
  4272. return -1 / jsPlumb.util.gradient(p1,p2);
  4273. },
  4274. segment : function(p1, p2) {
  4275. p1 = p1.constructor == Array ? p1 : [p1.x, p1.y];
  4276. p2 = p2.constructor == Array ? p2 : [p2.x, p2.y];
  4277. if (p2[0] > p1[0]) {
  4278. return (p2[1] > p1[1]) ? 2 : 1;
  4279. }
  4280. else {
  4281. return (p2[1] > p1[1]) ? 3 : 4;
  4282. }
  4283. },
  4284. segmentMultipliers : [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
  4285. inverseSegmentMultipliers : [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
  4286. pointOnLine : function(fromPoint, toPoint, distance) {
  4287. var m = jsPlumb.util.gradient(fromPoint, toPoint),
  4288. s = jsPlumb.util.segment(fromPoint, toPoint),
  4289. segmentMultiplier = distance > 0 ? jsPlumb.util.segmentMultipliers[s] : jsPlumb.util.inverseSegmentMultipliers[s],
  4290. theta = Math.atan(m),
  4291. y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
  4292. x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
  4293. return { x:fromPoint.x + x, y:fromPoint.y + y };
  4294. },
  4295. /**
  4296. * calculates a perpendicular to the line fromPoint->toPoint, that passes through toPoint and is 'length' long.
  4297. * @param fromPoint
  4298. * @param toPoint
  4299. * @param length
  4300. */
  4301. perpendicularLineTo : function(fromPoint, toPoint, length) {
  4302. var m = jsPlumb.util.gradient(fromPoint, toPoint),
  4303. theta2 = Math.atan(-1 / m),
  4304. y = length / 2 * Math.sin(theta2),
  4305. x = length / 2 * Math.cos(theta2);
  4306. return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
  4307. }
  4308. };
  4309. var _curryAnchor = function(x, y, ox, oy, type, fnInit) {
  4310. return function(params) {
  4311. params = params || {};
  4312. var a = jsPlumb.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
  4313. a.type = type;
  4314. if (fnInit) fnInit(a, params);
  4315. return a;
  4316. };
  4317. };
  4318. jsPlumb.Anchors["TopCenter"] = _curryAnchor(0.5, 0, 0,-1, "TopCenter");
  4319. jsPlumb.Anchors["BottomCenter"] = _curryAnchor(0.5, 1, 0, 1, "BottomCenter");
  4320. jsPlumb.Anchors["LeftMiddle"] = _curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
  4321. jsPlumb.Anchors["RightMiddle"] = _curryAnchor(1, 0.5, 1, 0, "RightMiddle");
  4322. jsPlumb.Anchors["Center"] = _curryAnchor(0.5, 0.5, 0, 0, "Center");
  4323. jsPlumb.Anchors["TopRight"] = _curryAnchor(1, 0, 0,-1, "TopRight");
  4324. jsPlumb.Anchors["BottomRight"] = _curryAnchor(1, 1, 0, 1, "BottomRight");
  4325. jsPlumb.Anchors["TopLeft"] = _curryAnchor(0, 0, 0, -1, "TopLeft");
  4326. jsPlumb.Anchors["BottomLeft"] = _curryAnchor(0, 1, 0, 1, "BottomLeft");
  4327. jsPlumb.Defaults.DynamicAnchors = function(params) {
  4328. return jsPlumb.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
  4329. };
  4330. jsPlumb.Anchors["AutoDefault"] = function(params) {
  4331. var a = jsPlumb.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors(params));
  4332. a.type = "AutoDefault";
  4333. return a;
  4334. };
  4335. jsPlumb.Anchors["Assign"] = _curryAnchor(0,0,0,0,"Assign", function(anchor, params) {
  4336. // find what to use as the "position finder". the user may have supplied a String which represents
  4337. // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
  4338. // position finder as a function. we find out what to use and then set it on the anchor.
  4339. var pf = params.position || "Fixed";
  4340. anchor.positionFinder = pf.constructor == String ? jsPlumb.AnchorPositionFinders[pf] : pf;
  4341. // always set the constructor params; the position finder might need them later (the Grid one does,
  4342. // for example)
  4343. anchor.constructorParams = params;
  4344. });
  4345. // Continuous anchor is just curried through to the 'get' method of the continuous anchor
  4346. // factory.
  4347. jsPlumb.Anchors["Continuous"] = function(params) {
  4348. return params.jsPlumbInstance.continuousAnchorFactory.get(params);
  4349. };
  4350. // these are the default anchor positions finders, which are used by the makeTarget function. supply
  4351. // a position finder argument to that function allows you to specify where the resulting anchor will
  4352. // be located
  4353. jsPlumb.AnchorPositionFinders = {
  4354. "Fixed": function(dp, ep, es, a) {
  4355. return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
  4356. },
  4357. "Grid":function(dp, ep, es, a) {
  4358. var dx = dp.left - ep.left, dy = dp.top - ep.top,
  4359. gx = es[0] / (a.constructorParams.grid[0]), gy = es[1] / (a.constructorParams.grid[1]),
  4360. mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
  4361. return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
  4362. }
  4363. };
  4364. })();
  4365. /*
  4366. * jsPlumb
  4367. *
  4368. * Title:jsPlumb 1.3.5
  4369. *
  4370. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  4371. * elements, or VML.
  4372. *
  4373. * This file contains the default Connectors, Endpoint and Overlay definitions.
  4374. *
  4375. * Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org)
  4376. *
  4377. * http://jsplumb.org
  4378. * http://github.com/sporritt/jsplumb
  4379. * http://code.google.com/p/jsplumb
  4380. *
  4381. * Dual licensed under the MIT and GPL2 licenses.
  4382. */
  4383. (function() {
  4384. /**
  4385. *
  4386. * Helper class to consume unused mouse events by components that are DOM elements and
  4387. * are used by all of the different rendering modes.
  4388. *
  4389. */
  4390. jsPlumb.DOMElementComponent = function(params) {
  4391. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  4392. // when render mode is canvas, these functions may be called by the canvas mouse handler.
  4393. // this component is safe to pipe this stuff to /dev/null.
  4394. this.mousemove =
  4395. this.dblclick =
  4396. this.click =
  4397. this.mousedown =
  4398. this.mouseup = function(e) { };
  4399. };
  4400. /**
  4401. * Class: Connectors.Straight
  4402. * The Straight connector draws a simple straight line between the two anchor points. It does not have any constructor parameters.
  4403. */
  4404. jsPlumb.Connectors.Straight = function() {
  4405. this.type = "Straight";
  4406. var self = this,
  4407. currentPoints = null,
  4408. _m, _m2, _b, _dx, _dy, _theta, _theta2, _sx, _sy, _tx, _ty, _segment, _length;
  4409. /**
  4410. * Computes the new size and position of the canvas.
  4411. * @param sourceAnchor Absolute position on screen of the source object's anchor.
  4412. * @param targetAnchor Absolute position on screen of the target object's anchor.
  4413. * @param positionMatrix Indicates the relative positions of the left,top of the
  4414. * two plumbed objects. so [0,0] indicates that the source is to the left of, and
  4415. * above, the target. [1,0] means the source is to the right and above. [0,1] means
  4416. * the source is to the left and below. [1,1] means the source is to the right
  4417. * and below. this is used to figure out which direction to draw the connector in.
  4418. * @returns an array of positioning information. the first two values are
  4419. * the [left, top] absolute position the canvas should be placed on screen. the
  4420. * next two values are the [width,height] the canvas should be. after that each
  4421. * Connector can put whatever it likes into the array:it will be passed back in
  4422. * to the paint call. This particular function stores the origin and destination of
  4423. * the line it is going to draw. a more involved implementation, like a Bezier curve,
  4424. * would store the control point info in this array too.
  4425. */
  4426. this.compute = function(sourcePos, targetPos, sourceEndpoint, targetEndpoint, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  4427. var w = Math.abs(sourcePos[0] - targetPos[0]),
  4428. h = Math.abs(sourcePos[1] - targetPos[1]),
  4429. // these are padding to ensure the whole connector line appears
  4430. xo = 0.45 * w, yo = 0.45 * h;
  4431. // these are padding to ensure the whole connector line appears
  4432. w *= 1.9; h *=1.9;
  4433. var x = Math.min(sourcePos[0], targetPos[0]) - xo;
  4434. var y = Math.min(sourcePos[1], targetPos[1]) - yo;
  4435. // minimum size is 2 * line Width if minWidth was not given.
  4436. var calculatedMinWidth = Math.max(2 * lineWidth, minWidth);
  4437. if (w < calculatedMinWidth) {
  4438. w = calculatedMinWidth;
  4439. x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - (calculatedMinWidth / 2);
  4440. xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;
  4441. }
  4442. if (h < calculatedMinWidth) {
  4443. h = calculatedMinWidth;
  4444. y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - (calculatedMinWidth / 2);
  4445. yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;
  4446. }
  4447. _sx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  4448. _sy = sourcePos[1] < targetPos[1] ? yo:h-yo;
  4449. _tx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  4450. _ty = sourcePos[1] < targetPos[1] ? h-yo : yo;
  4451. currentPoints = [ x, y, w, h, _sx, _sy, _tx, _ty ];
  4452. _dx = _tx - _sx, _dy = _ty - _sy;
  4453. //_m = _dy / _dx, _m2 = -1 / _m;
  4454. _m = jsPlumb.util.gradient({x:_sx, y:_sy}, {x:_tx, y:_ty}), _m2 = -1 / _m;
  4455. _b = -1 * ((_m * _sx) - _sy);
  4456. _theta = Math.atan(_m); _theta2 = Math.atan(_m2);
  4457. //_segment = jsPlumb.util.segment({x:_sx, y:_sy}, {x:_tx, y:_ty});
  4458. _length = Math.sqrt((_dx * _dx) + (_dy * _dy));
  4459. return currentPoints;
  4460. };
  4461. /**
  4462. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  4463. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  4464. */
  4465. this.pointOnPath = function(location) {
  4466. if (location == 0)
  4467. return { x:_sx, y:_sy };
  4468. else if (location == 1)
  4469. return { x:_tx, y:_ty };
  4470. else
  4471. return jsPlumb.util.pointOnLine({x:_sx, y:_sy}, {x:_tx, y:_ty}, location * _length);
  4472. };
  4473. /**
  4474. * returns the gradient of the connector at the given point - which for us is constant.
  4475. */
  4476. this.gradientAtPoint = function(location) {
  4477. return _m;
  4478. };
  4479. /**
  4480. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  4481. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
  4482. * this hands off to jsPlumb.util to do the maths, supplying our gradient and position and whether or
  4483. * not the coords should be flipped
  4484. */
  4485. this.pointAlongPathFrom = function(location, distance) {
  4486. var p = self.pointOnPath(location);
  4487. return jsPlumb.util.pointOnLine(p, {x:_tx,y:_ty}, distance);
  4488. };
  4489. };
  4490. /**
  4491. * Class:Connectors.Bezier
  4492. * This Connector draws a Bezier curve with two control points. You can provide a 'curviness' value which gets applied to jsPlumb's
  4493. * internal voodoo machine and ends up generating locations for the two control points. See the constructor documentation below.
  4494. */
  4495. /**
  4496. * Function:Constructor
  4497. *
  4498. * Parameters:
  4499. * curviness - How 'curvy' you want the curve to be! This is a directive for the placement of control points, not endpoints of the curve, so your curve does not
  4500. * actually touch the given point, but it has the tendency to lean towards it. The larger this value, the greater the curve is pulled from a straight line.
  4501. * Optional; defaults to 150.
  4502. *
  4503. */
  4504. jsPlumb.Connectors.Bezier = function(params) {
  4505. var self = this;
  4506. params = params || {};
  4507. this.majorAnchor = params.curviness || 150;
  4508. this.minorAnchor = 10;
  4509. var currentPoints = null;
  4510. this.type = "Bezier";
  4511. this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, sourceAnchor, targetAnchor) {
  4512. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  4513. // points around if so (code could be tightened up)
  4514. var soo = sourceAnchor.getOrientation(sourceEndpoint),
  4515. too = targetAnchor.getOrientation(targetEndpoint),
  4516. perpendicular = soo[0] != too[0] || soo[1] == too[1],
  4517. p = [],
  4518. ma = self.majorAnchor, mi = self.minorAnchor;
  4519. if (!perpendicular) {
  4520. if (soo[0] == 0) // X
  4521. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  4522. else p.push(point[0] - (ma * soo[0]));
  4523. if (soo[1] == 0) // Y
  4524. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  4525. else p.push(point[1] + (ma * too[1]));
  4526. }
  4527. else {
  4528. if (too[0] == 0) // X
  4529. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  4530. else p.push(point[0] + (ma * too[0]));
  4531. if (too[1] == 0) // Y
  4532. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  4533. else p.push(point[1] + (ma * soo[1]));
  4534. }
  4535. return p;
  4536. };
  4537. // this.isFlipX = function() { return
  4538. var _CP, _CP2, _sx, _tx, _ty, _sx, _sy, _canvasX, _canvasY, _w, _h;
  4539. this.compute = function(sourcePos, targetPos, sourceEndpoint, targetEndpoint, sourceAnchor, targetAnchor, lineWidth, minWidth)
  4540. {
  4541. lineWidth = lineWidth || 0;
  4542. _w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth;
  4543. _h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  4544. _canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2);
  4545. _canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  4546. _sx = sourcePos[0] < targetPos[0] ? _w - (lineWidth/2): (lineWidth/2);
  4547. _sy = sourcePos[1] < targetPos[1] ? _h - (lineWidth/2) : (lineWidth/2);
  4548. _tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : _w - (lineWidth/2);
  4549. _ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : _h - (lineWidth/2);
  4550. _CP = self._findControlPoint([_sx,_sy], sourcePos, targetPos, sourceEndpoint, targetEndpoint, sourceAnchor, targetAnchor);
  4551. _CP2 = self._findControlPoint([_tx,_ty], targetPos, sourcePos, sourceEndpoint, targetEndpoint, targetAnchor, sourceAnchor);
  4552. var minx1 = Math.min(_sx,_tx), minx2 = Math.min(_CP[0], _CP2[0]), minx = Math.min(minx1,minx2),
  4553. maxx1 = Math.max(_sx,_tx), maxx2 = Math.max(_CP[0], _CP2[0]), maxx = Math.max(maxx1,maxx2);
  4554. if (maxx > _w) _w = maxx;
  4555. if (minx < 0) {
  4556. _canvasX += minx; var ox = Math.abs(minx);
  4557. _w += ox; _CP[0] += ox; _sx += ox; _tx +=ox; _CP2[0] += ox;
  4558. }
  4559. var miny1 = Math.min(_sy,_ty), miny2 = Math.min(_CP[1], _CP2[1]), miny = Math.min(miny1,miny2),
  4560. maxy1 = Math.max(_sy,_ty), maxy2 = Math.max(_CP[1], _CP2[1]), maxy = Math.max(maxy1,maxy2);
  4561. if (maxy > _h) _h = maxy;
  4562. if (miny < 0) {
  4563. _canvasY += miny; var oy = Math.abs(miny);
  4564. _h += oy; _CP[1] += oy; _sy += oy; _ty +=oy; _CP2[1] += oy;
  4565. }
  4566. if (minWidth && _w < minWidth) {
  4567. var posAdjust = (minWidth - _w) / 2;
  4568. _w = minWidth;
  4569. _canvasX -= posAdjust; _sx = _sx + posAdjust ; _tx = _tx + posAdjust; _CP[0] = _CP[0] + posAdjust; _CP2[0] = _CP2[0] + posAdjust;
  4570. }
  4571. if (minWidth && _h < minWidth) {
  4572. var posAdjust = (minWidth - _h) / 2;
  4573. _h = minWidth;
  4574. _canvasY -= posAdjust; _sy = _sy + posAdjust ; _ty = _ty + posAdjust; _CP[1] = _CP[1] + posAdjust; _CP2[1] = _CP2[1] + posAdjust;
  4575. }
  4576. currentPoints = [_canvasX, _canvasY, _w, _h, _sx, _sy, _tx, _ty, _CP[0], _CP[1], _CP2[0], _CP2[1] ];
  4577. return currentPoints;
  4578. };
  4579. var _makeCurve = function() {
  4580. return [
  4581. { x:_sx, y:_sy },
  4582. { x:_CP[0], y:_CP[1] },
  4583. { x:_CP2[0], y:_CP2[1] },
  4584. { x:_tx, y:_ty }
  4585. ];
  4586. };
  4587. /**
  4588. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  4589. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  4590. */
  4591. this.pointOnPath = function(location) {
  4592. return jsBezier.pointOnCurve(_makeCurve(), location);
  4593. };
  4594. /**
  4595. * returns the gradient of the connector at the given point.
  4596. */
  4597. this.gradientAtPoint = function(location) {
  4598. return jsBezier.gradientAtPoint(_makeCurve(), location);
  4599. };
  4600. /**
  4601. * for Bezier curves this method is a little tricky, cos calculating path distance algebraically is notoriously difficult.
  4602. * this method is iterative, jumping forward .05% of the path at a time and summing the distance between this point and the previous
  4603. * one, until the sum reaches 'distance'. the method may turn out to be computationally expensive; we'll see.
  4604. * another drawback of this method is that if the connector gets quite long, .05% of the length of it is not necessarily smaller
  4605. * than the desired distance, in which case the loop returns immediately and the arrow is mis-shapen. so a better strategy might be to
  4606. * calculate the step as a function of distance/distance between endpoints.
  4607. */
  4608. this.pointAlongPathFrom = function(location, distance) {
  4609. return jsBezier.pointAlongCurveFrom(_makeCurve(), location, distance);
  4610. };
  4611. };
  4612. /**
  4613. * Class: Connectors.Flowchart
  4614. * Provides 'flowchart' connectors, consisting of vertical and horizontal line segments.
  4615. */
  4616. /**
  4617. * Function: Constructor
  4618. *
  4619. * Parameters:
  4620. * stub - minimum length for the stub at each end of the connector. defaults to 30 pixels.
  4621. */
  4622. jsPlumb.Connectors.Flowchart = function(params) {
  4623. this.type = "Flowchart";
  4624. params = params || {};
  4625. var self = this,
  4626. minStubLength = params.stub || params.minStubLength /* bwds compat. */ || 30,
  4627. segments = [],
  4628. totalLength = 0,
  4629. segmentProportions = [],
  4630. segmentProportionalLengths = [],
  4631. points = [],
  4632. swapX,
  4633. swapY,
  4634. /**
  4635. * recalculates the points at which the segments begin and end, proportional to the total length travelled
  4636. * by all the segments that constitute the connector. we use this to help with pointOnPath calculations.
  4637. */
  4638. updateSegmentProportions = function(startX, startY, endX, endY) {
  4639. var curLoc = 0;
  4640. for (var i = 0; i < segments.length; i++) {
  4641. segmentProportionalLengths[i] = segments[i][5] / totalLength;
  4642. segmentProportions[i] = [curLoc, (curLoc += (segments[i][5] / totalLength)) ];
  4643. }
  4644. },
  4645. appendSegmentsToPoints = function() {
  4646. points.push(segments.length);
  4647. for (var i = 0; i < segments.length; i++) {
  4648. points.push(segments[i][0]);
  4649. points.push(segments[i][1]);
  4650. }
  4651. },
  4652. /**
  4653. * helper method to add a segment.
  4654. */
  4655. addSegment = function(x, y, sx, sy, tx, ty) {
  4656. var lx = segments.length == 0 ? sx : segments[segments.length - 1][0],
  4657. ly = segments.length == 0 ? sy : segments[segments.length - 1][1],
  4658. m = x == lx ? Infinity : 0,
  4659. l = Math.abs(x == lx ? y - ly : x - lx);
  4660. segments.push([x, y, lx, ly, m, l]);
  4661. totalLength += l;
  4662. },
  4663. /**
  4664. * returns [segment, proportion of travel in segment, segment index] for the segment
  4665. * that contains the point which is 'location' distance along the entire path, where
  4666. * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
  4667. * are made up of a list of segments, each of which contributes some fraction to
  4668. * the total length.
  4669. */
  4670. findSegmentForLocation = function(location) {
  4671. var idx = segmentProportions.length - 1, inSegmentProportion = 0;
  4672. for (var i = 0; i < segmentProportions.length; i++) {
  4673. if (segmentProportions[i][1] >= location) {
  4674. idx = i;
  4675. inSegmentProportion = (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
  4676. break;
  4677. }
  4678. }
  4679. return { segment:segments[idx], proportion:inSegmentProportion, index:idx };
  4680. };
  4681. this.compute = function(sourcePos, targetPos, sourceEndpoint, targetEndpoint, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  4682. segments = [];
  4683. totalLength = 0;
  4684. segmentProportionalLengths = [];
  4685. swapX = targetPos[0] < sourcePos[0];
  4686. swapY = targetPos[1] < sourcePos[1];
  4687. var lw = lineWidth || 1,
  4688. offx = (lw / 2) + (minStubLength * 2),
  4689. offy = (lw / 2) + (minStubLength * 2),
  4690. so = sourceAnchor.orientation || sourceAnchor.getOrientation(sourceEndpoint),
  4691. to = targetAnchor.orientation || targetAnchor.getOrientation(targetEndpoint),
  4692. x = swapX ? targetPos[0] : sourcePos[0],
  4693. y = swapY ? targetPos[1] : sourcePos[1],
  4694. w = Math.abs(targetPos[0] - sourcePos[0]) + 2*offx,
  4695. h = Math.abs(targetPos[1] - sourcePos[1]) + 2*offy;
  4696. if (w < minWidth) {
  4697. offx += (minWidth - w) / 2;
  4698. w = minWidth;
  4699. }
  4700. if (h < minWidth) {
  4701. offy += (minWidth - h) / 2;
  4702. h = minWidth;
  4703. }
  4704. var sx = swapX ? w-offx : offx,
  4705. sy = swapY ? h-offy : offy,
  4706. tx = swapX ? offx : w-offx ,
  4707. ty = swapY ? offy : h-offy,
  4708. startStubX = sx + (so[0] * minStubLength),
  4709. startStubY = sy + (so[1] * minStubLength),
  4710. endStubX = tx + (to[0] * minStubLength),
  4711. endStubY = ty + (to[1] * minStubLength),
  4712. midx = startStubX + ((endStubX - startStubX) / 2),
  4713. midy = startStubY + ((endStubY - startStubY) / 2);
  4714. x -= offx; y -= offy;
  4715. points = [x, y, w, h, sx, sy, tx, ty];
  4716. var extraPoints = [];
  4717. addSegment(startStubX, startStubY, sx, sy, tx, ty);
  4718. if (so[0] == 0) {
  4719. var startStubIsBeforeEndStub = startStubY < endStubY;
  4720. // when start point's stub is less than endpoint's stub
  4721. if (startStubIsBeforeEndStub) {
  4722. addSegment(startStubX, midy, sx, sy, tx, ty);
  4723. addSegment(midx, midy, sx, sy, tx, ty);
  4724. addSegment(endStubX, midy, sx, sy, tx, ty);
  4725. } else {
  4726. // when start point's stub is greater than endpoint's stub
  4727. addSegment(midx, startStubY, sx, sy, tx, ty);
  4728. addSegment(midx, endStubY, sx, sy, tx, ty);
  4729. }
  4730. }
  4731. else {
  4732. var startStubIsBeforeEndStub = startStubX < endStubX;
  4733. // when start point's stub is less than endpoint's stub
  4734. if (startStubIsBeforeEndStub) {
  4735. addSegment(midx, startStubY, sx, sy, tx, ty);
  4736. addSegment(midx, midy, sx, sy, tx, ty);
  4737. addSegment(midx, endStubY, sx, sy, tx, ty);
  4738. } else {
  4739. // when start point's stub is greater than endpoint's stub
  4740. addSegment(startStubX, midy, sx, sy, tx, ty);
  4741. addSegment(endStubX, midy, sx, sy, tx, ty);
  4742. }
  4743. }
  4744. addSegment(endStubX, endStubY, sx, sy, tx, ty);
  4745. addSegment(tx, ty, sx, sy, tx, ty);
  4746. appendSegmentsToPoints();
  4747. updateSegmentProportions(sx, sy, tx, ty);
  4748. return points;
  4749. };
  4750. /**
  4751. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  4752. * 0 to 1 inclusive. for this connector we must first figure out which segment the given point lies in, and then compute the x,y position
  4753. * from our knowledge of the segment's start and end points.
  4754. */
  4755. this.pointOnPath = function(location) {
  4756. return self.pointAlongPathFrom(location, 0);
  4757. };
  4758. /**
  4759. * returns the gradient of the connector at the given point; the gradient will be either 0 or Infinity, depending on the direction of the
  4760. * segment the point falls in. segment gradients are calculated in the compute method.
  4761. */
  4762. this.gradientAtPoint = function(location) {
  4763. return segments[findSegmentForLocation(location)["index"]][4];
  4764. };
  4765. /**
  4766. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  4767. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels. when you consider this concept from the point of view
  4768. * of this connector, it starts to become clear that there's a problem with the overlay paint code: given that this connector makes several
  4769. * 90 degree turns, it's entirely possible that an arrow overlay could be forced to paint itself around a corner, which would look stupid. this is
  4770. * because jsPlumb uses this method (and pointOnPath) so determine the locations of the various points that go to make up an overlay. a better
  4771. * solution would probably be to just use pointOnPath along with gradientAtPoint, and draw the overlay so that its axis ran along
  4772. * a tangent to the connector. for straight line connectors this would obviously mean the overlay was painted directly on the connector, since a
  4773. * tangent to a straight line is the line itself, which is what we want; for this connector, and for beziers, the results would probably be better. an additional
  4774. * advantage is, of course, that there's less computation involved doing it that way.
  4775. */
  4776. this.pointAlongPathFrom = function(location, distance) {
  4777. var s = findSegmentForLocation(location), seg = s.segment, p = s.proportion, sl = segments[s.index][5], m = segments[s.index][4];
  4778. var e = {
  4779. x : m == Infinity ? seg[2] : seg[2] > seg[0] ? seg[0] + ((1 - p) * sl) - distance : seg[2] + (p * sl) + distance,
  4780. y : m == 0 ? seg[3] : seg[3] > seg[1] ? seg[1] + ((1 - p) * sl) - distance : seg[3] + (p * sl) + distance,
  4781. segmentInfo : s
  4782. };
  4783. return e;
  4784. };
  4785. };
  4786. // ********************************* END OF CONNECTOR TYPES *******************************************************************
  4787. // ********************************* ENDPOINT TYPES *******************************************************************
  4788. /**
  4789. * Class: Endpoints.Dot
  4790. * A round endpoint, with default radius 10 pixels.
  4791. */
  4792. /**
  4793. * Function: Constructor
  4794. *
  4795. * Parameters:
  4796. *
  4797. * radius - radius of the endpoint. defaults to 10 pixels.
  4798. */
  4799. jsPlumb.Endpoints.Dot = function(params) {
  4800. this.type = "Dot";
  4801. var self = this;
  4802. params = params || {};
  4803. this.radius = params.radius || 10;
  4804. this.defaultOffset = 0.5 * this.radius;
  4805. this.defaultInnerRadius = this.radius / 3;
  4806. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  4807. var r = endpointStyle.radius || self.radius,
  4808. x = anchorPoint[0] - r,
  4809. y = anchorPoint[1] - r;
  4810. return [ x, y, r * 2, r * 2, r ];
  4811. };
  4812. };
  4813. /**
  4814. * Class: Endpoints.Rectangle
  4815. * A Rectangular Endpoint, with default size 20x20.
  4816. */
  4817. /**
  4818. * Function: Constructor
  4819. *
  4820. * Parameters:
  4821. *
  4822. * width - width of the endpoint. defaults to 20 pixels.
  4823. * height - height of the endpoint. defaults to 20 pixels.
  4824. */
  4825. jsPlumb.Endpoints.Rectangle = function(params) {
  4826. this.type = "Rectangle";
  4827. var self = this;
  4828. params = params || {};
  4829. this.width = params.width || 20;
  4830. this.height = params.height || 20;
  4831. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  4832. var width = endpointStyle.width || self.width,
  4833. height = endpointStyle.height || self.height,
  4834. x = anchorPoint[0] - (width/2),
  4835. y = anchorPoint[1] - (height/2);
  4836. return [ x, y, width, height];
  4837. };
  4838. };
  4839. /**
  4840. * Class: Endpoints.Image
  4841. * Draws an image as the Endpoint.
  4842. */
  4843. /**
  4844. * Function: Constructor
  4845. *
  4846. * Parameters:
  4847. *
  4848. * src - location of the image to use.
  4849. */
  4850. jsPlumb.Endpoints.Image = function(params) {
  4851. this.type = "Image";
  4852. jsPlumb.DOMElementComponent.apply(this, arguments);
  4853. var self = this,
  4854. initialized = false,
  4855. widthToUse = params.width,
  4856. heightToUse = params.height,
  4857. _onload = null,
  4858. _endpoint = params.endpoint;
  4859. this.img = new Image();
  4860. self.ready = false;
  4861. this.img.onload = function() {
  4862. self.ready = true;
  4863. widthToUse = widthToUse || self.img.width;
  4864. heightToUse = heightToUse || self.img.height;
  4865. if (_onload) {
  4866. _onload(this);
  4867. }
  4868. };
  4869. _endpoint.setImage = function(img, onload) {
  4870. var s = img.constructor == String ? img : img.src;
  4871. _onload = onload;
  4872. self.img.src = img;
  4873. };
  4874. _endpoint.setImage(params.src || params.url, params.onload);
  4875. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  4876. self.anchorPoint = anchorPoint;
  4877. if (self.ready) return [anchorPoint[0] - widthToUse / 2, anchorPoint[1] - heightToUse / 2,
  4878. widthToUse, heightToUse];
  4879. else return [0,0,0,0];
  4880. };
  4881. self.canvas = document.createElement("img"), initialized = false;
  4882. self.canvas.style["margin"] = 0;
  4883. self.canvas.style["padding"] = 0;
  4884. self.canvas.style["outline"] = 0;
  4885. self.canvas.style["position"] = "absolute";
  4886. var clazz = params.cssClass ? " " + params.cssClass : "";
  4887. self.canvas.className = jsPlumb.endpointClass + clazz;
  4888. if (widthToUse) self.canvas.setAttribute("width", widthToUse);
  4889. if (heightToUse) self.canvas.setAttribute("height", heightToUse);
  4890. jsPlumb.appendElement(self.canvas, params.parent);
  4891. self.attachListeners(self.canvas, self);
  4892. var actuallyPaint = function(d, style, anchor) {
  4893. if (!initialized) {
  4894. self.canvas.setAttribute("src", self.img.src);
  4895. initialized = true;
  4896. }
  4897. var x = self.anchorPoint[0] - (widthToUse / 2),
  4898. y = self.anchorPoint[1] - (heightToUse / 2);
  4899. jsPlumb.sizeCanvas(self.canvas, x, y, widthToUse, heightToUse);
  4900. };
  4901. this.paint = function(d, style, anchor) {
  4902. if (self.ready) {
  4903. actuallyPaint(d, style, anchor);
  4904. }
  4905. else {
  4906. window.setTimeout(function() {
  4907. self.paint(d, style, anchor);
  4908. }, 200);
  4909. }
  4910. };
  4911. };
  4912. /**
  4913. * Class: Endpoints.Blank
  4914. * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints.
  4915. */
  4916. jsPlumb.Endpoints.Blank = function(params) {
  4917. var self = this;
  4918. this.type = "Blank";
  4919. jsPlumb.DOMElementComponent.apply(this, arguments);
  4920. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  4921. return [anchorPoint[0], anchorPoint[1],10,0];
  4922. };
  4923. self.canvas = document.createElement("div");
  4924. self.canvas.style.display = "block";
  4925. self.canvas.style.width = "1px";
  4926. self.canvas.style.height = "1px";
  4927. self.canvas.style.background = "transparent";
  4928. self.canvas.style.position = "absolute";
  4929. self.canvas.className = self._jsPlumb.endpointClass;
  4930. jsPlumb.appendElement(self.canvas, params.parent);
  4931. this.paint = function(d, style, anchor) {
  4932. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  4933. };
  4934. };
  4935. /**
  4936. * Class: Endpoints.Triangle
  4937. * A triangular Endpoint.
  4938. */
  4939. /**
  4940. * Function: Constructor
  4941. *
  4942. * Parameters:
  4943. *
  4944. * width - width of the triangle's base. defaults to 55 pixels.
  4945. * height - height of the triangle from base to apex. defaults to 55 pixels.
  4946. */
  4947. jsPlumb.Endpoints.Triangle = function(params) {
  4948. this.type = "Triangle";
  4949. params = params || { };
  4950. params.width = params.width || 55;
  4951. params.height = params.height || 55;
  4952. this.width = params.width;
  4953. this.height = params.height;
  4954. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  4955. var width = endpointStyle.width || self.width,
  4956. height = endpointStyle.height || self.height,
  4957. x = anchorPoint[0] - (width/2),
  4958. y = anchorPoint[1] - (height/2);
  4959. return [ x, y, width, height ];
  4960. };
  4961. };
  4962. // ********************************* END OF ENDPOINT TYPES *******************************************************************
  4963. // ********************************* OVERLAY DEFINITIONS ***********************************************************************
  4964. var AbstractOverlay = function(params) {
  4965. var visible = true, self = this;
  4966. this.isAppendedAtTopLevel = true;
  4967. this.connection = params.connection;
  4968. this.loc = params.location == null ? 0.5 : params.location;
  4969. this.setVisible = function(val) {
  4970. visible = val;
  4971. self.connection.repaint();
  4972. };
  4973. this.isVisible = function() { return visible; };
  4974. this.hide = function() { self.setVisible(false); };
  4975. this.show = function() { self.setVisible(true); };
  4976. this.incrementLocation = function(amount) {
  4977. self.loc += amount;
  4978. self.connection.repaint();
  4979. };
  4980. this.setLocation = function(l) {
  4981. self.loc = l;
  4982. self.connection.repaint();
  4983. };
  4984. this.getLocation = function() {
  4985. return self.loc;
  4986. };
  4987. };
  4988. /**
  4989. * Class: Overlays.Arrow
  4990. *
  4991. * An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length
  4992. * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
  4993. * of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line
  4994. * across the tail.
  4995. */
  4996. /**
  4997. * Function: Constructor
  4998. *
  4999. * Parameters:
  5000. *
  5001. * length - distance in pixels from head to tail baseline. default 20.
  5002. * width - width in pixels of the tail baseline. default 20.
  5003. * fillStyle - style to use when filling the arrow. defaults to "black".
  5004. * strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
  5005. * lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null.
  5006. * foldback - distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
  5007. * location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
  5008. * direction - indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
  5009. */
  5010. jsPlumb.Overlays.Arrow = function(params) {
  5011. this.type = "Arrow";
  5012. AbstractOverlay.apply(this, arguments);
  5013. this.isAppendedAtTopLevel = false;
  5014. params = params || {};
  5015. var self = this;
  5016. this.length = params.length || 20;
  5017. this.width = params.width || 20;
  5018. this.id = params.id;
  5019. var direction = (params.direction || 1) < 0 ? -1 : 1,
  5020. paintStyle = params.paintStyle || { lineWidth:1 },
  5021. // how far along the arrow the lines folding back in come to. default is 62.3%.
  5022. foldback = params.foldback || 0.623;
  5023. this.computeMaxSize = function() { return self.width * 1.5; };
  5024. this.cleanup = function() { }; // nothing to clean up for Arrows
  5025. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  5026. var hxy, mid, txy, tail, cxy;
  5027. if (self.loc == 1) {
  5028. hxy = connector.pointOnPath(self.loc);
  5029. mid = connector.pointAlongPathFrom(self.loc, -1);
  5030. txy = jsPlumb.util.pointOnLine(hxy, mid, self.length);
  5031. }
  5032. else if (self.loc == 0) {
  5033. txy = connector.pointOnPath(self.loc);
  5034. mid = connector.pointAlongPathFrom(self.loc, 1);
  5035. hxy = jsPlumb.util.pointOnLine(txy, mid, self.length);
  5036. }
  5037. else {
  5038. hxy = connector.pointAlongPathFrom(self.loc, direction * self.length / 2),
  5039. mid = connector.pointOnPath(self.loc),
  5040. txy = jsPlumb.util.pointOnLine(hxy, mid, self.length);
  5041. }
  5042. tail = jsPlumb.util.perpendicularLineTo(hxy, txy, self.width);
  5043. cxy = jsPlumb.util.pointOnLine(hxy, txy, foldback * self.length);
  5044. var minx = Math.min(hxy.x, tail[0].x, tail[1].x),
  5045. maxx = Math.max(hxy.x, tail[0].x, tail[1].x),
  5046. miny = Math.min(hxy.y, tail[0].y, tail[1].y),
  5047. maxy = Math.max(hxy.y, tail[0].y, tail[1].y);
  5048. var d = { hxy:hxy, tail:tail, cxy:cxy },
  5049. strokeStyle = paintStyle.strokeStyle || currentConnectionPaintStyle.strokeStyle,
  5050. fillStyle = paintStyle.fillStyle || currentConnectionPaintStyle.strokeStyle,
  5051. lineWidth = paintStyle.lineWidth || currentConnectionPaintStyle.lineWidth;
  5052. self.paint(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions);
  5053. return [ minx, maxx, miny, maxy];
  5054. };
  5055. };
  5056. /**
  5057. * Class: Overlays.PlainArrow
  5058. *
  5059. * A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some
  5060. * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
  5061. * a 'call' to Arrow with foldback set appropriately.
  5062. */
  5063. /**
  5064. * Function: Constructor
  5065. * See <Overlays.Arrow> for allowed parameters for this overlay.
  5066. */
  5067. jsPlumb.Overlays.PlainArrow = function(params) {
  5068. params = params || {};
  5069. var p = jsPlumb.extend(params, {foldback:1});
  5070. jsPlumb.Overlays.Arrow.call(this, p);
  5071. this.type = "PlainArrow";
  5072. };
  5073. /**
  5074. * Class: Overlays.Diamond
  5075. *
  5076. * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
  5077. * happens that in this case, that point is greater than the length of the the arrow.
  5078. *
  5079. * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
  5080. * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
  5081. * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
  5082. * would be -l/4 in this case - move along one quarter of the total length.
  5083. */
  5084. /**
  5085. * Function: Constructor
  5086. * See <Overlays.Arrow> for allowed parameters for this overlay.
  5087. */
  5088. jsPlumb.Overlays.Diamond = function(params) {
  5089. params = params || {};
  5090. var l = params.length || 40,
  5091. p = jsPlumb.extend(params, {length:l/2, foldback:2});
  5092. jsPlumb.Overlays.Arrow.call(this, p);
  5093. this.type = "Diamond";
  5094. };
  5095. /**
  5096. * Class: Overlays.Label
  5097. * A Label overlay. For all different renderer types (SVG/Canvas/VML), jsPlumb draws a Label overlay as a styled DIV. Version 1.3.0 of jsPlumb
  5098. * introduced the ability to set css classes on the label; this is now the preferred way for you to style a label. The 'labelStyle' parameter
  5099. * is still supported in 1.3.0 but its usage is deprecated. Under the hood, jsPlumb just turns that object into a bunch of CSS directive that it
  5100. * puts on the Label's 'style' attribute, so the end result is the same.
  5101. */
  5102. /**
  5103. * Function: Constructor
  5104. *
  5105. * Parameters:
  5106. * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
  5107. * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
  5108. * label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your
  5109. * label function returns null. empty strings _will_ be painted.
  5110. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  5111. *
  5112. */
  5113. jsPlumb.Overlays.Label = function(params) {
  5114. this.type = "Label";
  5115. jsPlumb.DOMElementComponent.apply(this, arguments);
  5116. AbstractOverlay.apply(this, arguments);
  5117. this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle;
  5118. this.id = params.id;
  5119. this.cachedDimensions = null; // setting on 'this' rather than using closures uses a lot less memory. just don't monkey with it!
  5120. var label = params.label || "",
  5121. self = this,
  5122. initialised = false,
  5123. div = document.createElement("div"),
  5124. labelText = null;
  5125. div.style["position"] = "absolute";
  5126. var clazz = params["_jsPlumb"].overlayClass + " " +
  5127. (self.labelStyle.cssClass ? self.labelStyle.cssClass :
  5128. params.cssClass ? params.cssClass : "");
  5129. div.className = clazz;
  5130. jsPlumb.appendElement(div, params.connection.parent);
  5131. jsPlumb.getId(div);
  5132. self.attachListeners(div, self);
  5133. self.canvas = div;
  5134. //override setVisible
  5135. var osv = self.setVisible;
  5136. self.setVisible = function(state) {
  5137. osv(state); // call superclass
  5138. div.style.display = state ? "block" : "none";
  5139. };
  5140. this.getElement = function() {
  5141. return div;
  5142. };
  5143. this.cleanup = function() {
  5144. if (div != null) jsPlumb.CurrentLibrary.removeElement(div);
  5145. };
  5146. /*
  5147. * Function: setLabel
  5148. * sets the label's, um, label. you would think i'd call this function
  5149. * 'setText', but you can pass either a Function or a String to this, so
  5150. * it makes more sense as 'setLabel'.
  5151. */
  5152. this.setLabel = function(l) {
  5153. label = l;
  5154. labelText = null;
  5155. self.connection.repaint();
  5156. };
  5157. this.getLabel = function() {
  5158. return label;
  5159. };
  5160. this.paint = function(connector, d, connectorDimensions) {
  5161. if (!initialised) {
  5162. connector.appendDisplayElement(div);
  5163. self.attachListeners(div, connector);
  5164. initialised = true;
  5165. }
  5166. div.style.left = (connectorDimensions[0] + d.minx) + "px";
  5167. div.style.top = (connectorDimensions[1] + d.miny) + "px";
  5168. };
  5169. this.getTextDimensions = function(connector) {
  5170. if (typeof label == "function") {
  5171. var lt = label(self);
  5172. div.innerHTML = lt.replace(/\r\n/g, "<br/>");
  5173. }
  5174. else {
  5175. if (labelText == null) {
  5176. labelText = label;
  5177. div.innerHTML = labelText.replace(/\r\n/g, "<br/>");
  5178. }
  5179. }
  5180. var de = jsPlumb.CurrentLibrary.getElementObject(div),
  5181. s = jsPlumb.CurrentLibrary.getSize(de);
  5182. return {width:s[0], height:s[1]};
  5183. };
  5184. this.computeMaxSize = function(connector) {
  5185. var td = self.getTextDimensions(connector);
  5186. return td.width ? Math.max(td.width, td.height) * 1.5 : 0;
  5187. };
  5188. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  5189. var td = self.getTextDimensions(connector);
  5190. if (td.width != null) {
  5191. var cxy = connector.pointOnPath(self.loc),
  5192. minx = cxy.x - (td.width / 2),
  5193. miny = cxy.y - (td.height / 2);
  5194. self.paint(connector, {
  5195. minx:minx,
  5196. miny:miny,
  5197. td:td,
  5198. cxy:cxy
  5199. }, connectorDimensions);
  5200. return [minx, minx+td.width, miny, miny+td.height];
  5201. }
  5202. else return [0,0,0,0];
  5203. };
  5204. this.reattachListeners = function() {
  5205. if (div) self.reattachListenersForElement(div, self);
  5206. };
  5207. };
  5208. // this is really just a test overlay, so its undocumented and doesnt take any parameters. but i was loth to delete it.
  5209. jsPlumb.Overlays.GuideLines = function() {
  5210. var self = this;
  5211. self.length = 50;
  5212. self.lineWidth = 5;
  5213. this.type = "GuideLines";
  5214. AbstractOverlay.apply(this, arguments);
  5215. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  5216. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  5217. var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
  5218. mid = connector.pointOnPath(self.loc),
  5219. tail = jsPlumb.util.pointOnLine(head, mid, self.length),
  5220. tailLine = jsPlumb.util.perpendicularLineTo(head, tail, 40),
  5221. headLine = jsPlumb.util.perpendicularLineTo(tail, head, 20);
  5222. self.paint(connector, [head, tail, tailLine, headLine], self.lineWidth, "red", null, connectorDimensions);
  5223. return [Math.min(head.x, tail.x), Math.min(head.y, tail.y), Math.max(head.x, tail.x), Math.max(head.y,tail.y)];
  5224. };
  5225. this.computeMaxSize = function() { return 50; };
  5226. this.cleanup = function() { }; // nothing to clean up for GuideLines
  5227. };
  5228. // ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
  5229. // ********************************* OVERLAY CANVAS RENDERERS***********************************************************************
  5230. // ********************************* END OF OVERLAY CANVAS RENDERERS ***********************************************************************
  5231. })();/*
  5232. * jsPlumb
  5233. *
  5234. * Title:jsPlumb 1.3.5
  5235. *
  5236. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  5237. * elements, or VML.
  5238. *
  5239. * This file contains the state machine connectors.
  5240. *
  5241. * Thanks to Brainstorm Mobile Solutions for supporting the development of these.
  5242. *
  5243. * Copyright (c) 2010 - 2012 Simon Porritt (simon.porritt@gmail.com)
  5244. *
  5245. * http://jsplumb.org
  5246. * http://github.com/sporritt/jsplumb
  5247. * http://code.google.com/p/jsplumb
  5248. *
  5249. * Dual licensed under the MIT and GPL2 licenses.
  5250. */
  5251. ;(function() {
  5252. var Line = function(x1, y1, x2, y2) {
  5253. this.m = (y2 - y1) / (x2 - x1);
  5254. this.b = -1 * ((this.m * x1) - y1);
  5255. this.rectIntersect = function(x,y,w,h) {
  5256. var results = [];
  5257. // try top face
  5258. // the equation of the top face is y = (0 * x) + b; y = b.
  5259. var xInt = (y - this.b) / this.m;
  5260. // test that the X value is in the line's range.
  5261. if (xInt >= x && xInt <= (x + w)) results.push([ xInt, (this.m * xInt) + this.b ]);
  5262. // try right face
  5263. var yInt = (this.m * (x + w)) + this.b;
  5264. if (yInt >= y && yInt <= (y + h)) results.push([ (yInt - this.b) / this.m, yInt ]);
  5265. // bottom face
  5266. var xInt = ((y + h) - this.b) / this.m;
  5267. // test that the X value is in the line's range.
  5268. if (xInt >= x && xInt <= (x + w)) results.push([ xInt, (this.m * xInt) + this.b ]);
  5269. // try left face
  5270. var yInt = (this.m * x) + this.b;
  5271. if (yInt >= y && yInt <= (y + h)) results.push([ (yInt - this.b) / this.m, yInt ]);
  5272. if (results.length == 2) {
  5273. var midx = (results[0][0] + results[1][0]) / 2, midy = (results[0][1] + results[1][1]) / 2;
  5274. results.push([ midx,midy ]);
  5275. // now calculate the segment inside the rectangle where the midpoint lies.
  5276. var xseg = midx <= x + (w / 2) ? -1 : 1,
  5277. yseg = midy <= y + (h / 2) ? -1 : 1;
  5278. results.push([xseg, yseg]);
  5279. return results;
  5280. }
  5281. return null;
  5282. };
  5283. },
  5284. _segment = function(x1, y1, x2, y2) {
  5285. if (x1 <= x2 && y2 <= y1) return 1;
  5286. else if (x1 <= x2 && y1 <= y2) return 2;
  5287. else if (x2 <= x1 && y2 >= y1) return 3;
  5288. return 4;
  5289. },
  5290. // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the
  5291. // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they
  5292. // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the
  5293. // center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and
  5294. // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element
  5295. // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left.
  5296. //
  5297. // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are:
  5298. //
  5299. // 0 - absolute x
  5300. // 1 - absolute y
  5301. // 2 - proportional x in element (0 is left edge, 1 is right edge)
  5302. // 3 - proportional y in element (0 is top edge, 1 is bottom edge)
  5303. //
  5304. _findControlPoint = function(midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) {
  5305. // TODO (maybe)
  5306. // - if anchor pos is 0.5, make the control point take into account the relative position of the elements.
  5307. if (distance <= proximityLimit) return [midx, midy];
  5308. if (segment == 1) {
  5309. if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  5310. else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  5311. else return [ midx + (-1 * dx) , midy + (-1 * dy) ];
  5312. }
  5313. else if (segment == 2) {
  5314. if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  5315. else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  5316. else return [ midx + (1 * dx) , midy + (-1 * dy) ];
  5317. }
  5318. else if (segment == 3) {
  5319. if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  5320. else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  5321. else return [ midx + (-1 * dx) , midy + (-1 * dy) ];
  5322. }
  5323. else if (segment == 4) {
  5324. if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  5325. else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  5326. else return [ midx + (1 * dx) , midy + (-1 * dy) ];
  5327. }
  5328. };
  5329. /*
  5330. Function: StateMachine constructor
  5331. Allowed parameters:
  5332. curviness - measure of how "curvy" the connectors will be. this is translated as the distance that the
  5333. Bezier curve's control point is from the midpoint of the straight line connecting the two
  5334. endpoints, and does not mean that the connector is this wide. The Bezier curve never reaches
  5335. its control points; they act as gravitational masses. defaults to 10.
  5336. margin - distance from element to start and end connectors, in pixels. defaults to 5.
  5337. proximityLimit - sets the distance beneath which the elements are consider too close together to bother with fancy
  5338. curves. by default this is 80 pixels.
  5339. loopbackRadius - the radius of a loopback connector. optional; defaults to 25.
  5340. */
  5341. jsPlumb.Connectors.StateMachine = function(params) {
  5342. var self = this,
  5343. currentPoints = null,
  5344. _sx, _sy, _tx, _ty, _controlPoint = [],
  5345. curviness = params.curviness || 10,
  5346. margin = params.margin || 5,
  5347. proximityLimit = params.proximityLimit || 80,
  5348. clockwise = params.orientation && params.orientation == "clockwise",
  5349. loopbackRadius = params.loopbackRadius || 25,
  5350. isLoopback = false;
  5351. this.type = "StateMachine";
  5352. params = params || {};
  5353. this.compute = function(sourcePos, targetPos, sourceEndpoint, targetEndpoint, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  5354. var w = Math.abs(sourcePos[0] - targetPos[0]),
  5355. h = Math.abs(sourcePos[1] - targetPos[1]),
  5356. // these are padding to ensure the whole connector line appears
  5357. xo = 0.45 * w, yo = 0.45 * h;
  5358. // these are padding to ensure the whole connector line appears
  5359. w *= 1.9; h *= 1.9;
  5360. //ensure at least one pixel width
  5361. lineWidth = lineWidth || 1;
  5362. var x = Math.min(sourcePos[0], targetPos[0]) - xo,
  5363. y = Math.min(sourcePos[1], targetPos[1]) - yo;
  5364. if (sourceEndpoint.elementId != targetEndpoint.elementId) {
  5365. isLoopback = false;
  5366. _sx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  5367. _sy = sourcePos[1] < targetPos[1] ? yo:h-yo;
  5368. _tx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  5369. _ty = sourcePos[1] < targetPos[1] ? h-yo : yo;
  5370. // now adjust for the margin
  5371. if (sourcePos[2] == 0) _sx -= margin;
  5372. if (sourcePos[2] == 1) _sx += margin;
  5373. if (sourcePos[3] == 0) _sy -= margin;
  5374. if (sourcePos[3] == 1) _sy += margin;
  5375. if (targetPos[2] == 0) _tx -= margin;
  5376. if (targetPos[2] == 1) _tx += margin;
  5377. if (targetPos[3] == 0) _ty -= margin;
  5378. if (targetPos[3] == 1) _ty += margin;
  5379. //
  5380. // these connectors are quadratic bezier curves, having a single control point. if both anchors
  5381. // are located at 0.5 on their respective faces, the control point is set to the midpoint and you
  5382. // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since
  5383. // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned
  5384. // at 'curviness' pixels away along the normal to the straight line connecting the two anchors.
  5385. //
  5386. // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes
  5387. // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node,
  5388. // for example, we might increase the distance the control point is away from the midpoint in a bid to
  5389. // steer it around that node. this will work within limits, but i think those limits would also be the likely
  5390. // limits for, once again, aesthetic good sense in the layout of a chart using these connectors.
  5391. //
  5392. // the second possible change is actually two possible changes: firstly, it is possible we should gradually
  5393. // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some
  5394. // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors
  5395. // with respect to how far their anchor is from the center of its respective face. this could either look cool,
  5396. // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time.
  5397. //
  5398. var _midx = (_sx + _tx) / 2, _midy = (_sy + _ty) / 2,
  5399. m2 = (-1 * _midx) / _midy, theta2 = Math.atan(m2),
  5400. dy = (m2 == Infinity || m2 == -Infinity) ? 0 : Math.abs(curviness / 2 * Math.sin(theta2)),
  5401. dx = (m2 == Infinity || m2 == -Infinity) ? 0 : Math.abs(curviness / 2 * Math.cos(theta2)),
  5402. segment = _segment(_sx, _sy, _tx, _ty),
  5403. distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2));
  5404. // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it
  5405. // will work by extending the control point to force the curve to be, um, curvier.
  5406. _controlPoint = _findControlPoint(_midx,
  5407. _midy,
  5408. segment,
  5409. sourcePos,
  5410. targetPos,
  5411. curviness, curviness,
  5412. distance,
  5413. proximityLimit);
  5414. var requiredWidth = Math.max(Math.abs(_controlPoint[0] - _sx) * 3, Math.abs(_controlPoint[0] - _tx) * 3, Math.abs(_tx-_sx), 2 * lineWidth, minWidth),
  5415. requiredHeight = Math.max(Math.abs(_controlPoint[1] - _sy) * 3, Math.abs(_controlPoint[1] - _ty) * 3, Math.abs(_ty-_sy), 2 * lineWidth, minWidth);
  5416. if (w < requiredWidth) {
  5417. var dw = requiredWidth - w;
  5418. x -= (dw / 2);
  5419. _sx += (dw / 2);
  5420. _tx += (dw / 2);
  5421. w = requiredWidth;
  5422. _controlPoint[0] += (dw / 2);
  5423. }
  5424. if (h < requiredHeight) {
  5425. var dh = requiredHeight - h;
  5426. y -= (dh / 2);
  5427. _sy += (dh / 2);
  5428. _ty += (dh / 2);
  5429. h = requiredHeight;
  5430. _controlPoint[1] += (dh / 2);
  5431. }
  5432. currentPoints = [ x, y, w, h, _sx, _sy, _tx, _ty, _controlPoint[0], _controlPoint[1] ];
  5433. }
  5434. else {
  5435. isLoopback = true;
  5436. // a loopback connector. draw an arc from one anchor to the other.
  5437. // i guess we'll do this the same way as the others. just the control point will be a fair distance away.
  5438. var x1 = sourcePos[0], x2 = sourcePos[0], y1 = sourcePos[1] - margin, y2 = sourcePos[1] - margin,
  5439. cx = x1, cy = y1 - loopbackRadius;
  5440. // canvas sizing stuff, to ensure the whole painted area is visible.
  5441. w = ((2 * lineWidth) + (4 * loopbackRadius)), h = ((2 * lineWidth) + (4 * loopbackRadius));
  5442. x = cx - loopbackRadius - lineWidth - loopbackRadius, y = cy - loopbackRadius - lineWidth - loopbackRadius;
  5443. currentPoints = [ x, y, w, h, cx-x, cy-y, loopbackRadius, clockwise, x1-x, y1-y, x2-x, y2-y];
  5444. }
  5445. return currentPoints;
  5446. };
  5447. var _makeCurve = function() {
  5448. return [
  5449. { x:_tx, y:_ty },
  5450. { x:_controlPoint[0], y:_controlPoint[1] },
  5451. { x:_controlPoint[0] + 1, y:_controlPoint[1] + 1},
  5452. { x:_sx, y:_sy }
  5453. ];
  5454. };
  5455. /**
  5456. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  5457. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  5458. */
  5459. this.pointOnPath = function(location) {
  5460. if (isLoopback) {
  5461. if (location > 0 && location < 1) location = 1- location;
  5462. // current points are [ x, y, width, height, center x, center y, radius, clockwise, startx, starty, endx, endy ]
  5463. // so the path length is the circumference of the circle
  5464. //var len = 2 * Math.PI * currentPoints[6],
  5465. // map 'location' to an angle. 0 is PI/2 when the connector is on the top face; if we
  5466. // support other faces it will have to be calculated for each one. 1 is also PI/2.
  5467. // 0.5 is -PI/2.
  5468. var startAngle = (location * 2 * Math.PI) + (Math.PI / 2),
  5469. startX = currentPoints[4] + (currentPoints[6] * Math.cos(startAngle)),
  5470. startY = currentPoints[5] + (currentPoints[6] * Math.sin(startAngle));
  5471. return {x:startX, y:startY};
  5472. }
  5473. else return jsBezier.pointOnCurve(_makeCurve(), location);
  5474. };
  5475. /**
  5476. * returns the gradient of the connector at the given point.
  5477. */
  5478. this.gradientAtPoint = function(location) {
  5479. if (isLoopback)
  5480. return Math.atan(location * 2 * Math.PI);
  5481. else
  5482. return jsBezier.gradientAtPoint(_makeCurve(), location);
  5483. };
  5484. /**
  5485. * for Bezier curves this method is a little tricky, cos calculating path distance algebraically is notoriously difficult.
  5486. * this method is iterative, jumping forward .05% of the path at a time and summing the distance between this point and the previous
  5487. * one, until the sum reaches 'distance'. the method may turn out to be computationally expensive; we'll see.
  5488. * another drawback of this method is that if the connector gets quite long, .05% of the length of it is not necessarily smaller
  5489. * than the desired distance, in which case the loop returns immediately and the arrow is mis-shapen. so a better strategy might be to
  5490. * calculate the step as a function of distance/distance between endpoints.
  5491. */
  5492. this.pointAlongPathFrom = function(location, distance) {
  5493. if (isLoopback) {
  5494. if (location > 0 && location < 1) location = 1- location;
  5495. var circumference = 2 * Math.PI * currentPoints[6],
  5496. arcSpan = distance / circumference * 2 * Math.PI,
  5497. startAngle = (location * 2 * Math.PI) - arcSpan + (Math.PI / 2),
  5498. startX = currentPoints[4] + (currentPoints[6] * Math.cos(startAngle)),
  5499. startY = currentPoints[5] + (currentPoints[6] * Math.sin(startAngle));
  5500. return {x:startX, y:startY};
  5501. }
  5502. return jsBezier.pointAlongCurveFrom(_makeCurve(), location, distance);
  5503. };
  5504. };
  5505. /*
  5506. * Canvas state machine renderer.
  5507. */
  5508. jsPlumb.Connectors.canvas.StateMachine = function(params) {
  5509. params = params || {};
  5510. var self = this, drawGuideline = params.drawGuideline || true, avoidSelector = params.avoidSelector;
  5511. jsPlumb.Connectors.StateMachine.apply(this, arguments);
  5512. jsPlumb.CanvasConnector.apply(this, arguments);
  5513. this._paint = function(dimensions) {
  5514. if (dimensions.length == 10) {
  5515. self.ctx.beginPath();
  5516. self.ctx.moveTo(dimensions[4], dimensions[5]);
  5517. self.ctx.quadraticCurveTo(dimensions[8], dimensions[9], dimensions[6], dimensions[7]);
  5518. self.ctx.stroke();
  5519. /*/ draw the guideline
  5520. if (drawGuideline) {
  5521. self.ctx.save();
  5522. self.ctx.beginPath();
  5523. self.ctx.strokeStyle = "silver";
  5524. self.ctx.lineWidth = 1;
  5525. self.ctx.moveTo(dimensions[4], dimensions[5]);
  5526. self.ctx.lineTo(dimensions[6], dimensions[7]);
  5527. self.ctx.stroke();
  5528. self.ctx.restore();
  5529. }
  5530. //*/
  5531. }
  5532. else {
  5533. // a loopback connector
  5534. self.ctx.save();
  5535. self.ctx.beginPath();
  5536. var startAngle = 0, // Starting point on circle
  5537. endAngle = 2 * Math.PI, // End point on circle
  5538. clockwise = dimensions[7]; // clockwise or anticlockwise
  5539. self.ctx.arc(dimensions[4],dimensions[5],dimensions[6],0, endAngle, clockwise);
  5540. self.ctx.stroke();
  5541. self.ctx.closePath();
  5542. self.ctx.restore();
  5543. }
  5544. };
  5545. this.createGradient = function(dim, ctx) {
  5546. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  5547. };
  5548. };
  5549. /*
  5550. * SVG State Machine renderer
  5551. */
  5552. jsPlumb.Connectors.svg.StateMachine = function() {
  5553. var self = this;
  5554. jsPlumb.Connectors.StateMachine.apply(this, arguments);
  5555. jsPlumb.SvgConnector.apply(this, arguments);
  5556. this.getPath = function(d) {
  5557. if (d.length == 10)
  5558. return "M " + d[4] + " " + d[5] + " C " + d[8] + " " + d[9] + " " + d[8] + " " + d[9] + " " + d[6] + " " + d[7];
  5559. else {
  5560. // loopback
  5561. return "M" + (d[8] + 4) + " " + d[9] + " A " + d[6] + " " + d[6] + " 0 1,0 " + (d[8]-4) + " " + d[9];
  5562. }
  5563. };
  5564. };
  5565. /*
  5566. * VML state machine renderer
  5567. */
  5568. jsPlumb.Connectors.vml.StateMachine = function() {
  5569. jsPlumb.Connectors.StateMachine.apply(this, arguments);
  5570. jsPlumb.VmlConnector.apply(this, arguments);
  5571. var _conv = jsPlumb.vml.convertValue;
  5572. this.getPath = function(d) {
  5573. if (d.length == 10) {
  5574. return "m" + _conv(d[4]) + "," + _conv(d[5]) +
  5575. " c" + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[6]) + "," + _conv(d[7]) + " e";
  5576. }
  5577. else {
  5578. // loopback
  5579. var left = _conv(d[8] - d[6]),
  5580. top = _conv(d[9] - (2 * d[6])),
  5581. right = left + _conv(2 * d[6]),
  5582. bottom = top + _conv(2 * d[6]),
  5583. posString = left + "," + top + "," + right + "," + bottom;
  5584. var o = "ar " + posString + "," + _conv(d[8]) + ","
  5585. + _conv(d[9]) + "," + _conv(d[8]) + "," + _conv(d[9]) + " e";
  5586. return o;
  5587. }
  5588. };
  5589. };
  5590. })();
  5591. /*
  5592. // now for a rudimentary avoidance scheme. TODO: how to set this in a cross-library way?
  5593. // if (avoidSelector) {
  5594. // var testLine = new Line(sourcePos[0] + _sx,sourcePos[1] + _sy,sourcePos[0] + _tx,sourcePos[1] + _ty);
  5595. // var sel = jsPlumb.getSelector(avoidSelector);
  5596. // for (var i = 0; i < sel.length; i++) {
  5597. // var id = jsPlumb.getId(sel[i]);
  5598. // if (id != sourceEndpoint.elementId && id != targetEndpoint.elementId) {
  5599. // o = jsPlumb.getOffset(id), s = jsPlumb.getSize(id);
  5600. //
  5601. // if (o && s) {
  5602. // var collision = testLine.rectIntersect(o.left,o.top,s[0],s[1]);
  5603. // if (collision) {
  5604. // set the control point to be a certain distance from the midpoint of the two points that
  5605. // the line crosses on the rectangle.
  5606. // TODO where will this 75 number come from?
  5607. // _controlX = collision[2][0] + (75 * collision[3][0]);
  5608. // / _controlY = collision[2][1] + (75 * collision[3][1]);
  5609. // }
  5610. // }
  5611. // }
  5612. // }
  5613. //}
  5614. *//*
  5615. * jsPlumb
  5616. *
  5617. * Title:jsPlumb 1.3.5
  5618. *
  5619. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  5620. * elements, or VML.
  5621. *
  5622. * This file contains the VML renderers.
  5623. *
  5624. * Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org)
  5625. *
  5626. * http://jsplumb.org
  5627. * http://github.com/sporritt/jsplumb
  5628. * http://code.google.com/p/jsplumb
  5629. *
  5630. * Dual licensed under the MIT and GPL2 licenses.
  5631. */
  5632. ;(function() {
  5633. // http://ajaxian.com/archives/the-vml-changes-in-ie-8
  5634. // http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/
  5635. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  5636. var vmlAttributeMap = {
  5637. "stroke-linejoin":"joinstyle",
  5638. "joinstyle":"joinstyle",
  5639. "endcap":"endcap",
  5640. "miterlimit":"miterlimit"
  5641. };
  5642. if (document.createStyleSheet) {
  5643. // this is the style rule for IE7/6: it uses a CSS class, tidy.
  5644. document.createStyleSheet().addRule(".jsplumb_vml", "behavior:url(#default#VML);position:absolute;");
  5645. // these are for VML in IE8. you have to explicitly call out which elements
  5646. // you're going to expect to support VML!
  5647. //
  5648. document.createStyleSheet().addRule("jsplumb\\:textbox", "behavior:url(#default#VML);position:absolute;");
  5649. document.createStyleSheet().addRule("jsplumb\\:oval", "behavior:url(#default#VML);position:absolute;");
  5650. document.createStyleSheet().addRule("jsplumb\\:rect", "behavior:url(#default#VML);position:absolute;");
  5651. document.createStyleSheet().addRule("jsplumb\\:stroke", "behavior:url(#default#VML);position:absolute;");
  5652. document.createStyleSheet().addRule("jsplumb\\:shape", "behavior:url(#default#VML);position:absolute;");
  5653. // in this page it is also mentioned that IE requires the extra arg to the namespace
  5654. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  5655. // but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either.
  5656. // var iev = document.documentMode;
  5657. //if (!iev || iev < 8)
  5658. document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml");
  5659. //else
  5660. // document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML");
  5661. }
  5662. jsPlumb.vml = {};
  5663. var scale = 1000,
  5664. _atts = function(o, atts) {
  5665. for (var i in atts) {
  5666. // IE8 fix: setattribute does not work after an element has been added to the dom!
  5667. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  5668. //o.setAttribute(i, atts[i]);
  5669. o[i] = atts[i];
  5670. }
  5671. },
  5672. _node = function(name, d, atts) {
  5673. atts = atts || {};
  5674. var o = document.createElement("jsplumb:" + name);
  5675. o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml";
  5676. _pos(o, d);
  5677. _atts(o, atts);
  5678. return o;
  5679. },
  5680. _pos = function(o,d) {
  5681. o.style.left = d[0] + "px";
  5682. o.style.top = d[1] + "px";
  5683. o.style.width= d[2] + "px";
  5684. o.style.height= d[3] + "px";
  5685. o.style.position = "absolute";
  5686. },
  5687. _conv = jsPlumb.vml.convertValue = function(v) {
  5688. return Math.floor(v * scale);
  5689. },
  5690. // tests if the given style is "transparent" and then sets the appropriate opacity node to 0 if so,
  5691. // or 1 if not. TODO in the future, support variable opacity.
  5692. _maybeSetOpacity = function(styleToWrite, styleToCheck, type, component) {
  5693. if ("transparent" === styleToCheck)
  5694. component.setOpacity(type, "0.0");
  5695. else
  5696. component.setOpacity(type, "1.0");
  5697. },
  5698. _applyStyles = function(node, style, component) {
  5699. var styleToWrite = {};
  5700. if (style.strokeStyle) {
  5701. styleToWrite["stroked"] = "true";
  5702. var strokeColor = jsPlumb.util.convertStyle(style.strokeStyle, true);
  5703. styleToWrite["strokecolor"] = strokeColor;
  5704. _maybeSetOpacity(styleToWrite, strokeColor, "stroke", component);
  5705. styleToWrite["strokeweight"] = style.lineWidth + "px";
  5706. }
  5707. else styleToWrite["stroked"] = "false";
  5708. if (style.fillStyle) {
  5709. styleToWrite["filled"] = "true";
  5710. var fillColor = jsPlumb.util.convertStyle(style.fillStyle, true);
  5711. styleToWrite["fillcolor"] = fillColor;
  5712. _maybeSetOpacity(styleToWrite, fillColor, "fill", component);
  5713. }
  5714. else styleToWrite["filled"] = "false";
  5715. if(style["dashstyle"]) {
  5716. if (component.strokeNode == null) {
  5717. component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] });
  5718. node.appendChild(component.strokeNode);
  5719. }
  5720. else
  5721. component.strokeNode.dashstyle = style["dashstyle"];
  5722. }
  5723. else if (style["stroke-dasharray"] && style["lineWidth"]) {
  5724. var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",",
  5725. parts = style["stroke-dasharray"].split(sep),
  5726. styleToUse = "";
  5727. for(var i = 0; i < parts.length; i++) {
  5728. styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep);
  5729. }
  5730. if (component.strokeNode == null) {
  5731. component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse });
  5732. node.appendChild(component.strokeNode);
  5733. }
  5734. else
  5735. component.strokeNode.dashstyle = styleToUse;
  5736. }
  5737. _atts(node, styleToWrite);
  5738. },
  5739. /*
  5740. * Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent.
  5741. */
  5742. VmlComponent = function() {
  5743. var self = this;
  5744. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  5745. this.opacityNodes = {
  5746. "stroke":null,
  5747. "fill":null
  5748. };
  5749. this.initOpacityNodes = function(vml) {
  5750. self.opacityNodes["stroke"] = _node("stroke", [0,0,1,1], {opacity:"0.0"});
  5751. self.opacityNodes["fill"] = _node("fill", [0,0,1,1], {opacity:"0.0"});
  5752. vml.appendChild(self.opacityNodes["stroke"]);
  5753. vml.appendChild(self.opacityNodes["fill"]);
  5754. };
  5755. this.setOpacity = function(type, value) {
  5756. var node = self.opacityNodes[type];
  5757. if (node) node["opacity"] = "" + value;
  5758. };
  5759. },
  5760. /*
  5761. * Base class for Vml connectors. extends VmlComponent.
  5762. */
  5763. VmlConnector = jsPlumb.VmlConnector = function(params) {
  5764. var self = this;
  5765. self.strokeNode = null;
  5766. self.canvas = null;
  5767. VmlComponent.apply(this, arguments);
  5768. var clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : "");
  5769. this.paint = function(d, style, anchor) {
  5770. if (style != null) {
  5771. var path = self.getPath(d), p = { "path":path };
  5772. if (style.outlineColor) {
  5773. var outlineWidth = style.outlineWidth || 1,
  5774. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
  5775. outlineStyle = {
  5776. strokeStyle : jsPlumb.util.convertStyle(style.outlineColor),
  5777. lineWidth : outlineStrokeWidth
  5778. };
  5779. for (var aa in vmlAttributeMap) outlineStyle[aa] = style[aa];
  5780. if (self.bgCanvas == null) {
  5781. p["class"] = clazz;
  5782. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  5783. self.bgCanvas = _node("shape", d, p);
  5784. jsPlumb.appendElement(self.bgCanvas, params.parent);
  5785. _pos(self.bgCanvas, d);
  5786. displayElements.push(self.bgCanvas);
  5787. }
  5788. else {
  5789. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  5790. _pos(self.bgCanvas, d);
  5791. _atts(self.bgCanvas, p);
  5792. }
  5793. _applyStyles(self.bgCanvas, outlineStyle, self);
  5794. }
  5795. if (self.canvas == null) {
  5796. p["class"] = clazz;
  5797. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  5798. if (self.tooltip) p["label"] = self.tooltip;
  5799. self.canvas = _node("shape", d, p);
  5800. jsPlumb.appendElement(self.canvas, params.parent);
  5801. displayElements.push(self.canvas);
  5802. self.attachListeners(self.canvas, self);
  5803. self.initOpacityNodes(self.canvas, ["stroke"]);
  5804. }
  5805. else {
  5806. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  5807. _pos(self.canvas, d);
  5808. _atts(self.canvas, p);
  5809. }
  5810. _applyStyles(self.canvas, style, self);
  5811. }
  5812. };
  5813. var displayElements = [ self.canvas ];
  5814. this.getDisplayElements = function() {
  5815. return displayElements;
  5816. };
  5817. this.appendDisplayElement = function(el) {
  5818. self.canvas.parentNode.appendChild(el);
  5819. displayElements.push(el);
  5820. };
  5821. this.reattachListeners = function() {
  5822. if (self.canvas) self.reattachListenersForElement(self.canvas, self);
  5823. };
  5824. },
  5825. /*
  5826. *
  5827. * Base class for Vml Endpoints. extends VmlComponent.
  5828. *
  5829. */
  5830. VmlEndpoint = function(params) {
  5831. VmlComponent.apply(this, arguments);
  5832. var vml = null, self = this, opacityStrokeNode = null, opacityFillNode = null;
  5833. self.canvas = document.createElement("div");
  5834. self.canvas.style["position"] = "absolute";
  5835. jsPlumb.appendElement(self.canvas, params.parent);
  5836. if (self.tooltip) self.canvas.setAttribute("label", self.tooltip);
  5837. this.paint = function(d, style, anchor) {
  5838. var p = { };
  5839. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  5840. if (vml == null) {
  5841. p["class"] = jsPlumb.endpointClass;
  5842. vml = self.getVml([0,0, d[2], d[3]], p, anchor);
  5843. self.canvas.appendChild(vml);
  5844. self.attachListeners(vml, self);
  5845. self.initOpacityNodes(vml, ["fill"]);
  5846. }
  5847. else {
  5848. //p["coordsize"] = "1,1";//(d[2] * scale) + "," + (d[3] * scale); again, unsure.
  5849. _pos(vml, [0,0, d[2], d[3]]);
  5850. _atts(vml, p);
  5851. }
  5852. _applyStyles(vml, style, self);
  5853. };
  5854. this.reattachListeners = function() {
  5855. if (vml) self.reattachListenersForElement(vml, self);
  5856. };
  5857. };
  5858. jsPlumb.Connectors.vml.Bezier = function() {
  5859. jsPlumb.Connectors.Bezier.apply(this, arguments);
  5860. VmlConnector.apply(this, arguments);
  5861. this.getPath = function(d) {
  5862. return "m" + _conv(d[4]) + "," + _conv(d[5]) +
  5863. " c" + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[10]) + "," + _conv(d[11]) + "," + _conv(d[6]) + "," + _conv(d[7]) + " e";
  5864. };
  5865. };
  5866. jsPlumb.Connectors.vml.Straight = function() {
  5867. jsPlumb.Connectors.Straight.apply(this, arguments);
  5868. VmlConnector.apply(this, arguments);
  5869. this.getPath = function(d) {
  5870. return "m" + _conv(d[4]) + "," + _conv(d[5]) + " l" + _conv(d[6]) + "," + _conv(d[7]) + " e";
  5871. };
  5872. };
  5873. jsPlumb.Connectors.vml.Flowchart = function() {
  5874. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  5875. VmlConnector.apply(this, arguments);
  5876. this.getPath = function(dimensions) {
  5877. var p = "m " + _conv(dimensions[4]) + "," + _conv(dimensions[5]) + " l";
  5878. // loop through extra points
  5879. for (var i = 0; i < dimensions[8]; i++) {
  5880. p = p + " " + _conv(dimensions[9 + (i*2)]) + "," + _conv(dimensions[10 + (i*2)]);
  5881. }
  5882. // finally draw a line to the end
  5883. p = p + " " + _conv(dimensions[6]) + "," + _conv(dimensions[7]) + " e";
  5884. return p;
  5885. };
  5886. };
  5887. jsPlumb.Endpoints.vml.Dot = function() {
  5888. jsPlumb.Endpoints.Dot.apply(this, arguments);
  5889. VmlEndpoint.apply(this, arguments);
  5890. this.getVml = function(d, atts, anchor) { return _node("oval", d, atts); };
  5891. };
  5892. jsPlumb.Endpoints.vml.Rectangle = function() {
  5893. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  5894. VmlEndpoint.apply(this, arguments);
  5895. this.getVml = function(d, atts, anchor) { return _node("rect", d, atts); };
  5896. };
  5897. /*
  5898. * VML Image Endpoint is the same as the default image endpoint.
  5899. */
  5900. jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image;
  5901. /**
  5902. * placeholder for Blank endpoint in vml renderer.
  5903. */
  5904. jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank;
  5905. /**
  5906. * VML Label renderer. uses the default label renderer (which adds an element to the DOM)
  5907. */
  5908. jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label;
  5909. var AbstractVmlArrowOverlay = function(superclass, originalArgs) {
  5910. superclass.apply(this, originalArgs);
  5911. VmlComponent.apply(this, arguments);
  5912. var self = this, path = null;
  5913. self.canvas = null;
  5914. var getPath = function(d, connectorDimensions) {
  5915. return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) +
  5916. " l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) +
  5917. " " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) +
  5918. " " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) +
  5919. " x e";
  5920. };
  5921. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions) {
  5922. var p = {};
  5923. if (strokeStyle) {
  5924. p["stroked"] = "true";
  5925. p["strokecolor"] = jsPlumb.util.convertStyle(strokeStyle, true);
  5926. }
  5927. if (lineWidth) p["strokeweight"] = lineWidth + "px";
  5928. if (fillStyle) {
  5929. p["filled"] = "true";
  5930. p["fillcolor"] = fillStyle;
  5931. }
  5932. var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
  5933. ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
  5934. xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
  5935. ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
  5936. w = Math.abs(xmax - xmin),
  5937. h = Math.abs(ymax - ymin),
  5938. dim = [xmin, ymin, w, h];
  5939. // for VML, we create overlays using shapes that have the same dimensions and
  5940. // coordsize as their connector - overlays calculate themselves relative to the
  5941. // connector (it's how it's been done since the original canvas implementation, because
  5942. // for canvas that makes sense).
  5943. p["path"] = getPath(d, connectorDimensions);
  5944. p["coordsize"] = (connectorDimensions[2] * scale) + "," + (connectorDimensions[3] * scale);
  5945. dim[0] = connectorDimensions[0];
  5946. dim[1] = connectorDimensions[1];
  5947. dim[2] = connectorDimensions[2];
  5948. dim[3] = connectorDimensions[3];
  5949. if (self.canvas == null) {
  5950. //p["class"] = jsPlumb.overlayClass; // TODO currentInstance?
  5951. self.canvas = _node("shape", dim, p);
  5952. connector.appendDisplayElement(self.canvas);
  5953. self.attachListeners(self.canvas, connector);
  5954. }
  5955. else {
  5956. _pos(self.canvas, dim);
  5957. _atts(self.canvas, p);
  5958. }
  5959. };
  5960. this.reattachListeners = function() {
  5961. if (self.canvas) self.reattachListenersForElement(self.canvas, self);
  5962. };
  5963. };
  5964. jsPlumb.Overlays.vml.Arrow = function() {
  5965. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  5966. };
  5967. jsPlumb.Overlays.vml.PlainArrow = function() {
  5968. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  5969. };
  5970. jsPlumb.Overlays.vml.Diamond = function() {
  5971. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  5972. };
  5973. })();/*
  5974. * jsPlumb
  5975. *
  5976. * Title:jsPlumb 1.3.5
  5977. *
  5978. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  5979. * elements, or VML.
  5980. *
  5981. * This file contains the SVG renderers.
  5982. *
  5983. * Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org)
  5984. *
  5985. * http://jsplumb.org
  5986. * http://github.com/sporritt/jsplumb
  5987. * http://code.google.com/p/jsplumb
  5988. *
  5989. * Dual licensed under the MIT and GPL2 licenses.
  5990. */
  5991. /**
  5992. * SVG support for jsPlumb.
  5993. *
  5994. * things to investigate:
  5995. *
  5996. * gradients: https://developer.mozilla.org/en/svg_in_html_introduction
  5997. * css:http://tutorials.jenkov.com/svg/svg-and-css.html
  5998. * text on a path: http://www.w3.org/TR/SVG/text.html#TextOnAPath
  5999. * pointer events: https://developer.mozilla.org/en/css/pointer-events
  6000. *
  6001. * IE9 hover jquery: http://forum.jquery.com/topic/1-6-2-broke-svg-hover-events
  6002. *
  6003. */
  6004. ;(function() {
  6005. var svgAttributeMap = {
  6006. "joinstyle":"stroke-linejoin",
  6007. "stroke-linejoin":"stroke-linejoin",
  6008. "stroke-dashoffset":"stroke-dashoffset",
  6009. "stroke-linecap":"stroke-linecap"
  6010. },
  6011. STROKE_DASHARRAY = "stroke-dasharray",
  6012. DASHSTYLE = "dashstyle",
  6013. LINEAR_GRADIENT = "linearGradient",
  6014. RADIAL_GRADIENT = "radialGradient",
  6015. FILL = "fill",
  6016. STOP = "stop",
  6017. STROKE = "stroke",
  6018. STROKE_WIDTH = "stroke-width",
  6019. STYLE = "style",
  6020. NONE = "none",
  6021. JSPLUMB_GRADIENT = "jsplumb_gradient_",
  6022. LINE_WIDTH = "lineWidth",
  6023. ns = {
  6024. svg:"http://www.w3.org/2000/svg",
  6025. xhtml:"http://www.w3.org/1999/xhtml"
  6026. },
  6027. _attr = function(node, attributes) {
  6028. for (var i in attributes)
  6029. node.setAttribute(i, "" + attributes[i]);
  6030. },
  6031. _node = function(name, attributes) {
  6032. var n = document.createElementNS(ns.svg, name);
  6033. attributes = attributes || {};
  6034. attributes["version"] = "1.1";
  6035. attributes["xmnls"] = ns.xhtml;
  6036. _attr(n, attributes);
  6037. return n;
  6038. },
  6039. _pos = function(d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; },
  6040. _clearGradient = function(parent) {
  6041. for (var i = 0; i < parent.childNodes.length; i++) {
  6042. if (parent.childNodes[i].tagName == LINEAR_GRADIENT || parent.childNodes[i].tagName == RADIAL_GRADIENT)
  6043. parent.removeChild(parent.childNodes[i]);
  6044. }
  6045. },
  6046. _updateGradient = function(parent, node, style, dimensions, uiComponent) {
  6047. var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.idstamp();
  6048. // first clear out any existing gradient
  6049. _clearGradient(parent);
  6050. // this checks for an 'offset' property in the gradient, and in the absence of it, assumes
  6051. // we want a linear gradient. if it's there, we create a radial gradient.
  6052. // it is possible that a more explicit means of defining the gradient type would be
  6053. // better. relying on 'offset' means that we can never have a radial gradient that uses
  6054. // some default offset, for instance.
  6055. if (!style.gradient.offset) {
  6056. var g = _node(LINEAR_GRADIENT, {id:id});
  6057. parent.appendChild(g);
  6058. }
  6059. else {
  6060. var g = _node(RADIAL_GRADIENT, {
  6061. id:id
  6062. });
  6063. parent.appendChild(g);
  6064. }
  6065. // the svg radial gradient seems to treat stops in the reverse
  6066. // order to how canvas does it. so we want to keep all the maths the same, but
  6067. // iterate the actual style declarations in reverse order, if the x indexes are not in order.
  6068. for (var i = 0; i < style.gradient.stops.length; i++) {
  6069. // Straight Connectors and Bezier connectors act slightly differently; this code is a bit of a kludge. but next version of
  6070. // jsplumb will be replacing both Straight and Bezier to be generic instances of 'Connector', which has a list of segments.
  6071. // so, not too concerned about leaving this in for now.
  6072. var styleToUse = i;
  6073. if (dimensions.length == 8)
  6074. styleToUse = dimensions[4] < dimensions[6] ? i: style.gradient.stops.length - 1 - i;
  6075. else
  6076. styleToUse = dimensions[4] < dimensions[6] ? style.gradient.stops.length - 1 - i : i;
  6077. var stopColor = jsPlumb.util.convertStyle(style.gradient.stops[styleToUse][1], true);
  6078. var s = _node(STOP, {"offset":Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color":stopColor});
  6079. g.appendChild(s);
  6080. }
  6081. var applyGradientTo = style.strokeStyle ? STROKE : FILL;
  6082. node.setAttribute(STYLE, applyGradientTo + ":url(#" + id + ")");
  6083. },
  6084. _applyStyles = function(parent, node, style, dimensions, uiComponent) {
  6085. if (style.gradient) {
  6086. _updateGradient(parent, node, style, dimensions, uiComponent);
  6087. }
  6088. else {
  6089. // make sure we clear any existing gradient
  6090. _clearGradient(parent);
  6091. node.setAttribute(STYLE, "");
  6092. }
  6093. node.setAttribute(FILL, style.fillStyle ? jsPlumb.util.convertStyle(style.fillStyle, true) : NONE);
  6094. node.setAttribute(STROKE, style.strokeStyle ? jsPlumb.util.convertStyle(style.strokeStyle, true) : NONE);
  6095. if (style.lineWidth) {
  6096. node.setAttribute(STROKE_WIDTH, style.lineWidth);
  6097. }
  6098. // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
  6099. // the syntax in VML but is actually kind of nasty: values are given in the pixel
  6100. // coordinate space, whereas in VML they are multiples of the width of the stroked
  6101. // line, which makes a lot more sense. for that reason, jsPlumb is supporting both
  6102. // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
  6103. // VML, which will be the preferred method. the code below this converts a dashstyle
  6104. // attribute given in terms of stroke width into a pixel representation, by using the
  6105. // stroke's lineWidth.
  6106. if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) {
  6107. var sep = style[DASHSTYLE].indexOf(",") == -1 ? " " : ",",
  6108. parts = style[DASHSTYLE].split(sep),
  6109. styleToUse = "";
  6110. parts.forEach(function(p) {
  6111. styleToUse += (Math.floor(p * style.lineWidth) + sep);
  6112. });
  6113. node.setAttribute(STROKE_DASHARRAY, styleToUse);
  6114. }
  6115. else if(style[STROKE_DASHARRAY]) {
  6116. node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]);
  6117. }
  6118. // extra attributes such as join type, dash offset.
  6119. for (var i in svgAttributeMap) {
  6120. if (style[i]) {
  6121. node.setAttribute(svgAttributeMap[i], style[i]);
  6122. }
  6123. }
  6124. },
  6125. _decodeFont = function(f) {
  6126. var r = /([0-9].)(p[xt])\s(.*)/;
  6127. var bits = f.match(r);
  6128. return {size:bits[1] + bits[2], font:bits[3]};
  6129. },
  6130. _classManip = function(el, add, clazz) {
  6131. var classesToAddOrRemove = clazz.split(" "),
  6132. className = el.className,
  6133. curClasses = className.baseVal.split(" ");
  6134. for (var i = 0; i < classesToAddOrRemove.length; i++) {
  6135. if (add) {
  6136. if (curClasses.indexOf(classesToAddOrRemove[i]) == -1)
  6137. curClasses.push(classesToAddOrRemove[i]);
  6138. }
  6139. else {
  6140. var idx = curClasses.indexOf(classesToAddOrRemove[i]);
  6141. if (idx != -1)
  6142. curClasses.splice(idx, 1);
  6143. }
  6144. }
  6145. el.className.baseVal = curClasses.join(" ");
  6146. },
  6147. _addClass = function(el, clazz) {
  6148. _classManip(el, true, clazz);
  6149. },
  6150. _removeClass = function(el, clazz) {
  6151. _classManip(el, false, clazz);
  6152. };
  6153. /**
  6154. utility methods for other objects to use.
  6155. */
  6156. jsPlumb.util.svg = {
  6157. addClass:_addClass,
  6158. removeClass:_removeClass
  6159. };
  6160. /*
  6161. * Base class for SVG components.
  6162. */
  6163. //var SvgComponent = function(cssClass, originalArgs, pointerEventsSpec) {
  6164. var SvgComponent = function(params) {
  6165. var self = this,
  6166. pointerEventsSpec = params.pointerEventsSpec || "all";
  6167. jsPlumb.jsPlumbUIComponent.apply(this, params.originalArgs);
  6168. self.canvas = null, self.path = null, self.svg = null;
  6169. var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""),
  6170. svgParams = {
  6171. "style":"",
  6172. "width":0,
  6173. "height":0,
  6174. "pointer-events":pointerEventsSpec,
  6175. "position":"absolute"
  6176. };
  6177. if (self.tooltip) svgParams["label"] = self.tooltip;
  6178. self.svg = _node("svg", svgParams);
  6179. if (params.useDivWrapper) {
  6180. self.canvas = document.createElement("div");
  6181. self.canvas.style["position"] = "absolute";
  6182. jsPlumb.sizeCanvas(self.canvas,0,0,1,1);
  6183. self.canvas.className = clazz;
  6184. if (self.tooltip) self.canvas.setAttribute("label", self.tooltip);
  6185. }
  6186. else {
  6187. _attr(self.svg, { "class":clazz });
  6188. self.canvas = self.svg;
  6189. }
  6190. jsPlumb.appendElement(self.canvas, params.originalArgs[0]["parent"]);
  6191. if (params.useDivWrapper) self.canvas.appendChild(self.svg);
  6192. // TODO this displayElement stuff is common between all components, across all
  6193. // renderers. would be best moved to jsPlumbUIComponent.
  6194. var displayElements = [ self.canvas ];
  6195. this.getDisplayElements = function() {
  6196. return displayElements;
  6197. };
  6198. this.appendDisplayElement = function(el) {
  6199. displayElements.push(el);
  6200. };
  6201. this.paint = function(d, style, anchor) {
  6202. if (style != null) {
  6203. var x = d[0], y = d[1];
  6204. if (params.useDivWrapper) {
  6205. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  6206. x = 0, y = 0;
  6207. }
  6208. _attr(self.svg, {
  6209. "style":_pos([x, y, d[2], d[3]]),
  6210. "width": d[2],
  6211. "height": d[3]
  6212. });
  6213. self._paint.apply(this, arguments);
  6214. }
  6215. };
  6216. };
  6217. /*
  6218. * Base class for SVG connectors.
  6219. */
  6220. var SvgConnector = jsPlumb.SvgConnector = function(params) {
  6221. var self = this;
  6222. SvgComponent.apply(this, [ { cssClass:params["_jsPlumb"].connectorClass, originalArgs:arguments, pointerEventsSpec:"none", tooltip:params.tooltip } ]);
  6223. this._paint = function(d, style) {
  6224. var p = self.getPath(d), a = { "d":p }, outlineStyle = null;
  6225. a["pointer-events"] = "all";
  6226. // outline style. actually means drawing an svg object underneath the main one.
  6227. if (style.outlineColor) {
  6228. var outlineWidth = style.outlineWidth || 1,
  6229. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
  6230. outlineStyle = jsPlumb.CurrentLibrary.extend({}, style);
  6231. outlineStyle.strokeStyle = jsPlumb.util.convertStyle(style.outlineColor);
  6232. outlineStyle.lineWidth = outlineStrokeWidth;
  6233. if (self.bgPath == null) {
  6234. self.bgPath = _node("path", a);
  6235. self.svg.appendChild(self.bgPath);
  6236. self.attachListeners(self.bgPath, self);
  6237. }
  6238. else {
  6239. _attr(self.bgPath, a);
  6240. }
  6241. _applyStyles(self.svg, self.bgPath, outlineStyle, d, self);
  6242. }
  6243. // test - see below
  6244. // a["clip-path"]= "url(#testClip)";
  6245. if (self.path == null) {
  6246. self.path = _node("path", a);
  6247. self.svg.appendChild(self.path);
  6248. self.attachListeners(self.path, self);
  6249. /*
  6250. this is a test of a clip path. i'm looking into using one of these to animate a jsplumb connection.
  6251. you could do this by walking along the line, stepping along a little at a time, and setting the clip
  6252. path to extend as far as that point.
  6253. self.clip = _node("clipPath", {id:"testClip", clipPathUnits:"objectBoundingBox"});
  6254. self.svg.appendChild(self.clip);
  6255. self.clip.appendChild(_node("rect", {
  6256. x:"0",y:"0",width:"0.5",height:"1"
  6257. }));
  6258. */
  6259. }
  6260. else {
  6261. _attr(self.path, a);
  6262. }
  6263. _applyStyles(self.svg, self.path, style, d, self);
  6264. };
  6265. this.reattachListeners = function() {
  6266. if (self.bgPath) self.reattachListenersForElement(self.bgPath, self);
  6267. if (self.path) self.reattachListenersForElement(self.path, self);
  6268. };
  6269. };
  6270. /*
  6271. * SVG Bezier Connector
  6272. */
  6273. jsPlumb.Connectors.svg.Bezier = function(params) {
  6274. jsPlumb.Connectors.Bezier.apply(this, arguments);
  6275. SvgConnector.apply(this, arguments);
  6276. this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " C " + d[8] + " " + d[9] + " " + d[10] + " " + d[11] + " " + d[6] + " " + d[7]; };
  6277. };
  6278. /*
  6279. * SVG straight line Connector
  6280. */
  6281. jsPlumb.Connectors.svg.Straight = function(params) {
  6282. jsPlumb.Connectors.Straight.apply(this, arguments);
  6283. SvgConnector.apply(this, arguments);
  6284. this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " L " + d[6] + " " + d[7]; };
  6285. };
  6286. jsPlumb.Connectors.svg.Flowchart = function() {
  6287. var self = this;
  6288. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  6289. SvgConnector.apply(this, arguments);
  6290. this.getPath = function(dimensions) {
  6291. var p = "M " + dimensions[4] + "," + dimensions[5];
  6292. // loop through extra points
  6293. for (var i = 0; i < dimensions[8]; i++) {
  6294. p = p + " L " + dimensions[9 + (i*2)] + " " + dimensions[10 + (i*2)];
  6295. }
  6296. // finally draw a line to the end
  6297. p = p + " " + dimensions[6] + "," + dimensions[7];
  6298. return p;
  6299. };
  6300. };
  6301. /*
  6302. * Base class for SVG endpoints.
  6303. */
  6304. var SvgEndpoint = function(params) {
  6305. var self = this;
  6306. SvgComponent.apply(this, [ {
  6307. cssClass:params["_jsPlumb"].endpointClass,
  6308. originalArgs:arguments,
  6309. pointerEventsSpec:"all",
  6310. useDivWrapper:true
  6311. } ]);
  6312. this._paint = function(d, style) {
  6313. var s = jsPlumb.extend({}, style);
  6314. if (s.outlineColor) {
  6315. s.strokeWidth = s.outlineWidth;
  6316. s.strokeStyle = jsPlumb.util.convertStyle(s.outlineColor, true);
  6317. }
  6318. if (self.node == null) {
  6319. self.node = self.makeNode(d, s);
  6320. self.svg.appendChild(self.node);
  6321. self.attachListeners(self.node, self);
  6322. }
  6323. _applyStyles(self.svg, self.node, s, d, self);
  6324. _pos(self.node, d);
  6325. };
  6326. this.reattachListeners = function() {
  6327. if (self.node) self.reattachListenersForElement(self.node, self);
  6328. };
  6329. };
  6330. /*
  6331. * SVG Dot Endpoint
  6332. */
  6333. jsPlumb.Endpoints.svg.Dot = function() {
  6334. jsPlumb.Endpoints.Dot.apply(this, arguments);
  6335. SvgEndpoint.apply(this, arguments);
  6336. this.makeNode = function(d, style) {
  6337. return _node("circle", {
  6338. "cx" : d[2] / 2,
  6339. "cy" : d[3] / 2,
  6340. "r" : d[2] / 2
  6341. });
  6342. };
  6343. };
  6344. /*
  6345. * SVG Rectangle Endpoint
  6346. */
  6347. jsPlumb.Endpoints.svg.Rectangle = function() {
  6348. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  6349. SvgEndpoint.apply(this, arguments);
  6350. this.makeNode = function(d, style) {
  6351. return _node("rect", {
  6352. "width":d[2],
  6353. "height":d[3]
  6354. });
  6355. };
  6356. };
  6357. /*
  6358. * SVG Image Endpoint is the default image endpoint.
  6359. */
  6360. jsPlumb.Endpoints.svg.Image = jsPlumb.Endpoints.Image;
  6361. /*
  6362. * Blank endpoint in svg renderer is the default Blank endpoint.
  6363. */
  6364. jsPlumb.Endpoints.svg.Blank = jsPlumb.Endpoints.Blank;
  6365. /*
  6366. * Label endpoint in svg renderer is the default Label endpoint.
  6367. */
  6368. jsPlumb.Overlays.svg.Label = jsPlumb.Overlays.Label;
  6369. var AbstractSvgArrowOverlay = function(superclass, originalArgs) {
  6370. superclass.apply(this, originalArgs);
  6371. jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
  6372. this.isAppendedAtTopLevel = false;
  6373. var self = this, path =null;
  6374. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  6375. if (path == null) {
  6376. path = _node("path");
  6377. connector.svg.appendChild(path);
  6378. self.attachListeners(path, connector);
  6379. self.attachListeners(path, self);
  6380. }
  6381. var clazz = originalArgs && (originalArgs.length == 1) ? (originalArgs[0].cssClass || "") : "";
  6382. _attr(path, {
  6383. "d" : makePath(d),
  6384. "class" : clazz,
  6385. stroke : strokeStyle ? strokeStyle : null,
  6386. fill : fillStyle ? fillStyle : null
  6387. });
  6388. };
  6389. var makePath = function(d) {
  6390. return "M" + d.hxy.x + "," + d.hxy.y +
  6391. " L" + d.tail[0].x + "," + d.tail[0].y +
  6392. " L" + d.cxy.x + "," + d.cxy.y +
  6393. " L" + d.tail[1].x + "," + d.tail[1].y +
  6394. " L" + d.hxy.x + "," + d.hxy.y;
  6395. };
  6396. this.reattachListeners = function() {
  6397. if (path) self.reattachListenersForElement(path, self);
  6398. };
  6399. };
  6400. jsPlumb.Overlays.svg.Arrow = function() {
  6401. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  6402. };
  6403. jsPlumb.Overlays.svg.PlainArrow = function() {
  6404. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  6405. };
  6406. jsPlumb.Overlays.svg.Diamond = function() {
  6407. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  6408. };
  6409. // a test
  6410. jsPlumb.Overlays.svg.GuideLines = function() {
  6411. var path = null, self = this, path2 = null, p1_1, p1_2;
  6412. jsPlumb.Overlays.GuideLines.apply(this, arguments);
  6413. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  6414. if (path == null) {
  6415. path = _node("path");
  6416. connector.svg.appendChild(path);
  6417. self.attachListeners(path, connector);
  6418. self.attachListeners(path, self);
  6419. p1_1 = _node("path");
  6420. connector.svg.appendChild(p1_1);
  6421. self.attachListeners(p1_1, connector);
  6422. self.attachListeners(p1_1, self);
  6423. p1_2 = _node("path");
  6424. connector.svg.appendChild(p1_2);
  6425. self.attachListeners(p1_2, connector);
  6426. self.attachListeners(p1_2, self);
  6427. }
  6428. _attr(path, {
  6429. "d" : makePath(d[0], d[1]),
  6430. stroke : "red",
  6431. fill : null
  6432. });
  6433. _attr(p1_1, {
  6434. "d" : makePath(d[2][0], d[2][1]),
  6435. stroke : "blue",
  6436. fill : null
  6437. });
  6438. _attr(p1_2, {
  6439. "d" : makePath(d[3][0], d[3][1]),
  6440. stroke : "green",
  6441. fill : null
  6442. });
  6443. };
  6444. var makePath = function(d1, d2) {
  6445. return "M " + d1.x + "," + d1.y +
  6446. " L" + d2.x + "," + d2.y;
  6447. };
  6448. };
  6449. })();/*
  6450. * jsPlumb
  6451. *
  6452. * Title:jsPlumb 1.3.5
  6453. *
  6454. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  6455. * elements, or VML.
  6456. *
  6457. * This file contains the HTML5 canvas renderers.
  6458. *
  6459. * Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org)
  6460. *
  6461. * http://jsplumb.org
  6462. * http://github.com/sporritt/jsplumb
  6463. * http://code.google.com/p/jsplumb
  6464. *
  6465. * Dual licensed under the MIT and GPL2 licenses.
  6466. */
  6467. ;(function() {
  6468. // ********************************* CANVAS RENDERERS FOR CONNECTORS AND ENDPOINTS *******************************************************************
  6469. // TODO refactor to renderer common script. put a ref to jsPlumb.sizeCanvas in there too.
  6470. var _connectionBeingDragged = null,
  6471. _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
  6472. _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
  6473. _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
  6474. _pageXY = function(el) { return jsPlumb.CurrentLibrary.getPageXY(el); },
  6475. _clientXY = function(el) { return jsPlumb.CurrentLibrary.getClientXY(el); };
  6476. /*
  6477. * Class:CanvasMouseAdapter
  6478. * Provides support for mouse events on canvases.
  6479. */
  6480. var CanvasMouseAdapter = function() {
  6481. var self = this;
  6482. self.overlayPlacements = [];
  6483. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  6484. jsPlumb.EventGenerator.apply(this, arguments);
  6485. /**
  6486. * returns whether or not the given event is ojver a painted area of the canvas.
  6487. */
  6488. this._over = function(e) {
  6489. var o = _getOffset(_getElementObject(self.canvas)),
  6490. pageXY = _pageXY(e),
  6491. x = pageXY[0] - o.left, y = pageXY[1] - o.top;
  6492. if (x > 0 && y > 0 && x < self.canvas.width && y < self.canvas.height) {
  6493. // first check overlays
  6494. for ( var i = 0; i < self.overlayPlacements.length; i++) {
  6495. var p = self.overlayPlacements[i];
  6496. if (p && (p[0] <= x && p[1] >= x && p[2] <= y && p[3] >= y))
  6497. return true;
  6498. }
  6499. // then the canvas
  6500. var d = self.canvas.getContext("2d").getImageData(parseInt(x), parseInt(y), 1, 1);
  6501. return d.data[0] != 0 || d.data[1] != 0 || d.data[2] != 0 || d.data[3] != 0;
  6502. }
  6503. return false;
  6504. };
  6505. var _mouseover = false, _mouseDown = false, _posWhenMouseDown = null, _mouseWasDown = false,
  6506. _nullSafeHasClass = function(el, clazz) {
  6507. return el != null && _hasClass(el, clazz);
  6508. };
  6509. this.mousemove = function(e) {
  6510. var pageXY = _pageXY(e), clientXY = _clientXY(e),
  6511. ee = document.elementFromPoint(clientXY[0], clientXY[1]),
  6512. eventSourceWasOverlay = _nullSafeHasClass(ee, "_jsPlumb_overlay");
  6513. var _continue = _connectionBeingDragged == null && (_nullSafeHasClass(ee, "_jsPlumb_endpoint") || _nullSafeHasClass(ee, "_jsPlumb_connector"));
  6514. if (!_mouseover && _continue && self._over(e)) {
  6515. _mouseover = true;
  6516. self.fire("mouseenter", self, e);
  6517. return true;
  6518. }
  6519. // TODO here there is a remote chance that the overlay the mouse moved onto
  6520. // is actually not an overlay for the current component. a more thorough check would
  6521. // be to ensure the overlay belonged to the current component.
  6522. else if (_mouseover && (!self._over(e) || !_continue) && !eventSourceWasOverlay) {
  6523. _mouseover = false;
  6524. self.fire("mouseexit", self, e);
  6525. }
  6526. self.fire("mousemove", self, e);
  6527. };
  6528. this.click = function(e) {
  6529. // to filter right click in FF, i could compare e.button. 0 means left mouse button; 1 middle, 2 right.
  6530. //console.log(e.button);
  6531. if (_mouseover && self._over(e) && !_mouseWasDown)
  6532. self.fire("click", self, e);
  6533. _mouseWasDown = false;
  6534. };
  6535. this.dblclick = function(e) {
  6536. if (_mouseover && self._over(e) && !_mouseWasDown)
  6537. self.fire("dblclick", self, e);
  6538. _mouseWasDown = false;
  6539. };
  6540. this.mousedown = function(e) {
  6541. if(self._over(e) && !_mouseDown) {
  6542. _mouseDown = true;
  6543. _posWhenMouseDown = _getOffset(_getElementObject(self.canvas));
  6544. self.fire("mousedown", self, e);
  6545. }
  6546. };
  6547. this.mouseup = function(e) {
  6548. _mouseDown = false;
  6549. self.fire("mouseup", self, e);
  6550. };
  6551. };
  6552. var _newCanvas = function(params) {
  6553. var canvas = document.createElement("canvas");
  6554. jsPlumb.appendElement(canvas, params.parent);
  6555. canvas.style.position = "absolute";
  6556. if (params["class"]) canvas.className = params["class"];
  6557. // set an id. if no id on the element and if uuid was supplied it
  6558. // will be used, otherwise we'll create one.
  6559. params["_jsPlumb"].getId(canvas, params.uuid);
  6560. if (params.tooltip) canvas.setAttribute("label", params.tooltip);
  6561. return canvas;
  6562. };
  6563. /**
  6564. * Class:CanvasConnector
  6565. * Superclass for Canvas Connector renderers.
  6566. */
  6567. var CanvasConnector = jsPlumb.CanvasConnector = function(params) {
  6568. CanvasMouseAdapter.apply(this, arguments);
  6569. var _paintOneStyle = function(dim, aStyle) {
  6570. self.ctx.save();
  6571. jsPlumb.extend(self.ctx, aStyle);
  6572. if (aStyle.gradient) {
  6573. var g = self.createGradient(dim, self.ctx);
  6574. for ( var i = 0; i < aStyle.gradient.stops.length; i++)
  6575. g.addColorStop(aStyle.gradient.stops[i][0], aStyle.gradient.stops[i][1]);
  6576. self.ctx.strokeStyle = g;
  6577. }
  6578. self._paint(dim);
  6579. self.ctx.restore();
  6580. };
  6581. var self = this,
  6582. clazz = self._jsPlumb.connectorClass + " " + (params.cssClass || "");
  6583. self.canvas = _newCanvas({
  6584. "class":clazz,
  6585. _jsPlumb:self._jsPlumb,
  6586. parent:params.parent,
  6587. tooltip:params.tooltip
  6588. });
  6589. self.ctx = self.canvas.getContext("2d");
  6590. var displayElements = [ self.canvas ];
  6591. this.getDisplayElements = function() { return displayElements; };
  6592. this.appendDisplayElement = function(el) { displayElements.push(el); };
  6593. self.paint = function(dim, style) {
  6594. if (style != null) {
  6595. jsPlumb.sizeCanvas(self.canvas, dim[0], dim[1], dim[2], dim[3]);
  6596. if (style.outlineColor != null) {
  6597. var outlineWidth = style.outlineWidth || 1,
  6598. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
  6599. outlineStyle = {
  6600. strokeStyle:style.outlineColor,
  6601. lineWidth:outlineStrokeWidth
  6602. };
  6603. _paintOneStyle(dim, outlineStyle);
  6604. }
  6605. _paintOneStyle(dim, style);
  6606. }
  6607. };
  6608. };
  6609. /**
  6610. * Class:CanvasEndpoint
  6611. * Superclass for Canvas Endpoint renderers.
  6612. */
  6613. var CanvasEndpoint = function(params) {
  6614. var self = this;
  6615. CanvasMouseAdapter.apply(this, arguments);
  6616. var clazz = self._jsPlumb.endpointClass + " " + (params.cssClass || ""),
  6617. canvasParams = {
  6618. "class":clazz,
  6619. _jsPlumb:self._jsPlumb,
  6620. parent:params.parent,
  6621. tooltip:self.tooltip
  6622. };
  6623. self.canvas = _newCanvas(canvasParams);
  6624. self.ctx = self.canvas.getContext("2d");
  6625. this.paint = function(d, style, anchor) {
  6626. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  6627. if (style.outlineColor != null) {
  6628. var outlineWidth = style.outlineWidth || 1,
  6629. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  6630. var outlineStyle = {
  6631. strokeStyle:style.outlineColor,
  6632. lineWidth:outlineStrokeWidth
  6633. };
  6634. }
  6635. self._paint.apply(this, arguments);
  6636. };
  6637. };
  6638. jsPlumb.Endpoints.canvas.Dot = function(params) {
  6639. jsPlumb.Endpoints.Dot.apply(this, arguments);
  6640. CanvasEndpoint.apply(this, arguments);
  6641. var self = this,
  6642. parseValue = function(value) {
  6643. try { return parseInt(value); }
  6644. catch(e) {
  6645. if (value.substring(value.length - 1) == '%')
  6646. return parseInt(value.substring(0, value - 1));
  6647. }
  6648. },
  6649. calculateAdjustments = function(gradient) {
  6650. var offsetAdjustment = self.defaultOffset, innerRadius = self.defaultInnerRadius;
  6651. gradient.offset && (offsetAdjustment = parseValue(gradient.offset));
  6652. gradient.innerRadius && (innerRadius = parseValue(gradient.innerRadius));
  6653. return [offsetAdjustment, innerRadius];
  6654. };
  6655. this._paint = function(d, style, anchor) {
  6656. if (style != null) {
  6657. var ctx = self.canvas.getContext('2d'), orientation = anchor.getOrientation(self);
  6658. jsPlumb.extend(ctx, style);
  6659. if (style.gradient) {
  6660. var adjustments = calculateAdjustments(style.gradient),
  6661. yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0],
  6662. xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0],
  6663. g = ctx.createRadialGradient(d[4], d[4], d[4], d[4] + xAdjust, d[4] + yAdjust, adjustments[1]);
  6664. for (var i = 0; i < style.gradient.stops.length; i++)
  6665. g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
  6666. ctx.fillStyle = g;
  6667. }
  6668. ctx.beginPath();
  6669. ctx.arc(d[4], d[4], d[4], 0, Math.PI*2, true);
  6670. ctx.closePath();
  6671. if (style.fillStyle || style.gradient) ctx.fill();
  6672. if (style.strokeStyle) ctx.stroke();
  6673. }
  6674. };
  6675. };
  6676. jsPlumb.Endpoints.canvas.Rectangle = function(params) {
  6677. var self = this;
  6678. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  6679. CanvasEndpoint.apply(this, arguments);
  6680. this._paint = function(d, style, anchor) {
  6681. var ctx = self.canvas.getContext("2d"), orientation = anchor.getOrientation(self);
  6682. jsPlumb.extend(ctx, style);
  6683. /* canvas gradient */
  6684. if (style.gradient) {
  6685. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  6686. var y1 = orientation[1] == 1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
  6687. var y2 = orientation[1] == -1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
  6688. var x1 = orientation[0] == 1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
  6689. var x2 = orientation[0] == -1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
  6690. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  6691. for (var i = 0; i < style.gradient.stops.length; i++)
  6692. g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
  6693. ctx.fillStyle = g;
  6694. }
  6695. ctx.beginPath();
  6696. ctx.rect(0, 0, d[2], d[3]);
  6697. ctx.closePath();
  6698. if (style.fillStyle || style.gradient) ctx.fill();
  6699. if (style.strokeStyle) ctx.stroke();
  6700. };
  6701. };
  6702. jsPlumb.Endpoints.canvas.Triangle = function(params) {
  6703. var self = this;
  6704. jsPlumb.Endpoints.Triangle.apply(this, arguments);
  6705. CanvasEndpoint.apply(this, arguments);
  6706. this._paint = function(d, style, anchor)
  6707. {
  6708. var width = d[2], height = d[3], x = d[0], y = d[1],
  6709. ctx = self.canvas.getContext('2d'),
  6710. offsetX = 0, offsetY = 0, angle = 0,
  6711. orientation = anchor.getOrientation(self);
  6712. if( orientation[0] == 1 ) {
  6713. offsetX = width;
  6714. offsetY = height;
  6715. angle = 180;
  6716. }
  6717. if( orientation[1] == -1 ) {
  6718. offsetX = width;
  6719. angle = 90;
  6720. }
  6721. if( orientation[1] == 1 ) {
  6722. offsetY = height;
  6723. angle = -90;
  6724. }
  6725. ctx.fillStyle = style.fillStyle;
  6726. ctx.translate(offsetX, offsetY);
  6727. ctx.rotate(angle * Math.PI/180);
  6728. ctx.beginPath();
  6729. ctx.moveTo(0, 0);
  6730. ctx.lineTo(width/2, height/2);
  6731. ctx.lineTo(0, height);
  6732. ctx.closePath();
  6733. if (style.fillStyle || style.gradient) ctx.fill();
  6734. if (style.strokeStyle) ctx.stroke();
  6735. };
  6736. };
  6737. /*
  6738. * Canvas Image Endpoint: uses the default version, which creates an <img> tag.
  6739. */
  6740. jsPlumb.Endpoints.canvas.Image = jsPlumb.Endpoints.Image;
  6741. /*
  6742. * Blank endpoint in all renderers is just the default Blank endpoint.
  6743. */
  6744. jsPlumb.Endpoints.canvas.Blank = jsPlumb.Endpoints.Blank;
  6745. /*
  6746. * Canvas Bezier Connector. Draws a Bezier curve onto a Canvas element.
  6747. */
  6748. jsPlumb.Connectors.canvas.Bezier = function() {
  6749. var self = this;
  6750. jsPlumb.Connectors.Bezier.apply(this, arguments);
  6751. CanvasConnector.apply(this, arguments);
  6752. this._paint = function(dimensions) {
  6753. self.ctx.beginPath();
  6754. self.ctx.moveTo(dimensions[4], dimensions[5]);
  6755. self.ctx.bezierCurveTo(dimensions[8], dimensions[9], dimensions[10], dimensions[11], dimensions[6], dimensions[7]);
  6756. self.ctx.stroke();
  6757. };
  6758. // TODO i doubt this handles the case that source and target are swapped.
  6759. this.createGradient = function(dim, ctx, swap) {
  6760. return /*(swap) ? self.ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : */self.ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  6761. };
  6762. };
  6763. /*
  6764. * Canvas straight line Connector. Draws a straight line onto a Canvas element.
  6765. */
  6766. jsPlumb.Connectors.canvas.Straight = function() {
  6767. var self = this;
  6768. jsPlumb.Connectors.Straight.apply(this, arguments);
  6769. CanvasConnector.apply(this, arguments);
  6770. this._paint = function(dimensions) {
  6771. self.ctx.beginPath();
  6772. self.ctx.moveTo(dimensions[4], dimensions[5]);
  6773. self.ctx.lineTo(dimensions[6], dimensions[7]);
  6774. self.ctx.stroke();
  6775. };
  6776. // TODO this does not handle the case that src and target are swapped.
  6777. this.createGradient = function(dim, ctx) {
  6778. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  6779. };
  6780. };
  6781. jsPlumb.Connectors.canvas.Flowchart = function() {
  6782. var self = this;
  6783. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  6784. CanvasConnector.apply(this, arguments);
  6785. this._paint = function(dimensions) {
  6786. self.ctx.beginPath();
  6787. self.ctx.moveTo(dimensions[4], dimensions[5]);
  6788. // loop through extra points
  6789. for (var i = 0; i < dimensions[8]; i++) {
  6790. self.ctx.lineTo(dimensions[9 + (i*2)], dimensions[10 + (i*2)]);
  6791. }
  6792. // finally draw a line to the end
  6793. self.ctx.lineTo(dimensions[6], dimensions[7]);
  6794. self.ctx.stroke();
  6795. };
  6796. this.createGradient = function(dim, ctx) {
  6797. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  6798. };
  6799. };
  6800. // ********************************* END OF CANVAS RENDERERS *******************************************************************
  6801. jsPlumb.Overlays.canvas.Label = jsPlumb.Overlays.Label;
  6802. /**
  6803. * a placeholder right now, really just exists to mirror the fact that there are SVG and VML versions of this.
  6804. */
  6805. var CanvasOverlay = function() {
  6806. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  6807. };
  6808. var AbstractCanvasArrowOverlay = function(superclass, originalArgs) {
  6809. superclass.apply(this, originalArgs);
  6810. CanvasOverlay.apply(this, arguments);
  6811. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  6812. var ctx = connector.ctx;
  6813. ctx.lineWidth = lineWidth;
  6814. ctx.beginPath();
  6815. ctx.moveTo(d.hxy.x, d.hxy.y);
  6816. ctx.lineTo(d.tail[0].x, d.tail[0].y);
  6817. ctx.lineTo(d.cxy.x, d.cxy.y);
  6818. ctx.lineTo(d.tail[1].x, d.tail[1].y);
  6819. ctx.lineTo(d.hxy.x, d.hxy.y);
  6820. ctx.closePath();
  6821. if (strokeStyle) {
  6822. ctx.strokeStyle = strokeStyle;
  6823. ctx.stroke();
  6824. }
  6825. if (fillStyle) {
  6826. ctx.fillStyle = fillStyle;
  6827. ctx.fill();
  6828. }
  6829. };
  6830. };
  6831. jsPlumb.Overlays.canvas.Arrow = function() {
  6832. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  6833. };
  6834. jsPlumb.Overlays.canvas.PlainArrow = function() {
  6835. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  6836. };
  6837. jsPlumb.Overlays.canvas.Diamond = function() {
  6838. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  6839. };
  6840. })();/*
  6841. * jsPlumb
  6842. *
  6843. * Title:jsPlumb 1.3.5
  6844. *
  6845. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  6846. * elements, or VML.
  6847. *
  6848. * This file contains the YUI3 adapter.
  6849. *
  6850. * Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org)
  6851. *
  6852. * http://jsplumb.org
  6853. * http://github.com/sporritt/jsplumb
  6854. * http://code.google.com/p/jsplumb
  6855. *
  6856. * Dual licensed under the MIT and GPL2 licenses.
  6857. */
  6858. /**
  6859. * addClass adds a class to the given element
  6860. * animate calls the underlying library's animate functionality
  6861. * appendElement appends a child element to a parent element.
  6862. * bind binds some event to an element
  6863. * dragEvents a dictionary of event names
  6864. * extend extend some js object with another. probably not overly necessary; jsPlumb could just do this internally.
  6865. * getAttribute gets some attribute from an element
  6866. * getDragObject gets the object that is being dragged, by extracting it from the arguments passed to a drag callback
  6867. * getDragScope gets the drag scope for a given element.
  6868. * getElementObject turns an id or dom element into an element object of the underlying library's type.
  6869. * getOffset gets an element's offset
  6870. * getScrollLeft gets an element's scroll left. TODO: is this actually used? will it be?
  6871. * getScrollTop gets an element's scroll top. TODO: is this actually used? will it be?
  6872. * getSize gets an element's size.
  6873. * getUIPosition gets the position of some element that is currently being dragged, by extracting it from the arguments passed to a drag callback.
  6874. * initDraggable initializes an element to be draggable
  6875. * initDroppable initializes an element to be droppable
  6876. * isDragSupported returns whether or not drag is supported for some element.
  6877. * isDropSupported returns whether or not drop is supported for some element.
  6878. * removeClass removes a class from a given element.
  6879. * removeElement removes some element completely from the DOM.
  6880. * setAttribute sets an attribute on some element.
  6881. * setDraggable sets whether or not some element should be draggable.
  6882. * setDragScope sets the drag scope for a given element.
  6883. * setOffset sets the offset of some element.
  6884. */
  6885. (function() {
  6886. if (!Array.prototype.indexOf) {
  6887. Array.prototype.indexOf = function( v, b, s ) {
  6888. for( var i = +b || 0, l = this.length; i < l; i++ ) {
  6889. if( this[i]===v || s && this[i]==v ) { return i; }
  6890. }
  6891. return -1;
  6892. };
  6893. }
  6894. var Y;
  6895. YUI().use('node', 'dd', 'anim', 'node-event-simulate', function(_Y) {
  6896. Y = _Y;
  6897. Y.on("domready", function() { jsPlumb.init(); });
  6898. });
  6899. /**
  6900. * adds the given value to the given list, with the given scope. creates the scoped list
  6901. * if necessary.
  6902. * used by initDraggable and initDroppable.
  6903. */
  6904. var _add = function(list, scope, value) {
  6905. var l = list[scope];
  6906. if (!l) {
  6907. l = [];
  6908. list[scope] = l;
  6909. }
  6910. l.push(value);
  6911. },
  6912. ddEvents = [ "drag:mouseDown", "drag:afterMouseDown", "drag:mouseup",
  6913. "drag:align", "drag:removeHandle", "drag:addHandle", "drag:removeInvalid", "drag:addInvalid",
  6914. "drag:start", "drag:end", "drag:drag", "drag:over", "drag:enter",
  6915. "drag:exit", "drag:drophit", "drag:dropmiss", "drop:over", "drop:enter", "drop:exit", "drop:hit"
  6916. ],
  6917. animEvents = [ "tween" ],
  6918. /**
  6919. * helper function to curry callbacks for some element.
  6920. */
  6921. _wrapper = function(fn) {
  6922. return function() {
  6923. try {
  6924. return fn.apply(this, arguments);
  6925. }
  6926. catch (e) {
  6927. alert("YYYYY");
  6928. //console.log("wrap fail", e);
  6929. }
  6930. };
  6931. },
  6932. /**
  6933. * extracts options from the given options object, leaving out event handlers.
  6934. */
  6935. _getDDOptions = function(options) {
  6936. var o = {};
  6937. for (var i in options) if (ddEvents.indexOf(i) == -1) o[i] = options[i];
  6938. return o;
  6939. },
  6940. /**
  6941. * attaches all event handlers found in options to the given dragdrop object, and registering
  6942. * the given el as the element of interest.
  6943. */
  6944. _attachListeners = function(dd, options, eventList) {
  6945. for (var ev in options) {
  6946. if (eventList.indexOf(ev) != -1) {
  6947. var w = _wrapper(options[ev]);
  6948. dd.on(ev, w);
  6949. }
  6950. }
  6951. },
  6952. _droppables = {},
  6953. _droppableOptions = {},
  6954. _draggablesByScope = {},
  6955. _draggablesById = {},
  6956. _droppableScopesById = {},
  6957. _checkHover = function(el, entering) {
  6958. if (el) {
  6959. var id = el.get("id");
  6960. if (id) {
  6961. var options = _droppableOptions[id];
  6962. if (options) {
  6963. if (options['hoverClass']) {
  6964. if (entering) el.addClass(options['hoverClass']);
  6965. else el.removeClass(options['hoverClass']);
  6966. }
  6967. }
  6968. }
  6969. }
  6970. },
  6971. _lastDragObject = null,
  6972. _extend = function(o1, o2) {
  6973. for (var i in o2)
  6974. o1[i] = o2[i];
  6975. return o1;
  6976. },
  6977. _getAttribute = function(el, attributeId) {
  6978. return el.getAttribute(attributeId);
  6979. },
  6980. _getElementObject = function(el) {
  6981. var eee = null;
  6982. try {
  6983. eee = typeof el == 'string' ? Y.one('#' + el) : el._node ? el : Y.one(el);
  6984. }
  6985. catch(eeee) {
  6986. console.log(eeee);
  6987. }
  6988. return eee;
  6989. };
  6990. jsPlumb.CurrentLibrary = {
  6991. addClass : function(el, clazz) {
  6992. jsPlumb.CurrentLibrary.getElementObject(el).addClass(clazz);
  6993. },
  6994. /**
  6995. * animates the given element.
  6996. */
  6997. animate : function(el, properties, options) {
  6998. var o = _extend({node:el, to:properties}, options);
  6999. var id = _getAttribute(el, "id");
  7000. o["tween"] = jsPlumb.wrap(properties["tween"], function() {
  7001. jsPlumb.repaint(id);
  7002. });
  7003. var a = new Y.Anim(o);
  7004. _attachListeners(a, o, animEvents);
  7005. a.run();
  7006. },
  7007. appendElement : function(child, parent) {
  7008. _getElementObject (parent).append(child);
  7009. },
  7010. /**
  7011. * event binding wrapper.
  7012. */
  7013. bind : function(el, event, callback) {
  7014. _getElementObject(el).on(event, callback);
  7015. },
  7016. dragEvents : {
  7017. "start":"drag:start", "stop":"drag:end", "drag":"drag:drag", "step":"step",
  7018. "over":"drop:enter", "out":"drop:exit", "drop":"drop:hit"
  7019. },
  7020. extend : _extend,
  7021. getAttribute : _getAttribute,
  7022. getClientXY : function(eventObject) {
  7023. return [eventObject.clientX, eventObject.clientY];
  7024. },
  7025. /**
  7026. * takes the args passed to an event function and returns you an object representing that which is being dragged.
  7027. */
  7028. getDragObject : function(eventArgs) {
  7029. // this is a workaround for the unfortunate fact that in YUI3, the 'drop:exit' event does
  7030. // not contain a reference to the drag that just exited. single-threaded js to the
  7031. // rescue: we'll just keep it for ourselves.
  7032. if (eventArgs[0].drag) _lastDragObject = eventArgs[0].drag.el;
  7033. return _lastDragObject;
  7034. },
  7035. getDragScope : function(el) {
  7036. var id = jsPlumb.getId(el);
  7037. var dd = _draggablesById[id];
  7038. return dd.scope;
  7039. },
  7040. getDropScope : function(el) {
  7041. var id = jsPlumb.getId(el);
  7042. return _droppableScopesById[id];
  7043. },
  7044. getElementObject : _getElementObject,
  7045. getOffset : function(el) {
  7046. var o = Y.DOM.getXY(el._node);
  7047. return {left:o[0], top:o[1]};
  7048. },
  7049. getPageXY : function(eventObject) {
  7050. return [eventObject.pageX, eventObject.pageY];
  7051. },
  7052. getParent : function(el) {
  7053. return jsPlumb.CurrentLibrary.getElementObject(el).get("parentNode");
  7054. },
  7055. getScrollLeft : function(el) {
  7056. return 0;
  7057. },
  7058. getScrollTop : function(el) {
  7059. return 0;
  7060. },
  7061. getSelector : function(spec) {
  7062. var s = Y.all(spec);
  7063. return s && s ._nodes ? s._nodes : [];
  7064. },
  7065. getSize : function(el) {
  7066. return [ el._node.offsetWidth, el._node.offsetHeight ];
  7067. },
  7068. getTagName : function(el) {
  7069. var e = jsPlumb.CurrentLibrary.getElementObject(el);
  7070. return e != null && e._node != null ? e._node.tagName : null;
  7071. },
  7072. getUIPosition : function(args) {
  7073. var n = args[0].currentTarget.el._node,
  7074. o = Y.DOM.getXY(n);
  7075. return {left:o[0], top:o[1]};
  7076. },
  7077. hasClass : function(el, clazz) {
  7078. return el.hasClass(clazz);
  7079. },
  7080. initDraggable : function(el, options) {
  7081. var _opts = _getDDOptions(options);
  7082. var id = jsPlumb.getId(el);
  7083. _opts.node = "#" + id;
  7084. var dd = new Y.DD.Drag(_opts);
  7085. dd.el = el;
  7086. var scope = options['scope'] || jsPlumb.Defaults.Scope;
  7087. dd.scope = scope;
  7088. _draggablesById[id] = dd;
  7089. _add(_draggablesByScope, scope, dd);
  7090. _attachListeners(dd, options, ddEvents);
  7091. },
  7092. initDroppable : function(el, options) {
  7093. var _opts = _getDDOptions(options);
  7094. var id = jsPlumb.getId(el);
  7095. _opts.node = "#" + id;
  7096. var dd = new Y.DD.Drop(_opts);
  7097. _droppableOptions[id] = options;
  7098. options = _extend({}, options);
  7099. var scope = options['scope'] || jsPlumb.Defaults.Scope;
  7100. _droppableScopesById[id] = scope;
  7101. options["drop:enter"] = jsPlumb.wrap(options["drop:enter"], function(e) {
  7102. if (e.drag.scope !== scope) return true;
  7103. _checkHover(el, true);
  7104. }, true);
  7105. options["drop:exit"] = jsPlumb.wrap(options["drop:exit"], function(e) {
  7106. _checkHover(el, false);
  7107. });
  7108. options["drop:hit"] = jsPlumb.wrap(options["drop:hit"], function(e) {
  7109. if (e.drag.scope !== scope) return true;
  7110. _checkHover(el, false);
  7111. }, true);
  7112. _attachListeners(dd, options, ddEvents);
  7113. },
  7114. isAlreadyDraggable : function(el) {
  7115. el = _getElementObject(el);
  7116. return el.hasClass("yui3-dd-draggable");
  7117. },
  7118. isDragSupported : function(el) { return true; },
  7119. isDropSupported : function(el) { return true; },
  7120. removeClass : function(el, clazz) {
  7121. jsPlumb.CurrentLibrary.getElementObject(el).removeClass(clazz);
  7122. },
  7123. removeElement : function(el) { _getElementObject(el).remove(); },
  7124. setAttribute : function(el, attributeName, attributeValue) {
  7125. el.setAttribute(attributeName, attributeValue);
  7126. },
  7127. /**
  7128. * sets the draggable state for the given element
  7129. */
  7130. setDraggable : function(el, draggable) {
  7131. var id = jsPlumb.getId(el);
  7132. var dd = _draggablesById[id];
  7133. if (dd) dd.set("lock", !draggable);
  7134. },
  7135. setDragScope : function(el, scope) {
  7136. var id = jsPlumb.getId(el);
  7137. var dd = _draggablesById[id];
  7138. if (dd) dd.scope = scope;
  7139. },
  7140. setOffset : function(el, o) {
  7141. el = _getElementObject(el);
  7142. el.set("top", o.top);
  7143. el.set("left", o.left);
  7144. },
  7145. stopDrag : function() {
  7146. // console.log("stop drag!");
  7147. Y.DD.DDM.stopDrag();
  7148. },
  7149. trigger : function(el, event, originalEvent) {
  7150. originalEvent.stopPropagation();
  7151. _getElementObject(el).simulate(event, {
  7152. pageX:originalEvent.pageX,
  7153. pageY:originalEvent.pageY,
  7154. clientX:originalEvent.clientX,
  7155. clientY:originalEvent.clientY
  7156. });
  7157. },
  7158. /**
  7159. * event unbinding wrapper.
  7160. */
  7161. unbind : function(el, event, callback) {
  7162. _getElementObject(el).detach(event, callback);
  7163. }
  7164. };
  7165. })();(function(){if("undefined"==typeof Math.sgn)Math.sgn=function(a){return 0==a?0:0<a?1:-1};var l={subtract:function(a,b){return{x:a.x-b.x,y:a.y-b.y}},dotProduct:function(a,b){return a.x*b.x+a.y*b.y},square:function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},scale:function(a,b){return{x:a.x*b,y:a.y*b}}},w=Math.pow(2,-65),u=function(a,b){for(var f=[],d=b.length-1,h=2*d-1,g=[],c=[],k=[],i=[],m=[[1,0.6,0.3,0.1],[0.4,0.6,0.6,0.4],[0.1,0.3,0.6,1]],e=0;e<=d;e++)g[e]=l.subtract(b[e],a);for(e=0;e<=d-1;e++)c[e]=l.subtract(b[e+
  7166. 1],b[e]),c[e]=l.scale(c[e],3);for(e=0;e<=d-1;e++)for(var n=0;n<=d;n++)k[e]||(k[e]=[]),k[e][n]=l.dotProduct(c[e],g[n]);for(e=0;e<=h;e++)i[e]||(i[e]=[]),i[e].y=0,i[e].x=parseFloat(e)/h;h=d-1;for(g=0;g<=d+h;g++){e=Math.max(0,g-h);for(c=Math.min(g,d);e<=c;e++)j=g-e,i[e+j].y+=k[j][e]*m[j][e]}d=b.length-1;i=q(i,2*d-1,f,0);h=l.subtract(a,b[0]);k=l.square(h);for(e=m=0;e<i;e++)h=l.subtract(a,r(b,d,f[e],null,null)),h=l.square(h),h<k&&(k=h,m=f[e]);h=l.subtract(a,b[d]);h=l.square(h);h<k&&(k=h,m=1);return{location:m,
  7167. distance:k}},q=function(a,b,f,d){var h=[],g=[],c=[],k=[],i=0,m,e;e=Math.sgn(a[0].y);for(var n=1;n<=b;n++)m=Math.sgn(a[n].y),m!=e&&i++,e=m;switch(i){case 0:return 0;case 1:if(64<=d)return f[0]=(a[0].x+a[b].x)/2,1;var o,i=a[0].y-a[b].y;m=a[b].x-a[0].x;e=a[0].x*a[b].y-a[b].x*a[0].y;n=max_distance_below=0;for(o=1;o<b;o++){var l=i*a[o].x+m*a[o].y+e;l>n?n=l:l<max_distance_below&&(max_distance_below=l)}o=m;n=(1*(e-n)-0*o)*(1/(0*o-1*i));o=m;i=(1*(e-max_distance_below)-0*o)*(1/(0*o-1*i));m=Math.min(n,i);if(Math.max(n,
  7168. i)-m<w)return c=a[b].x-a[0].x,k=a[b].y-a[0].y,f[0]=0+1*(c*(a[0].y-0)-k*(a[0].x-0))*(1/(0*c-1*k)),1}r(a,b,0.5,h,g);a=q(h,b,c,d+1);b=q(g,b,k,d+1);for(d=0;d<a;d++)f[d]=c[d];for(d=0;d<b;d++)f[d+a]=k[d];return a+b},r=function(a,b,f,d,h){for(var g=[[]],c=0;c<=b;c++)g[0][c]=a[c];for(a=1;a<=b;a++)for(c=0;c<=b-a;c++)g[a]||(g[a]=[]),g[a][c]||(g[a][c]={}),g[a][c].x=(1-f)*g[a-1][c].x+f*g[a-1][c+1].x,g[a][c].y=(1-f)*g[a-1][c].y+f*g[a-1][c+1].y;if(null!=d)for(c=0;c<=b;c++)d[c]=g[c][0];if(null!=h)for(c=0;c<=b;c++)h[c]=
  7169. g[b-c][c];return g[b][0]},v={},x=function(a){var b=v[a];if(!b){var b=[],f=function(a){return function(){return a}},d=function(){return function(a){return a}},h=function(){return function(a){return 1-a}},g=function(a){return function(b){for(var c=1,d=0;d<a.length;d++)c*=a[d](b);return c}};b.push(new function(){return function(b){return Math.pow(b,a)}});for(var c=1;c<a;c++){for(var k=[new f(a)],i=0;i<a-c;i++)k.push(new d);for(i=0;i<c;i++)k.push(new h);b.push(new g(k))}b.push(new function(){return function(b){return Math.pow(1-
  7170. b,a)}});v[a]=b}return b},p=function(a,b){for(var f=x(a.length-1),d=0,h=0,g=0;g<a.length;g++)d+=a[g].x*f[g](b),h+=a[g].y*f[g](b);return{x:d,y:h}},s=function(a,b,f){for(var d=p(a,b),h=0,g=0<f?1:-1,c=null;h<Math.abs(f);)b+=0.005*g,c=p(a,b),h+=Math.sqrt(Math.pow(c.x-d.x,2)+Math.pow(c.y-d.y,2)),d=c;return{point:c,location:b}},t=function(a,b){var f=p(a,b),d=p(a.slice(0,a.length-1),b),h=d.y-f.y,f=d.x-f.x;return 0==h?Infinity:Math.atan(h/f)};window.jsBezier={distanceFromCurve:u,gradientAtPoint:t,gradientAtPointAlongCurveFrom:function(a,
  7171. b,f){b=s(a,b,f);if(1<b.location)b.location=1;if(0>b.location)b.location=0;return t(a,b.location)},nearestPointOnCurve:function(a,b){var f=u(a,b);return{point:r(b,b.length-1,f.location,null,null),location:f.location}},pointOnCurve:p,pointAlongCurveFrom:function(a,b,f){return s(a,b,f).point},perpendicularToCurveAt:function(a,b,f,d){b=s(a,b,null==d?0:d);a=t(a,b.location);d=Math.atan(-1/a);a=f/2*Math.sin(d);f=f/2*Math.cos(d);return[{x:b.point.x+f,y:b.point.y+a},{x:b.point.x-f,y:b.point.y-a}]}}})();