mootools.jsPlumb-1.3.5-all.js 330 KB

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