mootools.jsPlumb-1.3.1-all.js 216 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715
  1. /*
  2. * jsPlumb
  3. *
  4. * Title:jsPlumb 1.3.0
  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 - 2011 Simon Porritt (http://jsplumb.org)
  12. *
  13. * http://jsplumb.org
  14. * http://code.google.com/p/jsPlumb
  15. *
  16. * Triple licensed under the MIT, GPL2 and Beer licenses.
  17. */
  18. ;(function() {
  19. /**
  20. * Class:jsPlumb
  21. * The jsPlumb engine, registered as a static object in the window. This object contains all of the methods you will use to
  22. * create and maintain Connections and Endpoints.
  23. */
  24. var ie = !!!document.createElement('canvas').getContext;
  25. var canvasAvailable = !!document.createElement('canvas').getContext;
  26. var 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. var vmlAvailable = !(canvasAvailable | svgAvailable);
  29. var _findIndex = function(a, v, b, s) {
  30. var _eq = function(o1, o2) {
  31. if (o1 === o2)
  32. 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. /**
  57. * helper method to add an item to a list, creating the list if it does
  58. * not yet exist.
  59. */
  60. var _addToList = function(map, key, value) {
  61. var l = map[key];
  62. if (l == null) {
  63. l = [];
  64. map[key] = l;
  65. }
  66. l.push(value);
  67. return l;
  68. };
  69. var _connectionBeingDragged = null;
  70. var _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); };
  71. var _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); };
  72. var _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); };
  73. var _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); };
  74. var _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); };
  75. var _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); };
  76. var _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); };
  77. var _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); };
  78. var _log = function(jsp, msg) {
  79. if (jsp.logEnabled && typeof console != "undefined")
  80. console.log(msg);
  81. };
  82. /**
  83. * EventGenerator
  84. * Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
  85. */
  86. var EventGenerator = function() {
  87. var _listeners = {}, self = this;
  88. // 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
  89. // jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
  90. // 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"
  91. // event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
  92. // to hear what other people think.
  93. var eventsToDieOn = [ "ready" ];
  94. /*
  95. * Binds a listener to an event.
  96. *
  97. * Parameters:
  98. * event - name of the event to bind to.
  99. * listener - function to execute.
  100. */
  101. this.bind = function(event, listener) {
  102. _addToList(_listeners, event, listener);
  103. };
  104. /*
  105. * Fires an update for the given event.
  106. *
  107. * Parameters:
  108. * event - event to fire
  109. * value - value to pass to the event listener(s).
  110. * o riginalEvent - the original event from the browser
  111. */
  112. this.fire = function(event, value, originalEvent) {
  113. if (_listeners[event]) {
  114. for ( var i = 0; i < _listeners[event].length; i++) {
  115. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  116. // method will have the whole call stack available in the debugger.
  117. if (_findIndex(eventsToDieOn, event) != -1)
  118. _listeners[event][i](value, originalEvent);
  119. else {
  120. // for events we don't want to die on, catch and log.
  121. try {
  122. _listeners[event][i](value, originalEvent);
  123. } catch (e) {
  124. _log("jsPlumb: fire failed for event " + event + " : " + e);
  125. }
  126. }
  127. }
  128. }
  129. };
  130. /*
  131. * Clears either all listeners, or listeners for some specific event.
  132. *
  133. * Parameters:
  134. * event - optional. constrains the clear to just listeners for this event.
  135. */
  136. this.clearListeners = function(event) {
  137. if (event) {
  138. delete _listeners[event];
  139. } else {
  140. delete _listeners;
  141. _listeners = {};
  142. }
  143. };
  144. };
  145. /*
  146. * Class:jsPlumbUIComponent
  147. * Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle,
  148. * and also extends EventGenerator to provide the bind and fire methods.
  149. */
  150. var jsPlumbUIComponent = function(params) {
  151. var self = this, a = arguments, _hover = false;
  152. self._jsPlumb = params["_jsPlumb"];
  153. //self.parent = params["parent"];
  154. // all components can generate events
  155. EventGenerator.apply(this);
  156. // all components get this clone function.
  157. this.clone = function() {
  158. var o = new Object();
  159. self.constructor.apply(o, a);
  160. return o;
  161. };
  162. this.overlayPlacements = [],
  163. this.paintStyle = null,
  164. this.hoverPaintStyle = null;
  165. // helper method to update the hover style whenever it, or paintStyle, changes.
  166. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  167. // top.
  168. var _updateHoverStyle = function() {
  169. if (self.paintStyle && self.hoverPaintStyle) {
  170. var mergedHoverStyle = {};
  171. jsPlumb.extend(mergedHoverStyle, self.paintStyle);
  172. jsPlumb.extend(mergedHoverStyle, self.hoverPaintStyle);
  173. delete self.hoverPaintStyle;
  174. // we want the fillStyle of paintStyle to override a gradient, if possible.
  175. if (mergedHoverStyle.gradient && self.paintStyle.fillStyle)
  176. delete mergedHoverStyle.gradient;
  177. self.hoverPaintStyle = mergedHoverStyle;
  178. }
  179. };
  180. /*
  181. * Sets the paint style and then repaints the element.
  182. *
  183. * Parameters:
  184. * style - Style to use.
  185. */
  186. this.setPaintStyle = function(style, doNotRepaint) {
  187. self.paintStyle = style;
  188. self.paintStyleInUse = self.paintStyle;
  189. _updateHoverStyle();
  190. if (!doNotRepaint) self.repaint();
  191. };
  192. /*
  193. * Sets the paint style to use when the mouse is hovering over the element. This is null by default.
  194. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  195. * it. This is because people will most likely want to change just one thing when hovering, say the
  196. * color for example, but leave the rest of the appearance the same.
  197. *
  198. * Parameters:
  199. * style - Style to use when the mouse is hovering.
  200. * doNotRepaint - if true, the component will not be repainted. useful when setting things up initially.
  201. */
  202. this.setHoverPaintStyle = function(style, doNotRepaint) {
  203. self.hoverPaintStyle = style;
  204. _updateHoverStyle();
  205. if (!doNotRepaint) self.repaint();
  206. };
  207. /*
  208. * sets/unsets the hover state of this element.
  209. *
  210. * Parameters:
  211. * hover - hover state boolean
  212. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  213. */
  214. this.setHover = function(hover, ignoreAttachedElements) {
  215. _hover = hover;
  216. if (self.hoverPaintStyle != null) {
  217. self.paintStyleInUse = hover ? self.hoverPaintStyle : self.paintStyle;
  218. self.repaint();
  219. // get the list of other affected elements. for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  220. if (!ignoreAttachedElements)
  221. _updateAttachedElements(hover);
  222. }
  223. };
  224. this.isHover = function() {
  225. return _hover;
  226. };
  227. this.attachListeners = function(o, c) {
  228. var jpcl = jsPlumb.CurrentLibrary,
  229. events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup" ],
  230. eventFilters = { "mouseout":"mouseexit" },
  231. bindOne = function(evt) {
  232. var filteredEvent = eventFilters[evt] || evt;
  233. jpcl.bind(o, evt, function(ee) {
  234. c.fire(filteredEvent, c, ee);
  235. });
  236. };
  237. for (var i = 0; i < events.length; i++) {
  238. bindOne(events[i]);
  239. }
  240. };
  241. var _updateAttachedElements = function(state) {
  242. var affectedElements = self.getAttachedElements(); // implemented in subclasses
  243. if (affectedElements) {
  244. for (var i = 0; i < affectedElements.length; i++) {
  245. affectedElements[i].setHover(state, true); // tell the attached elements not to inform their own attached elements.
  246. }
  247. }
  248. };
  249. };
  250. var jsPlumbInstance = function(_defaults) {
  251. /*
  252. * Property: Defaults
  253. *
  254. * These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
  255. * to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
  256. * by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
  257. *
  258. * Properties:
  259. * - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
  260. * - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
  261. * - *Connector* The default connector definition to use for all connections. Default is "Bezier".
  262. * - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  263. * - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  264. * - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
  265. * - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
  266. * - *EndpointStyle* The default style definition to use for all endpoints. Default is empty.
  267. * - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
  268. * - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
  269. * - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
  270. * - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
  271. * - *LabelStyle* The default style to use for label overlays on connections.
  272. * - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
  273. * - *Overlays* The default overlay definitions. Defaults to an empty list.
  274. * - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
  275. * - *MouseEventsEnabled* Whether or not mouse events are enabled when using the canvas renderer. Defaults to true.
  276. * 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.
  277. * - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
  278. * - *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.
  279. * - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
  280. */
  281. this.Defaults = {
  282. Anchor : "BottomCenter",
  283. Anchors : [ null, null ],
  284. Connector : "Bezier",
  285. DragOptions : { },
  286. DropOptions : { },
  287. Endpoint : "Dot",
  288. Endpoints : [ null, null ],
  289. EndpointStyle : { fillStyle : null },
  290. EndpointStyles : [ null, null ],
  291. EndpointHoverStyle : null,
  292. EndpointHoverStyles : [ null, null ],
  293. HoverPaintStyle : null,
  294. LabelStyle : { color : "black" },
  295. LogEnabled : false,
  296. Overlays : [ ],
  297. MaxConnections : 1,
  298. MouseEventsEnabled : true,
  299. PaintStyle : { lineWidth : 8, strokeStyle : "#456" },
  300. RenderMode : "canvas",
  301. Scope : "_jsPlumb_DefaultScope"
  302. };
  303. if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
  304. this.logEnabled = this.Defaults.LogEnabled;
  305. EventGenerator.apply(this);
  306. var _bb = this.bind;
  307. this.bind = function(event, fn) {
  308. if ("ready" === event && initialized) fn();
  309. else _bb(event, fn);
  310. };
  311. var _currentInstance = this,
  312. log = null,
  313. repaintFunction = function() {
  314. jsPlumb.repaintEverything();
  315. },
  316. automaticRepaint = true,
  317. repaintEverything = function() {
  318. if (automaticRepaint)
  319. repaintFunction();
  320. },
  321. resizeTimer = null,
  322. initialized = false,
  323. connectionsByScope = {},
  324. /**
  325. * map of element id -> endpoint lists. an element can have an arbitrary
  326. * number of endpoints on it, and not all of them have to be connected
  327. * to anything.
  328. */
  329. endpointsByElement = {},
  330. endpointsByUUID = {},
  331. offsets = {},
  332. offsetTimestamps = {},
  333. floatingConnections = {},
  334. draggableStates = {},
  335. _mouseEventsEnabled = this.Defaults.MouseEventsEnabled,
  336. _draggableByDefault = true,
  337. canvasList = [],
  338. sizes = [],
  339. listeners = {}, // a map: keys are event types, values are lists of listeners.
  340. DEFAULT_SCOPE = this.Defaults.Scope,
  341. renderMode = null, // will be set in init()
  342. /**
  343. * helper method to add an item to a list, creating the list if it does
  344. * not yet exist.
  345. */
  346. _addToList = function(map, key, value) {
  347. var l = map[key];
  348. if (l == null) {
  349. l = [];
  350. map[key] = l;
  351. }
  352. l.push(value);
  353. return l;
  354. },
  355. /**
  356. * appends an element to the given parent, or the document body if no
  357. * parent given.
  358. */
  359. _appendElement = function(el, parent) {
  360. if (!parent)
  361. document.body.appendChild(el);
  362. else
  363. jsPlumb.CurrentLibrary.appendElement(el, parent);
  364. },
  365. /**
  366. * creates a timestamp, using milliseconds since 1970, but as a string.
  367. */
  368. _timestamp = function() { return "" + (new Date()).getTime(); },
  369. /**
  370. * YUI, for some reason, put the result of a Y.all call into an object that contains
  371. * a '_nodes' array, instead of handing back an array-like object like the other
  372. * libraries do.
  373. */
  374. _convertYUICollection = function(c) {
  375. return c._nodes ? c._nodes : c;
  376. },
  377. /**
  378. * Draws an endpoint and its connections.
  379. *
  380. * @param element element to draw (of type library specific element object)
  381. * @param ui UI object from current library's event system. optional.
  382. * @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  383. */
  384. _draw = function(element, ui, timestamp) {
  385. var id = _getAttribute(element, "id");
  386. var endpoints = endpointsByElement[id];
  387. if (!timestamp) timestamp = _timestamp();
  388. if (endpoints) {
  389. _updateOffset( { elId : id, offset : ui, recalc : false, timestamp : timestamp }); // timestamp is checked against last update cache; it is
  390. // valid for one paint cycle.
  391. var myOffset = offsets[id], myWH = sizes[id];
  392. for ( var i = 0; i < endpoints.length; i++) {
  393. endpoints[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  394. var l = endpoints[i].connections;
  395. for ( var j = 0; j < l.length; j++) {
  396. l[j].paint( { elId : id, ui : ui, recalc : false, timestamp : timestamp }); // ...paint each connection.
  397. // then, check for dynamic endpoint; need to repaint it.
  398. var oIdx = l[j].endpoints[0] == endpoints[i] ? 1 : 0;
  399. if (l[j].endpoints[oIdx].anchor.isDynamic && !l[j].endpoints[oIdx].isFloating()) {
  400. var oId = oIdx == 0 ? l[j].sourceId : l[j].targetId,
  401. oOffset = offsets[oId], oWH = sizes[oId],
  402. // TODO i still want to make this faster.
  403. anchorLoc = l[j].endpoints[oIdx].anchor.compute( {
  404. xy : [ oOffset.left, oOffset.top ],
  405. wh : oWH,
  406. element : l[j].endpoints[oIdx],
  407. txy : [ myOffset.left, myOffset.top ],
  408. twh : myWH,
  409. tElement : endpoints[i]
  410. });
  411. l[j].endpoints[oIdx].paint({ anchorLoc : anchorLoc });
  412. }
  413. }
  414. }
  415. }
  416. },
  417. /**
  418. * executes the given function against the given element if the first
  419. * argument is an object, or the list of elements, if the first argument
  420. * is a list. the function passed in takes (element, elementId) as
  421. * arguments.
  422. */
  423. _elementProxy = function(element, fn) {
  424. var retVal = null;
  425. if (element.constructor == Array) {
  426. retVal = [];
  427. for ( var i = 0; i < element.length; i++) {
  428. var el = _getElementObject(element[i]), id = _getAttribute(el, "id");
  429. retVal.push(fn(el, id)); // append return values to what we will return
  430. }
  431. } else {
  432. var el = _getElementObject(element), id = _getAttribute(el, "id");
  433. retVal = fn(el, id);
  434. }
  435. return retVal;
  436. },
  437. /**
  438. * gets an Endpoint by uuid.
  439. */
  440. _getEndpoint = function(uuid) { return endpointsByUUID[uuid]; },
  441. /**
  442. * inits a draggable if it's not already initialised.
  443. */
  444. _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  445. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  446. if (draggable) {
  447. if (jsPlumb.CurrentLibrary.isDragSupported(element) && !jsPlumb.CurrentLibrary.isAlreadyDraggable(element)) {
  448. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  449. options = jsPlumb.extend( {}, options); // make a copy.
  450. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  451. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  452. options[dragEvent] = _wrap(options[dragEvent], function() {
  453. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  454. _draw(element, ui);
  455. _addClass(element, "jsPlumb_dragged");
  456. });
  457. options[stopEvent] = _wrap(options[stopEvent], function() {
  458. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  459. _draw(element, ui);
  460. _removeClass(element, "jsPlumb_dragged");
  461. });
  462. var draggable = draggableStates[_getId(element)];
  463. options.disabled = draggable == null ? false : !draggable;
  464. jsPlumb.CurrentLibrary.initDraggable(element, options);
  465. }
  466. }
  467. },
  468. _newConnection = function(params) {
  469. var connectionFunc = jsPlumb.Defaults.ConnectionType || Connection,
  470. endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint,
  471. parent = jsPlumb.CurrentLibrary.getParent;
  472. if (params.sourceEndpoint)
  473. params["parent"] = params.sourceEndpoint.parent;
  474. else if (params.source.constructor == endpointFunc)
  475. params["parent"] = params.source.parent;
  476. else params["parent"] = parent(params.source);
  477. params["_jsPlumb"] = _currentInstance;
  478. var con = new connectionFunc(params);
  479. _eventFireProxy("click", "click", con);
  480. _eventFireProxy("dblclick", "dblclick", con);
  481. return con;
  482. },
  483. _eventFireProxy = function(event, proxyEvent, obj) {
  484. obj.bind(event, function(e) {
  485. _currentInstance.fire(proxyEvent, obj, e);
  486. });
  487. },
  488. _newEndpoint = function(params) {
  489. var endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint;
  490. params["parent"] = jsPlumb.CurrentLibrary.getParent(params.source);
  491. params["_jsPlumb"] = _currentInstance,
  492. ep = new endpointFunc(params);
  493. _eventFireProxy("click", "endpointClick", ep);
  494. _eventFireProxy("dblclick", "endpointDblClick", ep);
  495. return ep;
  496. },
  497. /**
  498. * performs the given function operation on all the connections found
  499. * for the given element id; this means we find all the endpoints for
  500. * the given element, and then for each endpoint find the connectors
  501. * connected to it. then we pass each connection in to the given
  502. * function.
  503. */
  504. _operation = function(elId, func) {
  505. var endpoints = endpointsByElement[elId];
  506. if (endpoints && endpoints.length) {
  507. for ( var i = 0; i < endpoints.length; i++) {
  508. for ( var j = 0; j < endpoints[i].connections.length; j++) {
  509. var retVal = func(endpoints[i].connections[j]);
  510. // if the function passed in returns true, we exit.
  511. // most functions return false.
  512. if (retVal) return;
  513. }
  514. }
  515. }
  516. },
  517. /**
  518. * perform an operation on all elements.
  519. */
  520. _operationOnAll = function(func) {
  521. for ( var elId in endpointsByElement) {
  522. _operation(elId, func);
  523. }
  524. },
  525. /**
  526. * helper to remove an element from the DOM.
  527. */
  528. _removeElement = function(element, parent) {
  529. if (element != null && element.parentNode != null) {
  530. element.parentNode.removeChild(element);
  531. }
  532. },
  533. /**
  534. * helper to remove a list of elements from the DOM.
  535. */
  536. _removeElements = function(elements, parent) {
  537. for ( var i = 0; i < elements.length; i++)
  538. _removeElement(elements[i], parent);
  539. },
  540. /**
  541. * helper method to remove an item from a list.
  542. */
  543. _removeFromList = function(map, key, value) {
  544. if (key != null) {
  545. var l = map[key];
  546. if (l != null) {
  547. var i = _findIndex(l, value);
  548. if (i >= 0) {
  549. delete (l[i]);
  550. l.splice(i, 1);
  551. return true;
  552. }
  553. }
  554. }
  555. return false;
  556. },
  557. /**
  558. * Sets whether or not the given element(s) should be draggable,
  559. * regardless of what a particular plumb command may request.
  560. *
  561. * @param element
  562. * May be a string, a element objects, or a list of
  563. * strings/elements.
  564. * @param draggable
  565. * Whether or not the given element(s) should be draggable.
  566. */
  567. _setDraggable = function(element, draggable) {
  568. return _elementProxy(element, function(el, id) {
  569. draggableStates[id] = draggable;
  570. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  571. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  572. }
  573. });
  574. },
  575. /**
  576. * private method to do the business of hiding/showing.
  577. *
  578. * @param el
  579. * either Id of the element in question or a library specific
  580. * object for the element.
  581. * @param state
  582. * String specifying a value for the css 'display' property
  583. * ('block' or 'none').
  584. */
  585. _setVisible = function(el, state) {
  586. _operation(_getAttribute(el, "id"), function(jpc) {
  587. jpc.canvas.style.display = state;
  588. });
  589. },
  590. /**
  591. * toggles the draggable state of the given element(s).
  592. *
  593. * @param el
  594. * either an id, or an element object, or a list of
  595. * ids/element objects.
  596. */
  597. _toggleDraggable = function(el) {
  598. return _elementProxy(el, function(el, elId) {
  599. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  600. state = !state;
  601. draggableStates[elId] = state;
  602. jsPlumb.CurrentLibrary.setDraggable(el, state);
  603. return state;
  604. });
  605. },
  606. /**
  607. * private method to do the business of toggling hiding/showing.
  608. *
  609. * @param elId
  610. * Id of the element in question
  611. */
  612. _toggleVisible = function(elId) {
  613. _operation(elId, function(jpc) {
  614. var state = ('none' == jpc.canvas.style.display);
  615. jpc.canvas.style.display = state ? "block" : "none";
  616. });
  617. // todo this should call _elementProxy, and pass in the
  618. // _operation(elId, f) call as a function. cos _toggleDraggable does
  619. // that.
  620. },
  621. /**
  622. * updates the offset and size for a given element, and stores the
  623. * values. if 'offset' is not null we use that (it would have been
  624. * passed in from a drag call) because it's faster; but if it is null,
  625. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  626. */
  627. _updateOffset = function(params) {
  628. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId;
  629. if (!recalc) {
  630. if (timestamp && timestamp === offsetTimestamps[elId])
  631. return offsets[elId];
  632. }
  633. if (recalc || offset == null) { // if forced repaint or no offset
  634. // available, we recalculate.
  635. // get the current size and offset, and store them
  636. var s = _getElementObject(elId);
  637. if (s != null) {
  638. sizes[elId] = _getSize(s);
  639. offsets[elId] = _getOffset(s);
  640. offsetTimestamps[elId] = timestamp;
  641. }
  642. } else {
  643. offsets[elId] = offset;
  644. }
  645. return offsets[elId];
  646. },
  647. /**
  648. * gets an id for the given element, creating and setting one if
  649. * necessary.
  650. */
  651. _getId = function(element, uuid) {
  652. var ele = _getElementObject(element);
  653. var id = _getAttribute(ele, "id");
  654. if (!id || id == "undefined") {
  655. // check if fixed uuid parameter is given
  656. if (arguments.length == 2 && arguments[1] != undefined)
  657. id = uuid;
  658. else
  659. id = "jsPlumb_" + _timestamp();
  660. _setAttribute(ele, "id", id);
  661. }
  662. return id;
  663. },
  664. /**
  665. * wraps one function with another, creating a placeholder for the
  666. * wrapped function if it was null. this is used to wrap the various
  667. * drag/drop event functions - to allow jsPlumb to be notified of
  668. * important lifecycle events without imposing itself on the user's
  669. * drag/drop functionality. TODO: determine whether or not we should
  670. * support an error handler concept, if one of the functions fails.
  671. *
  672. * @param wrappedFunction original function to wrap; may be null.
  673. * @param newFunction function to wrap the original with.
  674. * @param returnOnThisValue Optional. Indicates that the wrappedFunction should
  675. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  676. * note that this is a simple comparison and only works for primitives right now.
  677. */
  678. _wrap = function(wrappedFunction, newFunction, returnOnThisValue) {
  679. wrappedFunction = wrappedFunction || function() { };
  680. newFunction = newFunction || function() { };
  681. return function() {
  682. var r = null;
  683. try {
  684. r = newFunction.apply(this, arguments);
  685. } catch (e) {
  686. _log(_currentInstance, 'jsPlumb function failed : ' + e);
  687. }
  688. if (returnOnThisValue == null || (r !== returnOnThisValue)) {
  689. try {
  690. wrappedFunction.apply(this, arguments);
  691. } catch (e) {
  692. _log(_currentInstance, 'wrapped function failed : ' + e);
  693. }
  694. }
  695. return r;
  696. };
  697. };
  698. /*
  699. * Property: connectorClass
  700. * 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.
  701. */
  702. this.connectorClass = "_jsPlumb_connector";
  703. /*
  704. * Property: endpointClass
  705. * 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.
  706. */
  707. this.endpointClass = "_jsPlumb_endpoint";
  708. /*
  709. * Property: overlayClass
  710. * 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.
  711. */
  712. this.overlayClass = "_jsPlumb_overlay";
  713. this.Anchors = {};
  714. this.Connectors = {
  715. "canvas":{},
  716. "svg":{},
  717. "vml":{}
  718. };
  719. this.Endpoints = {
  720. "canvas":{},
  721. "svg":{},
  722. "vml":{}
  723. };
  724. this.Overlays = {
  725. "canvas":{},
  726. "svg":{},
  727. "vml":{}
  728. };
  729. // ************************ PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS *****************************************
  730. /*
  731. * Function: bind
  732. * Bind to an event on jsPlumb.
  733. *
  734. * Parameters:
  735. * event - the event to bind. Available events on jsPlumb are:
  736. * - *jsPlumbConnection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
  737. * - *jsPlumbConnectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
  738. * - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
  739. * - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
  740. * - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
  741. * - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
  742. *
  743. * callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
  744. */
  745. /*
  746. * Function: clearListeners
  747. * Clears either all listeners, or listeners for some specific event.
  748. *
  749. * Parameters:
  750. * event - optional. constrains the clear to just listeners for this event.
  751. */
  752. // *************** END OF PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS ***********************************************************
  753. /*
  754. Function: addEndpoint
  755. Adds an <Endpoint> to a given element or elements.
  756. Parameters:
  757. el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  758. params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
  759. referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
  760. shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
  761. this object are anything that 'params' can contain. See <Endpoint>.
  762. Returns:
  763. The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
  764. See Also:
  765. <addEndpoints>
  766. */
  767. this.addEndpoint = function(el, params, referenceParams) {
  768. referenceParams = referenceParams || {};
  769. var p = jsPlumb.extend({}, referenceParams);
  770. jsPlumb.extend(p, params);
  771. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
  772. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  773. // YUI wrapper
  774. el = _convertYUICollection(el);
  775. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  776. for (var i = 0; i < inputs.length; i++) {
  777. var _el = _getElementObject(inputs[i]), id = _getId(_el);
  778. p.source = _el;
  779. _updateOffset({ elId : id });
  780. var e = _newEndpoint(p);
  781. _addToList(endpointsByElement, id, e);
  782. var myOffset = offsets[id], myWH = sizes[id];
  783. var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e });
  784. e.paint({ anchorLoc : anchorLoc });
  785. results.push(e);
  786. }
  787. return results.length == 1 ? results[0] : results;
  788. };
  789. /*
  790. Function: addEndpoints
  791. Adds a list of <Endpoint>s to a given element or elements.
  792. Parameters:
  793. target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  794. endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
  795. 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.
  796. Returns:
  797. List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
  798. See Also:
  799. <addEndpoint>
  800. */
  801. this.addEndpoints = function(el, endpoints, referenceParams) {
  802. var results = [];
  803. for ( var i = 0; i < endpoints.length; i++) {
  804. var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
  805. if (e.constructor == Array)
  806. Array.prototype.push.apply(results, e);
  807. else results.push(e);
  808. }
  809. return results;
  810. };
  811. /*
  812. Function: animate
  813. This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
  814. 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
  815. 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.
  816. Parameters:
  817. el - Element to animate. Either an id, or a selector representing the element.
  818. properties - The 'properties' argument you want passed to the library's animate call.
  819. options - The 'options' argument you want passed to the library's animate call.
  820. Returns:
  821. void
  822. */
  823. this.animate = function(el, properties, options) {
  824. var ele = _getElementObject(el), id = _getAttribute(el, "id");
  825. options = options || {};
  826. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  827. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  828. options[stepFunction] = _wrap(options[stepFunction], function() {
  829. _currentInstance.repaint(id);
  830. });
  831. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  832. options[completeFunction] = _wrap(options[completeFunction],
  833. function() {
  834. _currentInstance.repaint(id);
  835. });
  836. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  837. };
  838. /*
  839. Function: connect
  840. Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
  841. Parameters:
  842. params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
  843. referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
  844. Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
  845. Returns:
  846. The newly created <Connection>.
  847. */
  848. this.connect = function(params, referenceParams) {
  849. var _p = jsPlumb.extend( {}, params);
  850. if (referenceParams) jsPlumb.extend(_p, referenceParams);
  851. if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source;
  852. if (_p.source && _p.target.endpoint) _p.targetEndpoint = _p.target;
  853. // test for endpoint uuids to connect
  854. if (params.uuids) {
  855. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  856. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  857. }
  858. // now ensure that if we do have Endpoints already, they're not full.
  859. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  860. _log(_currentInstance, "could not add connection; source endpoint is full");
  861. return;
  862. }
  863. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  864. _log(_currentInstance, "could not add connection; target endpoint is full");
  865. return;
  866. }
  867. // dynamic anchors. backwards compatibility here: from 1.2.6 onwards you don't need to specify "dynamicAnchors". the fact that some anchor consists
  868. // of multiple definitions is enough to tell jsPlumb you want it to be dynamic.
  869. if (_p.dynamicAnchors) {
  870. // these can either be an array of anchor coords, which we will use for both source and target, or an object with {source:[anchors], target:[anchors]}, in which
  871. // case we will use a different set for each element.
  872. var a = _p.dynamicAnchors.constructor == Array;
  873. var sa = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.source));
  874. var ta = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.target));
  875. _p.anchors = [sa,ta];
  876. }
  877. var jpc = _newConnection(_p);
  878. // add to list of connections (by scope).
  879. _addToList(connectionsByScope, jpc.scope, jpc);
  880. // fire an event
  881. _currentInstance.fire("jsPlumbConnection", {
  882. connection:jpc,
  883. source : jpc.source, target : jpc.target,
  884. sourceId : jpc.sourceId, targetId : jpc.targetId,
  885. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  886. });
  887. // force a paint
  888. _draw(jpc.source);
  889. return jpc;
  890. };
  891. /*
  892. Function: deleteEndpoint
  893. Deletes an Endpoint and removes all Connections it has (which removes the Connections from the other Endpoints involved too)
  894. Parameters:
  895. object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
  896. Returns:
  897. void
  898. */
  899. this.deleteEndpoint = function(object) {
  900. var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object;
  901. if (endpoint) {
  902. var uuid = endpoint.getUuid();
  903. if (uuid) endpointsByUUID[uuid] = null;
  904. endpoint.detachAll();
  905. _removeElement(endpoint.canvas, endpoint.parent);
  906. // remove from endpointsbyElement
  907. for (var e in endpointsByElement) {
  908. var endpoints = endpointsByElement[e];
  909. if (endpoints) {
  910. var newEndpoints = [];
  911. for (var i = 0; i < endpoints.length; i++)
  912. if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
  913. endpointsByElement[e] = newEndpoints;
  914. }
  915. }
  916. delete endpoint;
  917. }
  918. };
  919. /*
  920. Function: deleteEveryEndpoint
  921. Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
  922. between this method and jsPlumb.reset).
  923. Returns:
  924. void
  925. */
  926. this.deleteEveryEndpoint = function() {
  927. for ( var id in endpointsByElement) {
  928. var endpoints = endpointsByElement[id];
  929. if (endpoints && endpoints.length) {
  930. for ( var i = 0; i < endpoints.length; i++) {
  931. _currentInstance.deleteEndpoint(endpoints[i]);
  932. }
  933. }
  934. }
  935. delete endpointsByElement;
  936. endpointsByElement = {};
  937. delete endpointsByUUID;
  938. endpointsByUUID = {};
  939. };
  940. var fireDetachEvent = function(jpc) {
  941. _currentInstance.fire("jsPlumbConnectionDetached", {
  942. connection:jpc,
  943. source : jpc.source, target : jpc.target,
  944. sourceId : jpc.sourceId, targetId : jpc.targetId,
  945. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  946. });
  947. };
  948. /*
  949. Function: detach
  950. Detaches and then removes a <Connection>. Takes either (source, target) (the old way, maintained for backwards compatibility), or a params
  951. object with various possible values.
  952. Parameters:
  953. source - id or element object of the first element in the Connection.
  954. target - id or element object of the second element in the Connection.
  955. params - a JS object containing the same parameters as you pass to jsPlumb.connect. If this is present then neither source nor
  956. target should be present; it should be the only argument to the method. See the docs for <Connection>'s constructor for information
  957. about the parameters allowed in the params object.
  958. Returns:
  959. true if successful, false if not.
  960. */
  961. this.detach = function(source, target) {
  962. if (arguments.length == 2) {
  963. var s = _getElementObject(source), sId = _getId(s);
  964. var t = _getElementObject(target), tId = _getId(t);
  965. _operation(sId, function(jpc) {
  966. if ((jpc.sourceId == sId && jpc.targetId == tId) || (jpc.targetId == sId && jpc.sourceId == tId)) {
  967. _removeElements(jpc.connector.getDisplayElements(), jpc.parent);
  968. jpc.endpoints[0].removeConnection(jpc);
  969. jpc.endpoints[1].removeConnection(jpc);
  970. _removeFromList(connectionsByScope, jpc.scope, jpc);
  971. }
  972. });
  973. }
  974. // this is the new version of the method, taking a JS object like
  975. // the connect method does.
  976. else if (arguments.length == 1) {
  977. // TODO investigate whether or not this code still works when a user has supplied their own subclass of Connection. i suspect it may not.
  978. if (arguments[0].constructor == Connection) {
  979. arguments[0].endpoints[0].detachFrom(arguments[0].endpoints[1]);
  980. }
  981. else if (arguments[0].connection) {
  982. arguments[0].connection.endpoints[0].detachFrom(arguments[0].connection.endpoints[1]);
  983. }
  984. else {
  985. var _p = jsPlumb.extend( {}, source); // a backwards compatibility hack: source should be thought of as 'params' in this case.
  986. // test for endpoint uuids to detach
  987. if (_p.uuids) {
  988. _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]));
  989. } else if (_p.sourceEndpoint && _p.targetEndpoint) {
  990. _p.sourceEndpoint.detachFrom(_p.targetEndpoint);
  991. } else {
  992. var sourceId = _getId(_p.source);
  993. var targetId = _getId(_p.target);
  994. _operation(sourceId, function(jpc) {
  995. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  996. _removeElements(jpc.connector.getDisplayElements(), jpc.parent);
  997. jpc.endpoints[0].removeConnection(jpc);
  998. jpc.endpoints[1].removeConnection(jpc);
  999. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1000. }
  1001. });
  1002. }
  1003. }
  1004. }
  1005. };
  1006. /*
  1007. Function: detachAll
  1008. Removes all an element's Connections.
  1009. Parameters:
  1010. el - either the id of the element, or a selector for the element.
  1011. Returns:
  1012. void
  1013. */
  1014. this.detachAllConnections = function(el) {
  1015. var id = _getAttribute(el, "id");
  1016. var endpoints = endpointsByElement[id];
  1017. if (endpoints && endpoints.length) {
  1018. for ( var i = 0; i < endpoints.length; i++) {
  1019. endpoints[i].detachAll();
  1020. }
  1021. }
  1022. };
  1023. /**
  1024. * @deprecated Use detachAllConnections instead. this will be removed in jsPlumb 1.3.
  1025. */
  1026. this.detachAll = this.detachAllConnections;
  1027. /*
  1028. Function: detachEveryConnection
  1029. Remove all Connections from all elements, but leaves Endpoints in place.
  1030. Returns:
  1031. void
  1032. See Also:
  1033. <removeEveryEndpoint>
  1034. */
  1035. this.detachEveryConnection = function() {
  1036. for ( var id in endpointsByElement) {
  1037. var endpoints = endpointsByElement[id];
  1038. if (endpoints && endpoints.length) {
  1039. for ( var i = 0; i < endpoints.length; i++) {
  1040. endpoints[i].detachAll();
  1041. }
  1042. }
  1043. }
  1044. delete connectionsByScope;
  1045. connectionsByScope = {};
  1046. };
  1047. /**
  1048. * @deprecated use detachEveryConnection instead. this will be removed in jsPlumb 1.3.
  1049. */
  1050. this.detachEverything = this.detachEveryConnection;
  1051. /*
  1052. Function: draggable
  1053. Initialises the draggability of some element or elements. You should use this instead of you library's draggable method so that jsPlumb can setup the appropriate callbacks. Your underlying library's drag method is always called from this method.
  1054. Parameters:
  1055. el - either an element id, a list of element ids, or a selector.
  1056. options - options to pass through to the underlying library
  1057. Returns:
  1058. void
  1059. */
  1060. this.draggable = function(el, options) {
  1061. if (typeof el == 'object' && el.length) {
  1062. for ( var i = 0; i < el.length; i++) {
  1063. var ele = _getElementObject(el[i]);
  1064. if (ele) _initDraggableIfNecessary(ele, true, options);
  1065. }
  1066. }
  1067. else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced
  1068. // into the library adapters (for jquery and mootools aswell)
  1069. for ( var i = 0; i < el._nodes.length; i++) {
  1070. var ele = _getElementObject(el._nodes[i]);
  1071. if (ele) _initDraggableIfNecessary(ele, true, options);
  1072. }
  1073. }
  1074. else {
  1075. var ele = _getElementObject(el);
  1076. if (ele) _initDraggableIfNecessary(ele, true, options);
  1077. }
  1078. };
  1079. /*
  1080. Function: extend
  1081. Wraps the underlying library's extend functionality.
  1082. Parameters:
  1083. o1 - object to extend
  1084. o2 - object to extend o1 with
  1085. Returns:
  1086. o1, extended with all properties from o2.
  1087. */
  1088. this.extend = function(o1, o2) {
  1089. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1090. };
  1091. /*
  1092. * Function: getDefaultEndpointType
  1093. * Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
  1094. * you would make a call like this in your class's constructor:
  1095. * jsPlumb.getDefaultEndpointType().apply(this, arguments);
  1096. *
  1097. * Returns:
  1098. * the default Endpoint function used by jsPlumb.
  1099. */
  1100. this.getDefaultEndpointType = function() {
  1101. return Endpoint;
  1102. };
  1103. /*
  1104. * Function: getDefaultConnectionType
  1105. * Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
  1106. * you would make a call like this in your class's constructor:
  1107. * jsPlumb.getDefaultConnectionType().apply(this, arguments);
  1108. *
  1109. * Returns:
  1110. * the default Connection function used by jsPlumb.
  1111. */
  1112. this.getDefaultConnectionType = function() {
  1113. return Connection;
  1114. };
  1115. /*
  1116. * Function: getConnections
  1117. * Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
  1118. * 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
  1119. * default scope). If multiple scopes are passed in, the return value will be a map of { scope -> [ connection... ] }.
  1120. *
  1121. * Parameters
  1122. * scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
  1123. * of connections that are in the given scope.
  1124. * options - if the argument is a JS object, you can specify a finer-grained filter:
  1125. *
  1126. * - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes.
  1127. * - *source* either a string representing an element id, or a selector. constrains the result to connections having this source.
  1128. * - *target* either a string representing an element id, or a selector. constrains the result to connections having this target.
  1129. *
  1130. */
  1131. this.getConnections = function(options) {
  1132. if (!options) {
  1133. options = {};
  1134. } else if (options.constructor == String) {
  1135. options = { "scope": options };
  1136. }
  1137. var prepareList = function(input) {
  1138. var r = [];
  1139. if (input) {
  1140. if (typeof input == 'string')
  1141. r.push(input);
  1142. else
  1143. r = input;
  1144. }
  1145. return r;
  1146. };
  1147. var scope = options.scope || jsPlumb.getDefaultScope(),
  1148. scopes = prepareList(scope),
  1149. sources = prepareList(options.source),
  1150. targets = prepareList(options.target),
  1151. filter = function(list, value) {
  1152. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1153. },
  1154. results = scopes.length > 1 ? {} : [],
  1155. _addOne = function(scope, obj) {
  1156. if (scopes.length > 1) {
  1157. var ss = results[scope];
  1158. if (ss == null) {
  1159. ss = []; results[scope] = ss;
  1160. }
  1161. ss.push(obj);
  1162. } else results.push(obj);
  1163. };
  1164. for ( var i in connectionsByScope) {
  1165. if (filter(scopes, i)) {
  1166. for ( var j = 0; j < connectionsByScope[i].length; j++) {
  1167. var c = connectionsByScope[i][j];
  1168. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1169. _addOne(i, c);
  1170. }
  1171. }
  1172. }
  1173. return results;
  1174. };
  1175. /*
  1176. * Function: getAllConnections
  1177. * Gets all connections, as a map of { scope -> [ connection... ] }.
  1178. */
  1179. this.getAllConnections = function() {
  1180. return connectionsByScope;
  1181. };
  1182. /*
  1183. * Function: getDefaultScope
  1184. * Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a
  1185. * scope to an endpoint or connection allows you to support different
  1186. * types of connections in the same UI. but if you're only interested in
  1187. * one type of connection, you don't need to supply a scope. this method
  1188. * will probably be used by very few people; it's good for testing
  1189. * though.
  1190. */
  1191. this.getDefaultScope = function() {
  1192. return DEFAULT_SCOPE;
  1193. };
  1194. /*
  1195. Function: getEndpoint
  1196. Gets an Endpoint by UUID
  1197. Parameters:
  1198. uuid - the UUID for the Endpoint
  1199. Returns:
  1200. Endpoint with the given UUID, null if nothing found.
  1201. */
  1202. this.getEndpoint = _getEndpoint;
  1203. /**
  1204. * Function:getEndpoints
  1205. * Gets the list of Endpoints for a given selector, or element id.
  1206. * @param el
  1207. * @return
  1208. */
  1209. this.getEndpoints = function(el) {
  1210. return endpointsByElement[_getId(el)];
  1211. };
  1212. /*
  1213. * Gets an element's id, creating one if necessary. really only exposed
  1214. * for the lib-specific functionality to access; would be better to pass
  1215. * the current instance into the lib-specific code (even though this is
  1216. * a static call. i just don't want to expose it to the public API).
  1217. */
  1218. this.getId = _getId;
  1219. this.appendElement = _appendElement;
  1220. /*
  1221. Function: hide
  1222. Sets an element's connections to be hidden.
  1223. Parameters:
  1224. el - either the id of the element, or a selector for the element.
  1225. Returns:
  1226. void
  1227. */
  1228. this.hide = function(el) {
  1229. _setVisible(el, "none");
  1230. };
  1231. /**
  1232. * callback from the current library to tell us to prepare ourselves (attach
  1233. * mouse listeners etc; can't do that until the library has provided a bind method)
  1234. * @return
  1235. */
  1236. this.init = function() {
  1237. if (!initialized) {
  1238. _currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run.
  1239. var _bind = function(event) {
  1240. jsPlumb.CurrentLibrary.bind(document, event, function(e) {
  1241. if (!_currentInstance.currentlyDragging && _mouseEventsEnabled && renderMode == jsPlumb.CANVAS) {
  1242. // try connections first
  1243. for (var scope in connectionsByScope) {
  1244. var c = connectionsByScope[scope];
  1245. for (var i = 0; i < c.length; i++) {
  1246. var t = c[i].connector[event](e);
  1247. if (t) return;
  1248. }
  1249. }
  1250. for (var el in endpointsByElement) {
  1251. var ee = endpointsByElement[el];
  1252. for (var i = 0; i < ee.length; i++) {
  1253. if (ee[i].endpoint[event](e)) return;
  1254. }
  1255. }
  1256. }
  1257. });
  1258. };
  1259. _bind("click");
  1260. _bind("dblclick");
  1261. _bind("mousemove");
  1262. _bind("mousedown");
  1263. _bind("mouseup");
  1264. initialized = true;
  1265. _currentInstance.fire("ready");
  1266. }
  1267. };
  1268. this.jsPlumbUIComponent = jsPlumbUIComponent;
  1269. this.EventGenerator = EventGenerator;
  1270. /*
  1271. * Creates an anchor with the given params.
  1272. *
  1273. * You do not need to use this method. It is exposed because of the way jsPlumb is
  1274. * split into three scripts; this will change in the future.
  1275. *
  1276. * x - the x location of the anchor as a fraction of the
  1277. * total width. y - the y location of the anchor as a fraction of the
  1278. * total height. xOrientation - value indicating the general direction a
  1279. * connection from the anchor should go in, in the x direction.
  1280. * yOrientation - value indicating the general direction a connection
  1281. * from the anchor should go in, in the y direction. xOffset - a fixed
  1282. * offset that should be applied in the x direction that should be
  1283. * applied after the x position has been figured out. optional. defaults
  1284. * to 0. yOffset - a fixed offset that should be applied in the y
  1285. * direction that should be applied after the y position has been
  1286. * figured out. optional. defaults to 0.
  1287. * -- OR --
  1288. *
  1289. * params - {x:..., y:..., xOrientation etc }
  1290. * -- OR FROM 1.2.4 ---
  1291. *
  1292. * name - the name of some Anchor in the _currentInstance.Anchors array.
  1293. * -- OR FROM 1.2.4 ---
  1294. *
  1295. * coords - a list of coords for the anchor, like you would pass to
  1296. * jsPlumb.makeAnchor (eg [0.5,0.5,0,-1] - an anchor in the center of
  1297. * some element, oriented towards the top of the screen)
  1298. * -- OR FROM 1.2.4 ---
  1299. *
  1300. * anchor - an existing anchor. just gets passed back. it's handy
  1301. * internally to have this functionality.
  1302. *
  1303. * Returns: The newly created Anchor.
  1304. */
  1305. this.makeAnchor = function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1306. // backwards compatibility here. we used to require an object passed
  1307. // in but that makes the call very verbose. easier to use
  1308. // by just passing in four/six values. but for backwards
  1309. // compatibility if we are given only one value we assume it's a
  1310. // call in the old form.
  1311. if (arguments.length == 0) return null;
  1312. var params = {};
  1313. if (arguments.length == 1) {
  1314. var specimen = arguments[0];
  1315. // if it appears to be an anchor already...
  1316. if (specimen.compute && specimen.getOrientation) return specimen;
  1317. // is it the name of an anchor type?
  1318. else if (typeof specimen == "string") return _currentInstance.Anchors[arguments[0]]();
  1319. // is it an array of coordinates?
  1320. else if (specimen.constructor == Array) {
  1321. if (specimen[0].constructor == Array || specimen[0].constructor == String)
  1322. return new DynamicAnchor(specimen);
  1323. else
  1324. return jsPlumb.makeAnchor.apply(this, specimen);
  1325. }
  1326. // last we try the backwards compatibility stuff.
  1327. else if (typeof arguments[0] == "object") jsPlumb.extend(params, x);
  1328. } else {
  1329. params = { x : x, y : y };
  1330. if (arguments.length >= 4) params.orientation = [ arguments[2], arguments[3] ];
  1331. if (arguments.length == 6) params.offsets = [ arguments[4], arguments[5] ];
  1332. }
  1333. var a = new Anchor(params);
  1334. a.clone = function() {
  1335. return new Anchor(params);
  1336. };
  1337. return a;
  1338. };
  1339. /**
  1340. * makes a list of anchors from the given list of types or coords, eg
  1341. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  1342. */
  1343. this.makeAnchors = function(types) {
  1344. var r = [];
  1345. for ( var i = 0; i < types.length; i++)
  1346. if (typeof types[i] == "string")
  1347. r.push(_currentInstance.Anchors[types[i]]());
  1348. else if (types[i].constructor == Array)
  1349. r.push(jsPlumb.makeAnchor(types[i]));
  1350. return r;
  1351. };
  1352. /**
  1353. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  1354. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  1355. * not need to provide this - i think).
  1356. */
  1357. this.makeDynamicAnchor = function(anchors, anchorSelector) {
  1358. return new DynamicAnchor(anchors, anchorSelector);
  1359. };
  1360. /**
  1361. * Function: makeTarget
  1362. * Makes some DOM element a Connection target, allowing you to drag connections to it
  1363. * without having to register any Endpoints on it first. When a Connection is established,
  1364. * the endpoint spec that was passed in to this method is used to create a suitable
  1365. * Endpoint (the default will be used if you do not provide one).
  1366. *
  1367. * Parameters:
  1368. * el - string id or element selector for the element to make a target.
  1369. * params - JS object containing parameters:
  1370. * endpoint optional. specification of an endpoint to create when a connection is created.
  1371. * scope optional. scope for the drop zone.
  1372. * dropOptions optional. same stuff as you would pass to dropOptions of an Endpoint definition.
  1373. * deleteEndpointsOnDetach optional, defaults to false. whether or not to delete
  1374. * any Endpoints created by a connection to this target if
  1375. * the connection is subsequently detached. this will not
  1376. * remove Endpoints that have had more Connections attached
  1377. * to them after they were created.
  1378. *
  1379. *
  1380. */
  1381. this.makeTarget = function(el, params, referenceParams) {
  1382. var p = jsPlumb.extend({}, referenceParams);
  1383. jsPlumb.extend(p, params);
  1384. var jpcl = jsPlumb.CurrentLibrary,
  1385. scope = p.scope || _currentInstance.Defaults.Scope,
  1386. deleteEndpointsOnDetach = p.deleteEndpointsOnDetach || false,
  1387. _doOne = function(_el) {
  1388. var dropOptions = jsPlumb.extend({}, p.dropOptions || {});
  1389. var _drop = function() {
  1390. var draggable = _getElementObject(jpcl.getDragObject(arguments)),
  1391. id = _getAttribute(draggable, "dragId"),
  1392. // restore the original scope if necessary (issue 57)
  1393. scope = _getAttribute(draggable, "originalScope");
  1394. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  1395. // get the connection, to then get its endpoint
  1396. var jpc = floatingConnections[id],
  1397. source = jpc.endpoints[0],
  1398. _endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : null,
  1399. // make a new Endpoint
  1400. newEndpoint = jsPlumb.addEndpoint(_el, _endpoint);
  1401. var c = jsPlumb.connect({
  1402. source:source,
  1403. target:newEndpoint,
  1404. scope:scope
  1405. });
  1406. if (deleteEndpointsOnDetach)
  1407. c.endpointToDeleteOnDetach = newEndpoint;
  1408. };
  1409. var dropEvent = jpcl.dragEvents['drop'];
  1410. dropOptions["scope"] = dropOptions["scope"] || scope;
  1411. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop);
  1412. jpcl.initDroppable(_el, dropOptions);
  1413. };
  1414. el = _convertYUICollection(el);
  1415. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  1416. for (var i = 0; i < inputs.length; i++) {
  1417. _doOne(_getElementObject(inputs[i]));
  1418. }
  1419. };
  1420. /**
  1421. * helper method to make a list of elements drop targets.
  1422. * @param els
  1423. * @param params
  1424. * @param referenceParams
  1425. * @return
  1426. */
  1427. this.makeTargets = function(els, params, referenceParams) {
  1428. for ( var i = 0; i < els.length; i++) {
  1429. _currentInstance.makeTarget(els[i], params, referenceParams);
  1430. }
  1431. };
  1432. /*
  1433. Function: repaint
  1434. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1435. Parameters:
  1436. el - either the id of the element or a selector representing the element.
  1437. Returns:
  1438. void
  1439. See Also:
  1440. <repaintEverything>
  1441. */
  1442. this.repaint = function(el) {
  1443. var _processElement = function(el) { _draw(_getElementObject(el)); };
  1444. // support both lists...
  1445. if (typeof el == 'object')
  1446. for ( var i = 0; i < el.length; i++) _processElement(el[i]);
  1447. else // ...and single strings.
  1448. _processElement(el);
  1449. };
  1450. /*
  1451. Function: repaintEverything
  1452. Repaints all connections.
  1453. Returns:
  1454. void
  1455. See Also:
  1456. <repaint>
  1457. */
  1458. this.repaintEverything = function() {
  1459. var timestamp = _timestamp();
  1460. for ( var elId in endpointsByElement) {
  1461. _draw(_getElementObject(elId), null, timestamp);
  1462. }
  1463. };
  1464. /*
  1465. Function: removeAllEndpoints
  1466. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1467. Parameters:
  1468. el - either an element id, or a selector for an element.
  1469. Returns:
  1470. void
  1471. See Also:
  1472. <removeEndpoint>
  1473. */
  1474. this.removeAllEndpoints = function(el) {
  1475. var elId = _getAttribute(el, "id");
  1476. var ebe = endpointsByElement[elId];
  1477. for ( var i in ebe)
  1478. _currentInstance.deleteEndpoint(ebe[i]);
  1479. endpointsByElement[elId] = [];
  1480. };
  1481. /*
  1482. Removes every Endpoint in this instance of jsPlumb.
  1483. @deprecated use deleteEveryEndpoint instead
  1484. */
  1485. this.removeEveryEndpoint = this.deleteEveryEndpoint;
  1486. /*
  1487. Removes the given Endpoint from the given element.
  1488. @deprecated Use jsPlumb.deleteEndpoint instead (and note you dont need to supply the element. it's irrelevant).
  1489. */
  1490. this.removeEndpoint = function(el, endpoint) {
  1491. _currentInstance.deleteEndpoint(endpoint);
  1492. };
  1493. /*
  1494. Function:reset
  1495. Removes all endpoints and connections and clears the listener list. To keep listeners call jsPlumb.deleteEveryEndpoint instead of this.
  1496. */
  1497. this.reset = function() {
  1498. this.deleteEveryEndpoint();
  1499. this.clearListeners();
  1500. };
  1501. /*
  1502. Function: setAutomaticRepaint
  1503. Sets/unsets automatic repaint on window resize.
  1504. Parameters:
  1505. value - whether or not to automatically repaint when the window is resized.
  1506. Returns: void
  1507. */
  1508. this.setAutomaticRepaint = function(value) {
  1509. automaticRepaint = value;
  1510. };
  1511. /*
  1512. * Function: setDefaultScope
  1513. * Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
  1514. * scope to an Endpoint or Connection allows you to support different
  1515. * types of Connections in the same UI. If you're only interested in
  1516. * one type of Connection, you don't need to supply a scope. This method
  1517. * will probably be used by very few people; it just instructs jsPlumb
  1518. * to use a different key for the default scope.
  1519. *
  1520. * Parameters:
  1521. * scope - scope to set as default.
  1522. */
  1523. this.setDefaultScope = function(scope) {
  1524. DEFAULT_SCOPE = scope;
  1525. };
  1526. /*
  1527. * Function: setDraggable
  1528. * Sets whether or not a given element is
  1529. * draggable, regardless of what any jsPlumb command may request.
  1530. *
  1531. * Parameters:
  1532. * el - either the id for the element, or a selector representing the element.
  1533. *
  1534. * Returns:
  1535. * void
  1536. */
  1537. this.setDraggable = _setDraggable;
  1538. /*
  1539. * Function: setDraggableByDefault
  1540. * Sets whether or not elements are draggable by default. Default for this is true.
  1541. *
  1542. * Parameters:
  1543. * draggable - value to set
  1544. *
  1545. * Returns:
  1546. * void
  1547. */
  1548. this.setDraggableByDefault = function(draggable) {
  1549. _draggableByDefault = draggable;
  1550. };
  1551. this.setDebugLog = function(debugLog) {
  1552. log = debugLog;
  1553. };
  1554. /*
  1555. * Function: setRepaintFunction
  1556. * Sets the function to fire when the window size has changed and a repaint was fired.
  1557. *
  1558. * Parameters:
  1559. * f - Function to execute.
  1560. *
  1561. * Returns: void
  1562. */
  1563. this.setRepaintFunction = function(f) {
  1564. repaintFunction = f;
  1565. };
  1566. /*
  1567. * Function: setMouseEventsEnabled
  1568. * Sets whether or not mouse events are enabled. Default is true.
  1569. *
  1570. * Parameters:
  1571. * enabled - whether or not mouse events should be enabled.
  1572. *
  1573. * Returns:
  1574. * void
  1575. */
  1576. this.setMouseEventsEnabled = function(enabled) {
  1577. _mouseEventsEnabled = enabled;
  1578. };
  1579. /*
  1580. * Constant for use with the setRenderMode method
  1581. */
  1582. this.CANVAS = "canvas";
  1583. /*
  1584. * Constant for use with the setRenderMode method
  1585. */
  1586. this.SVG = "svg";
  1587. this.VML = "vml";
  1588. /*
  1589. * Function: setRenderMode
  1590. * Sets render mode: jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that
  1591. * what you asked for is not supported (and that VML is). If you asked for VML but the browser does
  1592. * not support it, jsPlumb uses SVG.
  1593. *
  1594. * Returns:
  1595. * the render mode that jsPlumb set, which of course may be different from that requested.
  1596. */
  1597. this.setRenderMode = function(mode) {
  1598. if (mode)
  1599. mode = mode.toLowerCase();
  1600. else
  1601. return;
  1602. 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");
  1603. // now test we actually have the capability to do this.
  1604. if (mode === jsPlumb.CANVAS && canvasAvailable)
  1605. renderMode = jsPlumb.CANVAS;
  1606. else if (mode === jsPlumb.SVG && svgAvailable)
  1607. renderMode = jsPlumb.SVG;
  1608. else if (vmlAvailable)
  1609. renderMode = jsPlumb.VML;
  1610. return renderMode;
  1611. };
  1612. this.getRenderMode = function() { return renderMode; };
  1613. /*
  1614. * Function: show
  1615. * Sets an element's connections to be visible.
  1616. *
  1617. * Parameters:
  1618. * el - either the id of the element, or a selector for the element.
  1619. *
  1620. * Returns:
  1621. * void
  1622. */
  1623. this.show = function(el) {
  1624. _setVisible(el, "block");
  1625. };
  1626. /*
  1627. * Function: sizeCanvas
  1628. * Helper to size a canvas. You would typically use
  1629. * this when writing your own Connector or Endpoint implementation.
  1630. *
  1631. * Parameters:
  1632. * x - [int] x position for the Canvas origin
  1633. * y - [int] y position for the Canvas origin
  1634. * w - [int] width of the canvas
  1635. * h - [int] height of the canvas
  1636. *
  1637. * Returns:
  1638. * void
  1639. */
  1640. this.sizeCanvas = function(canvas, x, y, w, h) {
  1641. if (canvas) {
  1642. canvas.style.height = h + "px";
  1643. canvas.height = h;
  1644. canvas.style.width = w + "px";
  1645. canvas.width = w;
  1646. canvas.style.left = x + "px";
  1647. canvas.style.top = y + "px";
  1648. }
  1649. };
  1650. /**
  1651. * gets some test hooks. nothing writable.
  1652. */
  1653. this.getTestHarness = function() {
  1654. return {
  1655. endpointsByElement : endpointsByElement,
  1656. endpointCount : function(elId) {
  1657. var e = endpointsByElement[elId];
  1658. return e ? e.length : 0;
  1659. },
  1660. connectionCount : function(scope) {
  1661. scope = scope || DEFAULT_SCOPE;
  1662. var c = connectionsByScope[scope];
  1663. return c ? c.length : 0;
  1664. },
  1665. findIndex : _findIndex,
  1666. getId : _getId,
  1667. makeAnchor:self.makeAnchor,
  1668. makeDynamicAnchor:self.makeDynamicAnchor
  1669. };
  1670. };
  1671. /**
  1672. * Toggles visibility of an element's connections. kept for backwards
  1673. * compatibility
  1674. */
  1675. this.toggle = _toggleVisible;
  1676. /*
  1677. * Function: toggleVisible
  1678. * Toggles visibility of an element's Connections.
  1679. *
  1680. * Parameters:
  1681. * el - either the element's id, or a selector representing the element.
  1682. *
  1683. * Returns:
  1684. * void, but should be updated to return the current state
  1685. */
  1686. // TODO: update this method to return the current state.
  1687. this.toggleVisible = _toggleVisible;
  1688. /*
  1689. * Function: toggleDraggable
  1690. * Toggles draggability (sic?) of an element's Connections.
  1691. *
  1692. * Parameters:
  1693. * el - either the element's id, or a selector representing the element.
  1694. *
  1695. * Returns:
  1696. * The current draggable state.
  1697. */
  1698. this.toggleDraggable = _toggleDraggable;
  1699. /*
  1700. * Function: unload
  1701. * Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element.
  1702. *
  1703. * Returns:
  1704. * void
  1705. */
  1706. this.unload = function() {
  1707. delete endpointsByElement;
  1708. delete endpointsByUUID;
  1709. delete offsets;
  1710. delete sizes;
  1711. delete floatingConnections;
  1712. delete draggableStates;
  1713. delete canvasList;
  1714. };
  1715. /*
  1716. * Helper method to wrap an existing function with one of
  1717. * your own. This is used by the various implementations to wrap event
  1718. * callbacks for drag/drop etc; it allows jsPlumb to be transparent in
  1719. * its handling of these things. If a user supplies their own event
  1720. * callback, for anything, it will always be called.
  1721. */
  1722. this.wrap = _wrap;
  1723. this.addListener = this.bind;
  1724. /**
  1725. * 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
  1726. * 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"),
  1727. * 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
  1728. * creation of Anchors without user intervention.
  1729. */
  1730. var Anchor = function(params) {
  1731. var self = this;
  1732. this.x = params.x || 0;
  1733. this.y = params.y || 0;
  1734. var orientation = params.orientation || [ 0, 0 ];
  1735. var lastTimestamp = null, lastReturnValue = null;
  1736. this.offsets = params.offsets || [ 0, 0 ];
  1737. self.timestamp = null;
  1738. this.compute = function(params) {
  1739. var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
  1740. if (timestamp && timestamp === self.timestamp) {
  1741. return lastReturnValue;
  1742. }
  1743. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  1744. if (element.canvas) {
  1745. var po = element.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(element.canvas.offsetParent);
  1746. lastReturnValue[0] = lastReturnValue[0] - po.left;
  1747. lastReturnValue[1] = lastReturnValue[1] - po.top;
  1748. }
  1749. self.timestamp = timestamp;
  1750. return lastReturnValue;
  1751. };
  1752. this.getOrientation = function() { return orientation; };
  1753. this.equals = function(anchor) {
  1754. if (!anchor) return false;
  1755. var ao = anchor.getOrientation();
  1756. var o = this.getOrientation();
  1757. return this.x == anchor.x && this.y == anchor.y
  1758. && this.offsets[0] == anchor.offsets[0]
  1759. && this.offsets[1] == anchor.offsets[1]
  1760. && o[0] == ao[0] && o[1] == ao[1];
  1761. };
  1762. this.getCurrentLocation = function() { return lastReturnValue; };
  1763. };
  1764. /**
  1765. * An Anchor that floats. its orientation is computed dynamically from
  1766. * its position relative to the anchor it is floating relative to. It is used when creating
  1767. * a connection through drag and drop.
  1768. *
  1769. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  1770. */
  1771. var FloatingAnchor = function(params) {
  1772. // this is the anchor that this floating anchor is referenced to for
  1773. // purposes of calculating the orientation.
  1774. var ref = params.reference;
  1775. // the canvas this refers to.
  1776. var refCanvas = params.referenceCanvas;
  1777. var size = _getSize(_getElementObject(refCanvas));
  1778. // these are used to store the current relative position of our
  1779. // anchor wrt the reference anchor. they only indicate
  1780. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  1781. // values are written by the compute method, and read
  1782. // by the getOrientation method.
  1783. var xDir = 0, yDir = 0;
  1784. // temporary member used to store an orientation when the floating
  1785. // anchor is hovering over another anchor.
  1786. var orientation = null;
  1787. var _lastResult = null;
  1788. this.compute = function(params) {
  1789. var xy = params.xy, element = params.element;
  1790. var 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.
  1791. if (element.canvas) {
  1792. var po = element.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(element.canvas.offsetParent);
  1793. result[0] = result[0] - po.left;
  1794. result[1] = result[1] - po.top;
  1795. }
  1796. _lastResult = result;
  1797. return result;
  1798. };
  1799. this.getOrientation = function() {
  1800. if (orientation) return orientation;
  1801. else {
  1802. var o = ref.getOrientation();
  1803. // here we take into account the orientation of the other
  1804. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  1805. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  1806. return [ Math.abs(o[0]) * xDir * -1,
  1807. Math.abs(o[1]) * yDir * -1 ];
  1808. }
  1809. };
  1810. /**
  1811. * notification the endpoint associated with this anchor is hovering
  1812. * over another anchor; we want to assume that anchor's orientation
  1813. * for the duration of the hover.
  1814. */
  1815. this.over = function(anchor) { orientation = anchor.getOrientation(); };
  1816. /**
  1817. * notification the endpoint associated with this anchor is no
  1818. * longer hovering over another anchor; we should resume calculating
  1819. * orientation as we normally do.
  1820. */
  1821. this.out = function() { orientation = null; };
  1822. this.getCurrentLocation = function() { return _lastResult; };
  1823. };
  1824. /*
  1825. * A DynamicAnchors is an Anchor that contains a list of other Anchors, which it cycles
  1826. * through at compute time to find the one that is located closest to
  1827. * the center of the target element, and returns that Anchor's compute
  1828. * method result. this causes endpoints to follow each other with
  1829. * respect to the orientation of their target elements, which is a useful
  1830. * feature for some applications.
  1831. *
  1832. */
  1833. var DynamicAnchor = function(anchors, anchorSelector) {
  1834. this.isSelective = true;
  1835. this.isDynamic = true;
  1836. var _anchors = [];
  1837. var _convert = function(anchor) { return anchor.constructor == Anchor ? anchor: jsPlumb.makeAnchor(anchor); };
  1838. for (var i = 0; i < anchors.length; i++) _anchors[i] = _convert(anchors[i]);
  1839. this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
  1840. this.getAnchors = function() { return _anchors; };
  1841. var _curAnchor = _anchors.length > 0 ? _anchors[0] : null;
  1842. var _curIndex = _anchors.length > 0 ? 0 : -1;
  1843. this.locked = false;
  1844. var self = this;
  1845. // helper method to calculate the distance between the centers of the two elements.
  1846. var _distance = function(anchor, cx, cy, xy, wh) {
  1847. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
  1848. return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
  1849. };
  1850. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  1851. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  1852. // xy - xy loc of the anchor's element
  1853. // wh - anchor's element's dimensions
  1854. // txy - xy loc of the element of the other anchor in the connection
  1855. // twh - dimensions of the element of the other anchor in the connection.
  1856. // anchors - the list of selectable anchors
  1857. var _anchorSelector = anchorSelector || function(xy, wh, txy, twh, anchors) {
  1858. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  1859. var minIdx = -1, minDist = Infinity;
  1860. for ( var i = 0; i < anchors.length; i++) {
  1861. var d = _distance(anchors[i], cx, cy, xy, wh);
  1862. if (d < minDist) {
  1863. minIdx = i + 0;
  1864. minDist = d;
  1865. }
  1866. }
  1867. return anchors[minIdx];
  1868. };
  1869. this.compute = function(params) {
  1870. var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
  1871. // if anchor is locked or an opposite element was not given, we
  1872. // maintain our state. anchor will be locked
  1873. // if it is the source of a drag and drop.
  1874. if (self.locked || txy == null || twh == null)
  1875. return _curAnchor.compute(params);
  1876. else
  1877. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  1878. _curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
  1879. var pos = _curAnchor.compute(params);
  1880. return pos;
  1881. };
  1882. this.getCurrentLocation = function() {
  1883. var cl = _curAnchor != null ? _curAnchor.getCurrentLocation() : null;
  1884. return cl;
  1885. };
  1886. this.getOrientation = function() { return _curAnchor != null ? _curAnchor.getOrientation() : [ 0, 0 ]; };
  1887. this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
  1888. this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
  1889. };
  1890. /*
  1891. * Class: Connection
  1892. * The connecting line between two Endpoints.
  1893. */
  1894. /*
  1895. * Function: Connection
  1896. * Connection constructor.
  1897. *
  1898. * Parameters:
  1899. * source - either an element id, a selector for an element, or an Endpoint.
  1900. * target - either an element id, a selector for an element, or an Endpoint
  1901. * scope - scope descriptor for this connection. optional.
  1902. * endpoint - Optional. Endpoint definition to use for both ends of the connection.
  1903. * endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  1904. * endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
  1905. * endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  1906. * paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
  1907. * 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).
  1908. * overlays - Optional array of Overlay definitions to appear on this Connection.
  1909. */
  1910. var Connection = function(params) {
  1911. jsPlumbUIComponent.apply(this, arguments);
  1912. // ************** get the source and target and register the connection. *******************
  1913. var self = this;
  1914. var visible = true;
  1915. /**
  1916. Function:isVisible
  1917. Returns whether or not the Connection is currently visible.
  1918. */
  1919. this.isVisible = function() { return visible; };
  1920. /**
  1921. Function: setVisible
  1922. Sets whether or not the Connection should be visible.
  1923. Parameters:
  1924. visible - boolean indicating desired visible state.
  1925. */
  1926. this.setVisible = function(v) {
  1927. visible = v;
  1928. if (self.connector && self.connector.canvas) self.connector.canvas.style.display = v ? "block" : "none";
  1929. };
  1930. var id = new String('_jsplumb_c_' + (new Date()).getTime());
  1931. this.getId = function() { return id; };
  1932. this.parent = params.parent;
  1933. /**
  1934. Property: source
  1935. The source element for this Connection.
  1936. */
  1937. this.source = _getElementObject(params.source);
  1938. /**
  1939. Property:target
  1940. The target element for this Connection.
  1941. */
  1942. this.target = _getElementObject(params.target);
  1943. // sourceEndpoint and targetEndpoint override source/target, if they are present.
  1944. if (params.sourceEndpoint) this.source = params.sourceEndpoint.getElement();
  1945. if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
  1946. /*
  1947. * Property: sourceId
  1948. * Id of the source element in the connection.
  1949. */
  1950. this.sourceId = _getAttribute(this.source, "id");
  1951. /*
  1952. * Property: targetId
  1953. * Id of the target element in the connection.
  1954. */
  1955. this.targetId = _getAttribute(this.target, "id");
  1956. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  1957. /**
  1958. * implementation of abstract method in EventGenerator
  1959. * @return list of attached elements. in our case, a list of Endpoints.
  1960. */
  1961. this.getAttachedElements = function() {
  1962. return self.endpoints;
  1963. };
  1964. /**
  1965. * implementation of abstract method in EventGenerator
  1966. */
  1967. var srcWhenMouseDown = null, targetWhenMouseDown = null;
  1968. this.savePosition = function() {
  1969. srcWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.source));
  1970. targetWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.target));
  1971. };
  1972. /*
  1973. * Property: scope
  1974. * Optional scope descriptor for the connection.
  1975. */
  1976. 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.
  1977. /*
  1978. * Property: endpoints
  1979. * Array of [source, target] Endpoint objects.
  1980. */
  1981. this.endpoints = [];
  1982. this.endpointStyles = [];
  1983. // wrapped the main function to return null if no input given. this lets us cascade defaults properly.
  1984. var _makeAnchor = function(anchorParams) {
  1985. if (anchorParams)
  1986. return jsPlumb.makeAnchor(anchorParams);
  1987. };
  1988. var prepareEndpoint = function(existing, index, params, element, connectorPaintStyle, connectorHoverPaintStyle) {
  1989. if (existing) {
  1990. self.endpoints[index] = existing;
  1991. existing.addConnection(self);
  1992. } else {
  1993. if (!params.endpoints) params.endpoints = [ null, null ];
  1994. var ep = params.endpoints[index]
  1995. || params.endpoint
  1996. || _currentInstance.Defaults.Endpoints[index]
  1997. || jsPlumb.Defaults.Endpoints[index]
  1998. || _currentInstance.Defaults.Endpoint
  1999. || jsPlumb.Defaults.Endpoint;
  2000. if (!params.endpointStyles) params.endpointStyles = [ null, null ];
  2001. if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
  2002. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  2003. // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
  2004. if (es.fillStyle == null && connectorPaintStyle != null)
  2005. es.fillStyle = connectorPaintStyle.strokeStyle;
  2006. // TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
  2007. //*
  2008. if (es.outlineColor == null && connectorPaintStyle != null)
  2009. es.outlineColor = connectorPaintStyle.outlineColor;
  2010. if (es.outlineWidth == null && connectorPaintStyle != null)
  2011. es.outlineWidth = connectorPaintStyle.outlineWidth;
  2012. //*/
  2013. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _currentInstance.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
  2014. // endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
  2015. if (connectorHoverPaintStyle != null) {
  2016. if (ehs == null) ehs = {};
  2017. if (ehs.fillStyle == null) {
  2018. ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
  2019. }
  2020. }
  2021. var a = params.anchors ? params.anchors[index] : _makeAnchor(_currentInstance.Defaults.Anchors[index]) || _makeAnchor(jsPlumb.Defaults.Anchors[index]) || _makeAnchor(_currentInstance.Defaults.Anchor) || _makeAnchor(jsPlumb.Defaults.Anchor);
  2022. var u = params.uuids ? params.uuids[index] : null;
  2023. var e = _newEndpoint( { paintStyle : es, hoverPaintStyle:ehs, endpoint : ep, connections : [ self ], uuid : u, anchor : a, source : element });
  2024. self.endpoints[index] = e;
  2025. if (params.drawEndpoints === false) e.setVisible(false, true, true);
  2026. return e;
  2027. }
  2028. };
  2029. var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source, params.paintStyle, params.hoverPaintStyle);
  2030. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  2031. var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target, params.paintStyle, params.hoverPaintStyle);
  2032. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  2033. // if scope not set, set it to be the scope for the source endpoint.
  2034. if (!this.scope) this.scope = this.endpoints[0].scope;
  2035. /*
  2036. * Function: setConnector
  2037. * Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method - the same
  2038. * thing that you would set as the 'connector' property on a jsPlumb.connect call.
  2039. *
  2040. * Parameters:
  2041. * connector - Connector definition
  2042. */
  2043. this.setConnector = function(connector, doNotRepaint) {
  2044. if (self.connector != null) _removeElements(self.connector.getDisplayElements(), self.parent);
  2045. var connectorArgs = { _jsPlumb:self._jsPlumb, parent:params.parent, cssClass:params.cssClass };
  2046. if (connector.constructor == String)
  2047. this.connector = new jsPlumb.Connectors[renderMode][connector](connectorArgs); // lets you use a string as shorthand.
  2048. else if (connector.constructor == Array)
  2049. this.connector = new jsPlumb.Connectors[renderMode][connector[0]](jsPlumb.extend(connector[1], connectorArgs));
  2050. this.canvas = this.connector.canvas;
  2051. var _mouseDown = false, _mouseWasDown = false, _mouseDownAt = null;
  2052. // add mouse events
  2053. this.connector.bind("click", function(con, e) {
  2054. _mouseWasDown = false;
  2055. self.fire("click", self, e);
  2056. });
  2057. this.connector.bind("dblclick", function(con, e) { _mouseWasDown = false;self.fire("dblclick", self, e); });
  2058. this.connector.bind("mouseenter", function(con, e) {
  2059. if (!self.isHover()) {
  2060. if (_connectionBeingDragged == null) {
  2061. self.setHover(true);
  2062. }
  2063. self.fire("mouseenter", self, e);
  2064. }
  2065. });
  2066. this.connector.bind("mouseexit", function(con, e) {
  2067. if (self.isHover()) {
  2068. if (_connectionBeingDragged == null) {
  2069. self.setHover(false);
  2070. }
  2071. self.fire("mouseexit", self, e);
  2072. }
  2073. });
  2074. this.connector.bind("mousedown", function(con, e) {
  2075. _mouseDown = true;
  2076. _mouseDownAt = jsPlumb.CurrentLibrary.getPageXY(e);
  2077. self.savePosition();
  2078. });
  2079. this.connector.bind("mouseup", function(con, e) {
  2080. _mouseDown = false;
  2081. if (self.connector == _connectionBeingDragged) _connectionBeingDragged = null;
  2082. });
  2083. if (!doNotRepaint) self.repaint();
  2084. };
  2085. /*
  2086. * Property: connector
  2087. * The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
  2088. */
  2089. self.setConnector(this.endpoints[0].connector ||
  2090. this.endpoints[1].connector ||
  2091. params.connector ||
  2092. _currentInstance.Defaults.Connector ||
  2093. jsPlumb.Defaults.Connector, true);
  2094. this.setPaintStyle(this.endpoints[0].connectorStyle ||
  2095. this.endpoints[1].connectorStyle ||
  2096. params.paintStyle ||
  2097. _currentInstance.Defaults.PaintStyle ||
  2098. jsPlumb.Defaults.PaintStyle, true);
  2099. this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
  2100. this.endpoints[1].connectorHoverStyle ||
  2101. params.hoverPaintStyle ||
  2102. _currentInstance.Defaults.HoverPaintStyle ||
  2103. jsPlumb.Defaults.HoverPaintStyle, true);
  2104. this.paintStyleInUse = this.paintStyle;
  2105. /*
  2106. * Property: overlays
  2107. * List of Overlays for this Connection.
  2108. */
  2109. this.overlays = [];
  2110. var _overlays = params.overlays || _currentInstance.Defaults.Overlays;
  2111. if (_overlays) {
  2112. for (var i = 0; i < _overlays.length; i++) {
  2113. var o = _overlays[i], _newOverlay = null, _overlayEvents = null;
  2114. if (o.constructor == Array) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  2115. // there's also a three arg version:
  2116. // ["Arrow", { width:50 }, {location:0.7}]
  2117. // which merges the 3rd arg into the 2nd.
  2118. var type = o[0];
  2119. var p = jsPlumb.CurrentLibrary.extend({connection:self, _jsPlumb:_currentInstance}, o[1]); // make a copy of the object so as not to mess up anyone else's reference...
  2120. if (o.length == 3) jsPlumb.CurrentLibrary.extend(p, o[2]);
  2121. _newOverlay = new jsPlumb.Overlays[renderMode][type](p);
  2122. if (p.events) {
  2123. for (var evt in p.events) {
  2124. _newOverlay.bind(evt, p.events[evt]);
  2125. }
  2126. }
  2127. } else if (o.constructor == String) {
  2128. _newOverlay = new jsPlumb.Overlays[renderMode][o]({connection:self, _jsPlumb:_currentInstance});
  2129. } else {
  2130. _newOverlay = o;
  2131. }
  2132. this.overlays.push(_newOverlay);
  2133. }
  2134. }
  2135. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2136. /*
  2137. * Function: bind
  2138. * Bind to an event on the Connection.
  2139. *
  2140. * Parameters:
  2141. * event - the event to bind. Available events on a Connection are:
  2142. * - *click* : notification that a Connection was clicked.
  2143. * - *dblclick* : notification that a Connection was double clicked.
  2144. * - *mouseenter* : notification that the mouse is over a Connection.
  2145. * - *mouseexit* : notification that the mouse exited a Connection.
  2146. *
  2147. * callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
  2148. */
  2149. /*
  2150. * Function: setPaintStyle
  2151. * Sets the Connection's paint style and then repaints the Connection.
  2152. *
  2153. * Parameters:
  2154. * style - Style to use.
  2155. */
  2156. /*
  2157. * Function: setHoverPaintStyle
  2158. * Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
  2159. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  2160. * it. This is because people will most likely want to change just one thing when hovering, say the
  2161. * color for example, but leave the rest of the appearance the same.
  2162. *
  2163. * Parameters:
  2164. * style - Style to use when the mouse is hovering.
  2165. * doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
  2166. */
  2167. /*
  2168. * Function: setHover
  2169. * Sets/unsets the hover state of this Connection.
  2170. *
  2171. * Parameters:
  2172. * hover - hover state boolean
  2173. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  2174. */
  2175. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2176. /*
  2177. * Function: addOverlay
  2178. * Adds an Overlay to the Connection.
  2179. *
  2180. * Parameters:
  2181. * overlay - Overlay to add.
  2182. */
  2183. this.addOverlay = function(overlay) { self.overlays.push(overlay); };
  2184. /**
  2185. * Function: removeAllOverlays
  2186. * Removes all overlays from the Connection, and then repaints.
  2187. */
  2188. this.removeAllOverlays = function() {
  2189. self.overlays.splice(0, self.overlays.length);
  2190. self.repaint();
  2191. };
  2192. /**
  2193. * Function:removeOverlay
  2194. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  2195. * Parameters:
  2196. * overlayId - id of the overlay to remove.
  2197. */
  2198. this.removeOverlay = function(overlayId) {
  2199. var idx = -1;
  2200. for (var i = 0; i < self.overlays.length; i++) {
  2201. if (overlayId === self.overlays[i].id) {
  2202. idx = i;
  2203. break;
  2204. }
  2205. }
  2206. if (idx != -1) self.overlays.splice(idx, 1);
  2207. };
  2208. /**
  2209. * Function:removeOverlay
  2210. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  2211. * Parameters:
  2212. * overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
  2213. */
  2214. this.removeOverlays = function() {
  2215. for (var i = 0; i < arguments.length; i++)
  2216. self.removeOverlay(arguments[i]);
  2217. };
  2218. // this is a shortcut helper method to let people add a label as
  2219. // overlay.
  2220. this.labelStyle = params.labelStyle || _currentInstance.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;
  2221. this.label = params.label;
  2222. if (this.label) {
  2223. this.overlays.push(new jsPlumb.Overlays[renderMode].Label( {
  2224. cssClass:params.cssClass,
  2225. labelStyle : this.labelStyle,
  2226. label : this.label,
  2227. connection:self,
  2228. _jsPlumb:_currentInstance
  2229. }));
  2230. }
  2231. _updateOffset( { elId : this.sourceId });
  2232. _updateOffset( { elId : this.targetId });
  2233. /*
  2234. * Function: setLabel
  2235. * Sets the Connection's label.
  2236. *
  2237. * Parameters:
  2238. * l - label to set. May be a String or a Function that returns a String.
  2239. */
  2240. this.setLabel = function(l) {
  2241. self.label = l;
  2242. _currentInstance.repaint(self.source);
  2243. };
  2244. // paint the endpoints
  2245. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  2246. var otherOffset = offsets[this.targetId];
  2247. var otherWH = sizes[this.targetId];
  2248. var anchorLoc = this.endpoints[0].anchor.compute( {
  2249. xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
  2250. txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1]
  2251. });
  2252. this.endpoints[0].paint( { anchorLoc : anchorLoc });
  2253. anchorLoc = this.endpoints[1].anchor.compute( {
  2254. xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
  2255. txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0]
  2256. });
  2257. this.endpoints[1].paint({ anchorLoc : anchorLoc });
  2258. /*
  2259. * Paints the Connection. Not exposed for public usage.
  2260. *
  2261. * Parameters:
  2262. * elId - Id of the element that is in motion.
  2263. * ui - current library's event system ui object (present if we came from a drag to get here).
  2264. * recalc - whether or not to recalculate all anchors etc before painting.
  2265. * timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
  2266. */
  2267. this.paint = function(params) {
  2268. params = params || {};
  2269. var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp;
  2270. var fai = self.floatingAnchorIndex;
  2271. // if the moving object is not the source we must transpose the two references.
  2272. var swap = false;
  2273. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  2274. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  2275. var el = swap ? this.target : this.source;
  2276. _updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp });
  2277. _updateOffset( { elId : tId, timestamp : timestamp }); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  2278. var sAnchorP = this.endpoints[sIdx].anchor.getCurrentLocation();
  2279. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  2280. var tAnchorP = this.endpoints[tIdx].anchor.getCurrentLocation();
  2281. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  2282. /* paint overlays*/
  2283. var maxSize = 0;
  2284. for ( var i = 0; i < self.overlays.length; i++) {
  2285. var o = self.overlays[i];
  2286. var s = o.computeMaxSize(self.connector);
  2287. if (s > maxSize)
  2288. maxSize = s;
  2289. }
  2290. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, self.paintStyleInUse.lineWidth, maxSize);
  2291. self.connector.paint(dim, self.paintStyleInUse);
  2292. /* paint overlays*/
  2293. for ( var i = 0; i < self.overlays.length; i++) {
  2294. var o = self.overlays[i];
  2295. self.overlayPlacements[i] = o.draw(self.connector, self.paintStyleInUse, dim);
  2296. }
  2297. };
  2298. /*
  2299. * Function: repaint
  2300. * Repaints the Connection.
  2301. */
  2302. this.repaint = function() {
  2303. this.paint({ elId : this.sourceId, recalc : true });
  2304. };
  2305. _initDraggableIfNecessary(self.source, params.draggable, params.dragOptions);
  2306. _initDraggableIfNecessary(self.target, params.draggable, params.dragOptions);
  2307. // resizing (using the jquery.ba-resize plugin). todo: decide
  2308. // whether to include or not.
  2309. if (this.source.resize) {
  2310. this.source.resize(function(e) {
  2311. jsPlumb.repaint(self.sourceId);
  2312. });
  2313. }
  2314. // just to make sure the UI gets initialised fully on all browsers.
  2315. self.repaint();
  2316. };
  2317. /*
  2318. * Class: Endpoint
  2319. *
  2320. * Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
  2321. * to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
  2322. * actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
  2323. * do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
  2324. * 'target' Endpoints for Connections.
  2325. *
  2326. *
  2327. */
  2328. /*
  2329. * Function: Endpoint
  2330. *
  2331. * Endpoint constructor.
  2332. *
  2333. * Parameters:
  2334. * 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.
  2335. * 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 } ].
  2336. * paintStyle - endpoint style, a js object. may be null.
  2337. * hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
  2338. * source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
  2339. * canvas - canvas element to use. may be, and most often is, null.
  2340. * connections - optional list of Connections to configure the Endpoint with.
  2341. * isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
  2342. * maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
  2343. * dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
  2344. * connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
  2345. * connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
  2346. * 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 } ].
  2347. * connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
  2348. * isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
  2349. * 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.
  2350. * 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.
  2351. */
  2352. var Endpoint = function(params) {
  2353. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  2354. params = params || {};
  2355. var self = this;
  2356. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2357. /*
  2358. * Function: bind
  2359. * Bind to an event on the Endpoint.
  2360. *
  2361. * Parameters:
  2362. * event - the event to bind. Available events on an Endpoint are:
  2363. * - *click* : notification that a Endpoint was clicked.
  2364. * - *dblclick* : notification that a Endpoint was double clicked.
  2365. * - *mouseenter* : notification that the mouse is over a Endpoint.
  2366. * - *mouseexit* : notification that the mouse exited a Endpoint.
  2367. *
  2368. * callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
  2369. */
  2370. /*
  2371. * Function: setPaintStyle
  2372. * Sets the Endpoint's paint style and then repaints the Endpoint.
  2373. *
  2374. * Parameters:
  2375. * style - Style to use.
  2376. */
  2377. /*
  2378. * Function: setHoverPaintStyle
  2379. * Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
  2380. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  2381. * it. This is because people will most likely want to change just one thing when hovering, say the
  2382. * color for example, but leave the rest of the appearance the same.
  2383. *
  2384. * Parameters:
  2385. * style - Style to use when the mouse is hovering.
  2386. * doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
  2387. */
  2388. /*
  2389. * Function: setHover
  2390. * Sets/unsets the hover state of this Endpoint.
  2391. *
  2392. * Parameters:
  2393. * hover - hover state boolean
  2394. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  2395. */
  2396. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2397. var visible = true;
  2398. /*
  2399. Function: isVisible
  2400. Returns whether or not the Endpoint is currently visible.
  2401. */
  2402. this.isVisible = function() { return visible; };
  2403. /*
  2404. Function: setVisible
  2405. Sets whether or not the Endpoint is currently visible.
  2406. Parameters:
  2407. visible - whether or not the Endpoint should be visible.
  2408. doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
  2409. doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
  2410. */
  2411. this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  2412. visible = v;
  2413. if (self.canvas) self.canvas.style.display = v ? "block" : "none";
  2414. if (!doNotChangeConnections) {
  2415. for (var i = 0; i < self.connections.length; i++) {
  2416. self.connections[i].setVisible(v);
  2417. if (!doNotNotifyOtherEndpoint) {
  2418. var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
  2419. // only change the other endpoint if this is its only connection.
  2420. if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
  2421. }
  2422. }
  2423. }
  2424. };
  2425. var id = new String('_jsplumb_e_' + (new Date()).getTime());
  2426. this.getId = function() { return id; };
  2427. if (params.dynamicAnchors)
  2428. self.anchor = new DynamicAnchor(jsPlumb.makeAnchors(params.dynamicAnchors));
  2429. else
  2430. self.anchor = params.anchor ? jsPlumb.makeAnchor(params.anchor) : params.anchors ? jsPlumb.makeAnchor(params.anchors) : jsPlumb.makeAnchor("TopCenter");
  2431. var _endpoint = params.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot",
  2432. endpointArgs = { _jsPlumb:self._jsPlumb, parent:params.parent };
  2433. if (_endpoint.constructor == String)
  2434. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint](endpointArgs);
  2435. else if (_endpoint.constructor == Array)
  2436. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint[0]](jsPlumb.extend(_endpoint[1], endpointArgs ));
  2437. else _endpoint = _endpoint.clone();
  2438. self.endpoint = _endpoint;
  2439. this.endpoint.bind("click", function(e) { self.fire("click", self, e); });
  2440. this.endpoint.bind("dblclick", function(e) { self.fire("dblclick", self, e); });
  2441. this.setPaintStyle(params.paintStyle ||
  2442. params.style ||
  2443. _currentInstance.Defaults.EndpointStyle ||
  2444. jsPlumb.Defaults.EndpointStyle, true);
  2445. this.setHoverPaintStyle(params.hoverPaintStyle ||
  2446. _currentInstance.Defaults.EndpointHoverStyle ||
  2447. jsPlumb.Defaults.EndpointHoverStyle, true);
  2448. this.paintStyleInUse = this.paintStyle;
  2449. this.connectorStyle = params.connectorStyle;
  2450. this.connectorHoverStyle = params.connectorHoverStyle;
  2451. this.connectorOverlays = params.connectorOverlays;
  2452. this.connector = params.connector;
  2453. this.parent = params.parent;
  2454. this.isSource = params.isSource || false;
  2455. this.isTarget = params.isTarget || false;
  2456. var _element = params.source,
  2457. _uuid = params.uuid,
  2458. floatingEndpoint = null,
  2459. inPlaceCopy = null;
  2460. if (_uuid) endpointsByUUID[_uuid] = self;
  2461. var _elementId = _getAttribute(_element, "id");
  2462. this.elementId = _elementId;
  2463. this.element = _element;
  2464. var _maxConnections = params.maxConnections || _currentInstance.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
  2465. this.getAttachedElements = function() {
  2466. return self.connections;
  2467. };
  2468. /*
  2469. * Property: canvas
  2470. * The Endpoint's Canvas.
  2471. */
  2472. this.canvas = this.endpoint.canvas;
  2473. /*
  2474. * Property: connections
  2475. * List of Connections this Endpoint is attached to.
  2476. */
  2477. this.connections = params.connections || [];
  2478. /*
  2479. * Property: scope
  2480. * Scope descriptor for this Endpoint.
  2481. */
  2482. this.scope = params.scope || DEFAULT_SCOPE;
  2483. this.timestamp = null;
  2484. var _reattach = params.reattach || false;
  2485. var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
  2486. this.computeAnchor = function(params) {
  2487. return self.anchor.compute(params);
  2488. };
  2489. /*
  2490. * Function: addConnection
  2491. * Adds a Connection to this Endpoint.
  2492. *
  2493. * Parameters:
  2494. * connection - the Connection to add.
  2495. */
  2496. this.addConnection = function(connection) {
  2497. self.connections.push(connection);
  2498. };
  2499. /*
  2500. * Function: detach
  2501. * Detaches the given Connection from this Endpoint.
  2502. *
  2503. * Parameters:
  2504. * connection - the Connection to detach.
  2505. * ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
  2506. */
  2507. this.detach = function(connection, ignoreTarget) {
  2508. var idx = _findIndex(self.connections, connection);
  2509. if (idx >= 0) {
  2510. self.connections.splice(idx, 1);
  2511. // this avoids a circular loop
  2512. if (!ignoreTarget) {
  2513. var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
  2514. t.detach(connection, true);
  2515. // check connection to see if we want to delete the other endpoint.
  2516. // if the user uses makeTarget to make some element a target for connections,
  2517. // it is possible that they will have set 'endpointToDeleteOnDetach': when
  2518. // you make a connection to an element that acts as a target (note: NOT an
  2519. // Endpoint; just some div as a target), Endpoints are created for that
  2520. // connection. so if you then delete that Connection, it is feasible you
  2521. // will want these auto-generated endpoints to be removed.
  2522. if (connection.endpointToDeleteOnDetach && connection.endpointToDeleteOnDetach.connections.length == 0)
  2523. jsPlumb.deleteEndpoint(connection.endpointToDeleteOnDetach);
  2524. }
  2525. _removeElements(connection.connector.getDisplayElements(), connection.parent);
  2526. _removeFromList(connectionsByScope, connection.scope, connection);
  2527. if(!ignoreTarget) fireDetachEvent(connection);
  2528. }
  2529. };
  2530. /*
  2531. * Function: detachAll
  2532. * Detaches all Connections this Endpoint has.
  2533. */
  2534. this.detachAll = function() {
  2535. while (self.connections.length > 0) {
  2536. self.detach(self.connections[0]);
  2537. }
  2538. };
  2539. /*
  2540. * Function: detachFrom
  2541. * Removes any connections from this Endpoint that are connected to the given target endpoint.
  2542. *
  2543. * Parameters:
  2544. * targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
  2545. */
  2546. this.detachFrom = function(targetEndpoint) {
  2547. var c = [];
  2548. for ( var i = 0; i < self.connections.length; i++) {
  2549. if (self.connections[i].endpoints[1] == targetEndpoint
  2550. || self.connections[i].endpoints[0] == targetEndpoint) {
  2551. c.push(self.connections[i]);
  2552. }
  2553. }
  2554. for ( var i = 0; i < c.length; i++) {
  2555. c[i].setHover(false);
  2556. self.detach(c[i]);
  2557. }
  2558. };
  2559. /*
  2560. * Function: detachFromConnection
  2561. * Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
  2562. *
  2563. * Parameters:
  2564. * connection - Connection to detach from.
  2565. */
  2566. this.detachFromConnection = function(connection) {
  2567. var idx = _findIndex(self.connections, connection);
  2568. if (idx >= 0) {
  2569. self.connections.splice(idx, 1);
  2570. }
  2571. };
  2572. /*
  2573. * Function: getElement
  2574. * Returns the DOM element this Endpoint is attached to.
  2575. */
  2576. this.getElement = function() {
  2577. return _element;
  2578. };
  2579. /*
  2580. * Function: getUuid
  2581. * Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
  2582. */
  2583. this.getUuid = function() {
  2584. return _uuid;
  2585. };
  2586. /**
  2587. * private but must be exposed.
  2588. */
  2589. this.makeInPlaceCopy = function() {
  2590. return _newEndpoint( { anchor : self.anchor, source : _element, paintStyle : this.paintStyle, endpoint : _endpoint });
  2591. };
  2592. /*
  2593. * Function: isConnectedTo
  2594. * Returns whether or not this endpoint is connected to the given Endpoint.
  2595. *
  2596. * Parameters:
  2597. * endpoint - Endpoint to test.
  2598. */
  2599. this.isConnectedTo = function(endpoint) {
  2600. var found = false;
  2601. if (endpoint) {
  2602. for ( var i = 0; i < self.connections.length; i++) {
  2603. if (self.connections[i].endpoints[1] == endpoint) {
  2604. found = true;
  2605. break;
  2606. }
  2607. }
  2608. }
  2609. return found;
  2610. };
  2611. /**
  2612. * private but needs to be exposed.
  2613. */
  2614. this.isFloating = function() {
  2615. return floatingEndpoint != null;
  2616. };
  2617. /**
  2618. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  2619. */
  2620. this.connectorSelector = function() {
  2621. return (self.connections.length < _maxConnections) ? null : self.connections[0];
  2622. };
  2623. /*
  2624. * Function: isFull
  2625. * Returns whether or not the Endpoint can accept any more Connections.
  2626. */
  2627. this.isFull = function() {
  2628. return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
  2629. };
  2630. /*
  2631. * Function: setDragAllowedWhenFull
  2632. * Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
  2633. * which you're going to provide some other way of breaking connections, if you need to break them at all. This property
  2634. * is by default true; use it in conjunction with the 'reattach' option on a connect call.
  2635. *
  2636. * Parameters:
  2637. * allowed - whether drag is allowed or not when the Endpoint is full.
  2638. */
  2639. this.setDragAllowedWhenFull = function(allowed) {
  2640. dragAllowedWhenFull = allowed;
  2641. };
  2642. /*
  2643. * Function: setStyle
  2644. * 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.
  2645. * TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
  2646. * setStyle and deprecate it if so.
  2647. *
  2648. * Parameters:
  2649. * style - Style object to set, for example {fillStyle:"blue"}.
  2650. *
  2651. * @deprecated use setPaintStyle instead.
  2652. */
  2653. this.setStyle = self.setPaintStyle;
  2654. /**
  2655. * a deep equals check. everything must match, including the anchor,
  2656. * styles, everything. TODO: finish Endpoint.equals
  2657. */
  2658. this.equals = function(endpoint) {
  2659. return this.anchor.equals(endpoint.anchor);
  2660. };
  2661. /*
  2662. * Function: paint
  2663. * Paints the Endpoint, recalculating offset and anchor positions if necessary.
  2664. *
  2665. * Parameters:
  2666. * 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.
  2667. * canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
  2668. * connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
  2669. */
  2670. this.paint = function(params) {
  2671. params = params || {};
  2672. var timestamp = params.timestamp;
  2673. if (!timestamp || self.timestamp !== timestamp) {
  2674. var ap = params.anchorPoint, canvas = params.canvas, connectorPaintStyle = params.connectorPaintStyle;
  2675. if (ap == null) {
  2676. var xy = params.offset || offsets[_elementId];
  2677. var wh = params.dimensions || sizes[_elementId];
  2678. if (xy == null || wh == null) {
  2679. _updateOffset( { elId : _elementId, timestamp : timestamp });
  2680. xy = offsets[_elementId];
  2681. wh = sizes[_elementId];
  2682. }
  2683. var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
  2684. if (self.anchor.isDynamic) {
  2685. if (self.connections.length > 0) {
  2686. var c = self.connections[0];
  2687. var oIdx = c.endpoints[0] == self ? 1 : 0;
  2688. var oId = oIdx == 0 ? c.sourceId : c.targetId;
  2689. var oOffset = offsets[oId], oWH = sizes[oId];
  2690. anchorParams.txy = [ oOffset.left, oOffset.top ];
  2691. anchorParams.twh = oWH;
  2692. anchorParams.tElement = c.endpoints[oIdx];
  2693. }
  2694. }
  2695. ap = self.anchor.compute(anchorParams);
  2696. }
  2697. var d = _endpoint.compute(ap, self.anchor.getOrientation(), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
  2698. _endpoint.paint(d, self.paintStyleInUse, self.anchor);
  2699. self.timestamp = timestamp;
  2700. }
  2701. };
  2702. this.repaint = this.paint;
  2703. /**
  2704. * @deprecated
  2705. */
  2706. this.removeConnection = this.detach; // backwards compatibility
  2707. // is this a connection source? we make it draggable and have the
  2708. // drag listener maintain a connection with a floating endpoint.
  2709. if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  2710. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  2711. var start = function() {
  2712. jpc = self.connectorSelector();
  2713. if (self.isFull() && !dragAllowedWhenFull) return false;
  2714. _updateOffset( { elId : _elementId });
  2715. inPlaceCopy = self.makeInPlaceCopy();
  2716. inPlaceCopy.paint();
  2717. n = document.createElement("div");
  2718. n.style.position = "absolute";
  2719. var nE = _getElementObject(n);
  2720. _appendElement(n, self.parent);
  2721. // create and assign an id, and initialize the offset.
  2722. var id = _getId(nE);
  2723. // set the offset of this div to be where 'inPlaceCopy' is, to start with.
  2724. var ipcoel = _getElementObject(inPlaceCopy.canvas),
  2725. ipco = jsPlumb.CurrentLibrary.getOffset(ipcoel),
  2726. po = inPlaceCopy.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(inPlaceCopy.canvas.offsetParent);
  2727. jsPlumb.CurrentLibrary.setOffset(n, {left:ipco.left - po.left, top:ipco.top-po.top});
  2728. _updateOffset( { elId : id });
  2729. // store the id of the dragging div and the source element. the drop function will pick these up.
  2730. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  2731. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  2732. // create a floating anchor
  2733. var floatingAnchor = new FloatingAnchor( { reference : self.anchor, referenceCanvas : self.canvas });
  2734. floatingEndpoint = _newEndpoint({ paintStyle : self.paintStyle, endpoint : _endpoint, anchor : floatingAnchor, source : nE });
  2735. if (jpc == null) {
  2736. self.anchor.locked = true;
  2737. // create a connection. one end is this endpoint, the
  2738. // other is a floating endpoint.
  2739. jpc = _newConnection({
  2740. sourceEndpoint : self,
  2741. targetEndpoint : floatingEndpoint,
  2742. source : _getElementObject(_element),
  2743. target : _getElementObject(n),
  2744. anchors : [ self.anchor, floatingAnchor ],
  2745. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  2746. hoverPaintStyle:params.connectorHoverStyle,
  2747. connector : params.connector, // this can also be null. Connection will use the default.
  2748. overlays : params.connectorOverlays
  2749. });
  2750. // TODO determine whether or not we wish to do de-select hover when dragging a connection.
  2751. // it may be the case that we actually want to set it, since it provides a good
  2752. // visual cue.
  2753. jpc.connector.setHover(false);
  2754. } else {
  2755. existingJpc = true;
  2756. // TODO determine whether or not we wish to do de-select hover when dragging a connection.
  2757. // it may be the case that we actually want to set it, since it provides a good
  2758. // visual cue.
  2759. jpc.connector.setHover(false);
  2760. // if existing connection, allow to be dropped back on the source endpoint (issue 51).
  2761. _initDropTarget(_getElementObject(inPlaceCopy.canvas));
  2762. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1; // are we the source or the target?
  2763. jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
  2764. self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
  2765. // store the original scope (issue 57)
  2766. var c = _getElementObject(self.canvas);
  2767. var dragScope = jsPlumb.CurrentLibrary.getDragScope(c);
  2768. _setAttribute(c, "originalScope", dragScope);
  2769. // get a new, temporary scope, to use (issue 57)
  2770. var newScope = "scope_" + (new Date()).getTime();
  2771. // now we replace ourselves with the temporary div we created above:
  2772. if (anchorIdx == 0) {
  2773. existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
  2774. jpc.source = _getElementObject(n);
  2775. jpc.sourceId = id;
  2776. } else {
  2777. existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
  2778. jpc.target = _getElementObject(n);
  2779. jpc.targetId = id;
  2780. }
  2781. // set the new, temporary scope (issue 57)
  2782. jsPlumb.CurrentLibrary.setDragScope(i, newScope);
  2783. // lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
  2784. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
  2785. // store the original endpoint and assign the new floating endpoint for the drag.
  2786. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  2787. jpc.endpoints[anchorIdx] = floatingEndpoint;
  2788. }
  2789. // register it.
  2790. floatingConnections[id] = jpc;
  2791. // TODO unregister on stop? or will floating endpoint's
  2792. // destruction be assured.
  2793. floatingEndpoint.addConnection(jpc);
  2794. // only register for the target endpoint; we will not be
  2795. // dragging the source at any time
  2796. // before this connection is either discarded or made into a
  2797. // permanent connection.
  2798. _addToList(endpointsByElement, id, floatingEndpoint);
  2799. // tell jsplumb about it
  2800. _currentInstance.currentlyDragging = true;
  2801. };
  2802. var jpcl = jsPlumb.CurrentLibrary,
  2803. dragOptions = params.dragOptions || {},
  2804. defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
  2805. startEvent = jpcl.dragEvents['start'],
  2806. stopEvent = jpcl.dragEvents['stop'],
  2807. dragEvent = jpcl.dragEvents['drag'];
  2808. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  2809. dragOptions.scope = dragOptions.scope || self.scope;
  2810. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  2811. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent],
  2812. function() {
  2813. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  2814. jsPlumb.CurrentLibrary.setOffset(n, _ui);
  2815. _draw(_getElementObject(n), _ui);
  2816. });
  2817. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  2818. function() {
  2819. _removeFromList(endpointsByElement, id, floatingEndpoint);
  2820. _removeElements( [ n, floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
  2821. _removeElement(inPlaceCopy.canvas, _element);
  2822. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2823. jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
  2824. if (jpc.endpoints[idx] == floatingEndpoint) {
  2825. // if the connection was an existing one:
  2826. if (existingJpc && jpc.suspendedEndpoint) {
  2827. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  2828. // floating endpoint has been replaced.
  2829. if (idx == 0) {
  2830. jpc.source = existingJpcParams[0];
  2831. jpc.sourceId = existingJpcParams[1];
  2832. } else {
  2833. jpc.target = existingJpcParams[0];
  2834. jpc.targetId = existingJpcParams[1];
  2835. }
  2836. // restore the original scope (issue 57)
  2837. jsPlumb.CurrentLibrary.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  2838. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  2839. if (_reattach) {
  2840. jpc.floatingAnchorIndex = null;
  2841. jpc.suspendedEndpoint.addConnection(jpc);
  2842. jsPlumb.repaint(existingJpcParams[1]);
  2843. } else {
  2844. jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc); // the main endpoint will inform the floating endpoint
  2845. // to disconnect, and also post the detached event.
  2846. }
  2847. } else {
  2848. // TODO this looks suspiciously kind of like an Endpoint.detach call too.
  2849. // i wonder if this one should post an event though. maybe this is good like this.
  2850. _removeElements(jpc.connector.getDisplayElements(), self.parent);
  2851. self.detachFromConnection(jpc);
  2852. }
  2853. }
  2854. self.anchor.locked = false;
  2855. self.paint();
  2856. jpc.setHover(false);
  2857. jpc.repaint();
  2858. jpc = null;
  2859. delete inPlaceCopy;
  2860. delete endpointsByElement[floatingEndpoint.elementId];
  2861. floatingEndpoint = null;
  2862. delete floatingEndpoint;
  2863. _currentInstance.currentlyDragging = false;
  2864. });
  2865. var i = _getElementObject(self.canvas);
  2866. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
  2867. }
  2868. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  2869. // back onto the endpoint you detached it from.
  2870. var _initDropTarget = function(canvas) {
  2871. if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  2872. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  2873. dropOptions = jsPlumb.extend( {}, dropOptions);
  2874. dropOptions.scope = dropOptions.scope || self.scope;
  2875. var originalAnchor = null;
  2876. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
  2877. var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
  2878. var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
  2879. var drop = function() {
  2880. var draggable = _getElementObject(jsPlumb.CurrentLibrary.getDragObject(arguments));
  2881. var id = _getAttribute(draggable, "dragId");
  2882. var elId = _getAttribute(draggable, "elId");
  2883. // restore the original scope if necessary (issue 57)
  2884. var scope = _getAttribute(draggable, "originalScope");
  2885. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  2886. var jpc = floatingConnections[id];
  2887. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
  2888. if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
  2889. if (idx == 0) {
  2890. jpc.source = _element;
  2891. jpc.sourceId = _elementId;
  2892. } else {
  2893. jpc.target = _element;
  2894. jpc.targetId = _elementId;
  2895. }
  2896. // todo test that the target is not full.
  2897. // remove this jpc from the current endpoint
  2898. jpc.endpoints[idx].detachFromConnection(jpc);
  2899. if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
  2900. jpc.endpoints[idx] = self;
  2901. self.addConnection(jpc);
  2902. if (!jpc.suspendedEndpoint) {
  2903. _addToList(connectionsByScope, jpc.scope, jpc);
  2904. _initDraggableIfNecessary(_element, params.draggable, {});
  2905. }
  2906. else {
  2907. var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
  2908. // fire a detach event
  2909. _currentInstance.fire("jsPlumbConnectionDetached", {
  2910. source : idx == 0 ? suspendedElement : jpc.source,
  2911. target : idx == 1 ? suspendedElement : jpc.target,
  2912. sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
  2913. targetId : idx == 1 ? suspendedElementId : jpc.targetId,
  2914. sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  2915. targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  2916. connection : jpc
  2917. });
  2918. }
  2919. jsPlumb.repaint(elId);
  2920. _currentInstance.fire("jsPlumbConnection", {
  2921. source : jpc.source, target : jpc.target,
  2922. sourceId : jpc.sourceId, targetId : jpc.targetId,
  2923. sourceEndpoint : jpc.endpoints[0],
  2924. targetEndpoint : jpc.endpoints[1],
  2925. connection:jpc
  2926. });
  2927. }
  2928. _currentInstance.currentlyDragging = false;
  2929. delete floatingConnections[id];
  2930. };
  2931. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], drop);
  2932. dropOptions[overEvent] = _wrap(dropOptions[overEvent],
  2933. function() {
  2934. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  2935. var id = _getAttribute( _getElementObject(draggable), "dragId");
  2936. var jpc = floatingConnections[id];
  2937. if (jpc != null) {
  2938. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2939. jpc.endpoints[idx].anchor.over(self.anchor);
  2940. }
  2941. });
  2942. dropOptions[outEvent] = _wrap(dropOptions[outEvent],
  2943. function() {
  2944. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  2945. id = _getAttribute(_getElementObject(draggable), "dragId"),
  2946. jpc = floatingConnections[id];
  2947. if (jpc != null) {
  2948. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2949. jpc.endpoints[idx].anchor.out();
  2950. }
  2951. });
  2952. jsPlumb.CurrentLibrary.initDroppable(canvas, dropOptions);
  2953. }
  2954. };
  2955. // 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.
  2956. _initDropTarget(_getElementObject(self.canvas));
  2957. return self;
  2958. };
  2959. };
  2960. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  2961. jsPlumb.getInstance = function(_defaults) {
  2962. var j = new jsPlumbInstance(_defaults);
  2963. //if (_defaults) jsPlumb.extend(j.Defaults, _defaults);
  2964. return j;
  2965. };
  2966. var _curryAnchor = function(x,y,ox,oy) {
  2967. return function() {
  2968. return jsPlumb.makeAnchor(x,y,ox,oy);
  2969. };
  2970. };
  2971. jsPlumb.Anchors["TopCenter"] = _curryAnchor(0.5, 0, 0,-1);
  2972. jsPlumb.Anchors["BottomCenter"] = _curryAnchor(0.5, 1, 0, 1);
  2973. jsPlumb.Anchors["LeftMiddle"] = _curryAnchor(0, 0.5, -1, 0);
  2974. jsPlumb.Anchors["RightMiddle"] = _curryAnchor(1, 0.5, 1, 0);
  2975. jsPlumb.Anchors["Center"] = _curryAnchor(0.5, 0.5, 0, 0);
  2976. jsPlumb.Anchors["TopRight"] = _curryAnchor(1, 0, 0,-1);
  2977. jsPlumb.Anchors["BottomRight"] = _curryAnchor(1, 1, 0, 1);
  2978. jsPlumb.Anchors["TopLeft"] = _curryAnchor(0, 0, 0, -1);
  2979. jsPlumb.Anchors["BottomLeft"] = _curryAnchor(0, 1, 0, 1);
  2980. jsPlumb.Defaults.DynamicAnchors = function() {
  2981. return jsPlumb.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"]);
  2982. };
  2983. jsPlumb.Anchors["AutoDefault"] = function() { return jsPlumb.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors()); };
  2984. })();
  2985. /*
  2986. * jsPlumb-defaults-1.3.0-RC1
  2987. *
  2988. * Copyright 2010 - 2011 Simon Porritt http://jsplumb.org
  2989. *
  2990. * Triple licensed under the MIT, GPL2 and Beer licenses.
  2991. */
  2992. (function() {
  2993. /**
  2994. *
  2995. * Helper class to consume unused mouse events by components that are DOM elements and
  2996. * are used by all of the different rendering modes.
  2997. *
  2998. */
  2999. jsPlumb.DOMElementComponent = function(params) {
  3000. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  3001. // when render mode is canvas, these functions may be called by the canvas mouse handler.
  3002. // this component is safe to pipe this stuff to /dev/null.
  3003. this.mousemove =
  3004. this.dblclick =
  3005. this.click =
  3006. this.mousedown =
  3007. this.mouseup = function(e) { };
  3008. };
  3009. /**
  3010. * Class: Connectors.Straight
  3011. * The Straight connector draws a simple straight line between the two anchor points. It does not have any constructor parameters.
  3012. */
  3013. jsPlumb.Connectors.Straight = function() {
  3014. var self = this;
  3015. var currentPoints = null;
  3016. var _m, _m2, _b, _dx, _dy, _theta, _theta2, _sx, _sy, _tx, _ty;
  3017. /**
  3018. * Computes the new size and position of the canvas.
  3019. * @param sourceAnchor Absolute position on screen of the source object's anchor.
  3020. * @param targetAnchor Absolute position on screen of the target object's anchor.
  3021. * @param positionMatrix Indicates the relative positions of the left,top of the
  3022. * two plumbed objects. so [0,0] indicates that the source is to the left of, and
  3023. * above, the target. [1,0] means the source is to the right and above. [0,1] means
  3024. * the source is to the left and below. [1,1] means the source is to the right
  3025. * and below. this is used to figure out which direction to draw the connector in.
  3026. * @returns an array of positioning information. the first two values are
  3027. * the [left, top] absolute position the canvas should be placed on screen. the
  3028. * next two values are the [width,height] the canvas should be. after that each
  3029. * Connector can put whatever it likes into the array:it will be passed back in
  3030. * to the paint call. This particular function stores the origin and destination of
  3031. * the line it is going to draw. a more involved implementation, like a Bezier curve,
  3032. * would store the control point info in this array too.
  3033. */
  3034. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  3035. var w = Math.abs(sourcePos[0] - targetPos[0]);
  3036. var h = Math.abs(sourcePos[1] - targetPos[1]);
  3037. var widthAdjusted = false, heightAdjusted = false;
  3038. // these are padding to ensure the whole connector line appears
  3039. var xo = 0.45 * w, yo = 0.45 * h;
  3040. // these are padding to ensure the whole connector line appears
  3041. w *= 1.9; h *=1.9;
  3042. var x = Math.min(sourcePos[0], targetPos[0]) - xo;
  3043. var y = Math.min(sourcePos[1], targetPos[1]) - yo;
  3044. // minimum size is 2 * line Width if minWidth was not given.
  3045. var calculatedMinWidth = Math.max(2 * lineWidth, minWidth);
  3046. if (w < calculatedMinWidth) {
  3047. w = calculatedMinWidth;
  3048. x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - (calculatedMinWidth / 2);
  3049. xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;
  3050. }
  3051. if (h < calculatedMinWidth) {
  3052. h = calculatedMinWidth;
  3053. y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - (calculatedMinWidth / 2);
  3054. yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;
  3055. }
  3056. _sx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  3057. _sy = sourcePos[1] < targetPos[1] ? yo:h-yo;
  3058. _tx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  3059. _ty = sourcePos[1] < targetPos[1] ? h-yo : yo;
  3060. currentPoints = [ x, y, w, h, _sx, _sy, _tx, _ty ];
  3061. _dx = _tx - _sx, _dy = (_ty - _sy);
  3062. _m = _dy / _dx, _m2 = -1 / _m;
  3063. _b = -1 * ((_m * _sx) - _sy);
  3064. _theta = Math.atan(_m); _theta2 = Math.atan(_m2);
  3065. return currentPoints;
  3066. };
  3067. /**
  3068. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  3069. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  3070. */
  3071. this.pointOnPath = function(location) {
  3072. var xp = _sx + (location * _dx);
  3073. var yp = (_m == Infinity || _m == -Infinity) ? _sy + (location * (_ty - _sy)) : (_m * xp) + _b;
  3074. return {x:xp, y:yp};
  3075. };
  3076. /**
  3077. * returns the gradient of the connector at the given point - which for us is constant.
  3078. */
  3079. this.gradientAtPoint = function(location) { return _m; };
  3080. /**
  3081. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  3082. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
  3083. */
  3084. this.pointAlongPathFrom = function(location, distance) {
  3085. var p = self.pointOnPath(location);
  3086. var orientation = distance > 0 ? 1 : -1;
  3087. var y = Math.abs(distance * Math.sin(_theta));
  3088. if (_sy > _ty) y = y * -1;
  3089. var x = Math.abs(distance * Math.cos(_theta));
  3090. if (_sx > _tx) x = x * -1;
  3091. return {x:p.x + (orientation * x), y:p.y + (orientation * y)};
  3092. };
  3093. /**
  3094. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  3095. * the line is 'length' pixels long.
  3096. */
  3097. this.perpendicularToPathAt = function(location, length, distance) {
  3098. var p = self.pointAlongPathFrom(location, distance);
  3099. var m = self.gradientAtPoint(p.location);
  3100. var _theta2 = Math.atan(-1 / m);
  3101. var y = length / 2 * Math.sin(_theta2);
  3102. var x = length / 2 * Math.cos(_theta2);
  3103. return [{x:p.x + x, y:p.y + y}, {x:p.x - x, y:p.y - y}];
  3104. };
  3105. };
  3106. /**
  3107. * Class:Connectors.Bezier
  3108. * This Connector draws a Bezier curve with two control points. You can provide a 'curviness' value which gets applied to jsPlumb's
  3109. * internal voodoo machine and ends up generating locations for the two control points. See the constructor documentation below.
  3110. */
  3111. /**
  3112. * Function:Constructor
  3113. *
  3114. * Parameters:
  3115. * 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
  3116. * 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.
  3117. * Optional; defaults to 150.
  3118. *
  3119. */
  3120. jsPlumb.Connectors.Bezier = function(params) {
  3121. var self = this;
  3122. params = params || {};
  3123. this.majorAnchor = params.curviness || 150;
  3124. this.minorAnchor = 10;
  3125. var currentPoints = null;
  3126. this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
  3127. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  3128. // points around if so (code could be tightened up)
  3129. var soo = sourceAnchor.getOrientation(), too = targetAnchor.getOrientation();
  3130. var perpendicular = soo[0] != too[0] || soo[1] == too[1];
  3131. var p = [];
  3132. var ma = self.majorAnchor, mi = self.minorAnchor;
  3133. if (!perpendicular) {
  3134. if (soo[0] == 0) // X
  3135. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  3136. else p.push(point[0] - (ma * soo[0]));
  3137. if (soo[1] == 0) // Y
  3138. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  3139. else p.push(point[1] + (ma * too[1]));
  3140. }
  3141. else {
  3142. if (too[0] == 0) // X
  3143. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  3144. else p.push(point[0] + (ma * too[0]));
  3145. if (too[1] == 0) // Y
  3146. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  3147. else p.push(point[1] + (ma * soo[1]));
  3148. }
  3149. return p;
  3150. };
  3151. var _CP, _CP2, _sx, _tx, _ty, _sx, _sy, _canvasX, _canvasY, _w, _h;
  3152. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth)
  3153. {
  3154. lineWidth = lineWidth || 0;
  3155. _w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth;
  3156. _h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  3157. _canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2);
  3158. _canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  3159. _sx = sourcePos[0] < targetPos[0] ? _w - (lineWidth/2): (lineWidth/2);
  3160. _sy = sourcePos[1] < targetPos[1] ? _h - (lineWidth/2) : (lineWidth/2);
  3161. _tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : _w - (lineWidth/2);
  3162. _ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : _h - (lineWidth/2);
  3163. _CP = self._findControlPoint([_sx,_sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
  3164. _CP2 = self._findControlPoint([_tx,_ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
  3165. var minx1 = Math.min(_sx,_tx); var minx2 = Math.min(_CP[0], _CP2[0]); var minx = Math.min(minx1,minx2);
  3166. var maxx1 = Math.max(_sx,_tx); var maxx2 = Math.max(_CP[0], _CP2[0]); var maxx = Math.max(maxx1,maxx2);
  3167. if (maxx > _w) _w = maxx;
  3168. if (minx < 0) {
  3169. _canvasX += minx; var ox = Math.abs(minx);
  3170. _w += ox; _CP[0] += ox; _sx += ox; _tx +=ox; _CP2[0] += ox;
  3171. }
  3172. var miny1 = Math.min(_sy,_ty); var miny2 = Math.min(_CP[1], _CP2[1]); var miny = Math.min(miny1,miny2);
  3173. var maxy1 = Math.max(_sy,_ty); var maxy2 = Math.max(_CP[1], _CP2[1]); var maxy = Math.max(maxy1,maxy2);
  3174. if (maxy > _h) _h = maxy;
  3175. if (miny < 0) {
  3176. _canvasY += miny; var oy = Math.abs(miny);
  3177. _h += oy; _CP[1] += oy; _sy += oy; _ty +=oy; _CP2[1] += oy;
  3178. }
  3179. if (minWidth && _w < minWidth) {
  3180. var posAdjust = (minWidth - _w) / 2;
  3181. _w = minWidth;
  3182. _canvasX -= posAdjust; _sx = _sx + posAdjust ; _tx = _tx + posAdjust; _CP[0] = _CP[0] + posAdjust; _CP2[0] = _CP2[0] + posAdjust;
  3183. }
  3184. if (minWidth && _h < minWidth) {
  3185. var posAdjust = (minWidth - _h) / 2;
  3186. _h = minWidth;
  3187. _canvasY -= posAdjust; _sy = _sy + posAdjust ; _ty = _ty + posAdjust; _CP[1] = _CP[1] + posAdjust; _CP2[1] = _CP2[1] + posAdjust;
  3188. }
  3189. currentPoints = [_canvasX, _canvasY, _w, _h, _sx, _sy, _tx, _ty, _CP[0], _CP[1], _CP2[0], _CP2[1] ];
  3190. return currentPoints;
  3191. };
  3192. var _makeCurve = function() {
  3193. return [
  3194. { x:_sx, y:_sy },
  3195. { x:_CP[0], y:_CP[1] },
  3196. { x:_CP2[0], y:_CP2[1] },
  3197. { x:_tx, y:_ty }
  3198. ];
  3199. };
  3200. /**
  3201. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  3202. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  3203. */
  3204. this.pointOnPath = function(location) {
  3205. return jsBezier.pointOnCurve(_makeCurve(), location);
  3206. };
  3207. /**
  3208. * returns the gradient of the connector at the given point.
  3209. */
  3210. this.gradientAtPoint = function(location) {
  3211. return jsBezier.gradientAtPoint(_makeCurve(), location);
  3212. };
  3213. /**
  3214. * for Bezier curves this method is a little tricky, cos calculating path distance algebraically is notoriously difficult.
  3215. * this method is iterative, jumping forward .05% of the path at a time and summing the distance between this point and the previous
  3216. * one, until the sum reaches 'distance'. the method may turn out to be computationally expensive; we'll see.
  3217. * another drawback of this method is that if the connector gets quite long, .05% of the length of it is not necessarily smaller
  3218. * than the desired distance, in which case the loop returns immediately and the arrow is mis-shapen. so a better strategy might be to
  3219. * calculate the step as a function of distance/distance between endpoints.
  3220. */
  3221. this.pointAlongPathFrom = function(location, distance) {
  3222. return jsBezier.pointAlongCurveFrom(_makeCurve(), location, distance);
  3223. };
  3224. /**
  3225. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  3226. * the line is 'length' pixels long.
  3227. */
  3228. this.perpendicularToPathAt = function(location, length, distance) {
  3229. return jsBezier.perpendicularToCurveAt(_makeCurve(), location, length, distance);
  3230. };
  3231. };
  3232. /**
  3233. * Class: Connectors.Flowchart
  3234. * Provides 'flowchart' connectors, consisting of vertical and horizontal line segments.
  3235. */
  3236. /**
  3237. * Function: Constructor
  3238. *
  3239. * Parameters:
  3240. * stub - minimum length for the stub at each end of the connector. defaults to 30 pixels.
  3241. */
  3242. jsPlumb.Connectors.Flowchart = function(params) {
  3243. params = params || {};
  3244. var self = this,
  3245. minStubLength = params.stub || params.minStubLength /* bwds compat. */ || 30,
  3246. segments = [],
  3247. segmentGradients = [],
  3248. segmentProportions = [],
  3249. segmentLengths = [],
  3250. segmentProportionalLengths = [],
  3251. points = [],
  3252. swapX,
  3253. swapY,
  3254. /**
  3255. * recalculates the gradients of each segment, and the points at which the segments begin, proportional to the total length travelled
  3256. * by all the segments that constitute the connector.
  3257. */
  3258. updateSegmentGradientsAndProportions = function(startX, startY, endX, endY) {
  3259. var total = 0;
  3260. for (var i = 0; i < segments.length; i++) {
  3261. var sx = i == 0 ? startX : segments[i][2],
  3262. sy = i == 0 ? startY : segments[i][3],
  3263. ex = segments[i][0],
  3264. ey = segments[i][1];
  3265. segmentGradients[i] = sx == ex ? Infinity : 0;
  3266. segmentLengths[i] = Math.abs(sx == ex ? ey - sy : ex - sx);
  3267. total += segmentLengths[i];
  3268. }
  3269. var curLoc = 0;
  3270. for (var i = 0; i < segments.length; i++) {
  3271. segmentProportionalLengths[i] = segmentLengths[i] / total;
  3272. segmentProportions[i] = [curLoc, (curLoc += (segmentLengths[i] / total)) ];
  3273. }
  3274. },
  3275. appendSegmentsToPoints = function() {
  3276. points.push(segments.length);
  3277. for (var i = 0; i < segments.length; i++) {
  3278. points.push(segments[i][0]);
  3279. points.push(segments[i][1]);
  3280. }
  3281. },
  3282. /**
  3283. * helper method to add a segment.
  3284. */
  3285. addSegment = function(x, y, sx, sy, tx, ty) {
  3286. var lx = segments.length == 0 ? sx : segments[segments.length - 1][0];
  3287. var ly = segments.length == 0 ? sy : segments[segments.length - 1][1];
  3288. segments.push([x, y, lx, ly]);
  3289. },
  3290. /**
  3291. * returns [segment, proportion of travel in segment, segment index] for the segment
  3292. * that contains the point which is 'location' distance along the entire path, where
  3293. * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
  3294. * are made up of a list of segments, each of which contributes some fraction to
  3295. * the total length.
  3296. */
  3297. findSegmentForLocation = function(location) {
  3298. var idx = segmentProportions.length - 1, inSegmentProportion = 0;
  3299. for (var i = 0; i < segmentProportions.length; i++) {
  3300. if (segmentProportions[i][1] >= location) {
  3301. idx = i;
  3302. inSegmentProportion = (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
  3303. break;
  3304. }
  3305. }
  3306. return { segment:segments[idx], proportion:inSegmentProportion, index:idx };
  3307. };
  3308. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  3309. segments = [];
  3310. segmentGradients = [];
  3311. segmentProportionalLengths = [];
  3312. segmentLengths = [];
  3313. segmentProportionals = [];
  3314. swapX = targetPos[0] < sourcePos[0];
  3315. swapY = targetPos[1] < sourcePos[1];
  3316. var lw = lineWidth || 1,
  3317. offx = (lw / 2) + (minStubLength * 2),
  3318. offy = (lw / 2) + (minStubLength * 2),
  3319. so = sourceAnchor.orientation || sourceAnchor.getOrientation(),
  3320. to = targetAnchor.orientation || targetAnchor.getOrientation(),
  3321. x = swapX ? targetPos[0] : sourcePos[0],
  3322. y = swapY ? targetPos[1] : sourcePos[1],
  3323. w = Math.abs(targetPos[0] - sourcePos[0]) + 2*offx,
  3324. h = Math.abs(targetPos[1] - sourcePos[1]) + 2*offy;
  3325. if (w < minWidth) {
  3326. offx += (minWidth - w) / 2;
  3327. w = minWidth;
  3328. }
  3329. if (h < minWidth) {
  3330. offy += (minWidth - h) / 2;
  3331. h = minWidth;
  3332. }
  3333. var sx = swapX ? w-offx : offx,
  3334. sy = swapY ? h-offy : offy,
  3335. tx = swapX ? offx : w-offx ,
  3336. ty = swapY ? offy : h-offy,
  3337. startStubX = sx + (so[0] * minStubLength),
  3338. startStubY = sy + (so[1] * minStubLength),
  3339. endStubX = tx + (to[0] * minStubLength),
  3340. endStubY = ty + (to[1] * minStubLength),
  3341. midx = startStubX + ((endStubX - startStubX) / 2),
  3342. midy = startStubY + ((endStubY - startStubY) / 2);
  3343. x -= offx; y -= offy;
  3344. points = [x, y, w, h, sx, sy, tx, ty], extraPoints = [];
  3345. addSegment(startStubX, startStubY, sx, sy, tx, ty);
  3346. if (so[0] == 0) {
  3347. var startStubIsBeforeEndStub = startStubY < endStubY;
  3348. // when start point's stub is less than endpoint's stub
  3349. if (startStubIsBeforeEndStub) {
  3350. addSegment(startStubX, midy, sx, sy, tx, ty);
  3351. addSegment(midx, midy, sx, sy, tx, ty);
  3352. addSegment(endStubX, midy, sx, sy, tx, ty);
  3353. } else {
  3354. // when start point's stub is greater than endpoint's stub
  3355. addSegment(midx, startStubY, sx, sy, tx, ty);
  3356. addSegment(midx, endStubY, sx, sy, tx, ty);
  3357. }
  3358. }
  3359. else {
  3360. var startStubIsBeforeEndStub = startStubX < endStubX;
  3361. // when start point's stub is less than endpoint's stub
  3362. if (startStubIsBeforeEndStub) {
  3363. addSegment(midx, startStubY, sx, sy, tx, ty);
  3364. addSegment(midx, midy, sx, sy, tx, ty);
  3365. addSegment(midx, endStubY, sx, sy, tx, ty);
  3366. } else {
  3367. // when start point's stub is greater than endpoint's stub
  3368. addSegment(startStubX, midy, sx, sy, tx, ty);
  3369. addSegment(endStubX, midy, sx, sy, tx, ty);
  3370. }
  3371. }
  3372. addSegment(endStubX, endStubY, sx, sy, tx, ty);
  3373. addSegment(tx, ty, sx, sy, tx, ty);
  3374. appendSegmentsToPoints();
  3375. updateSegmentGradientsAndProportions(sx, sy, tx, ty);
  3376. return points;
  3377. };
  3378. /**
  3379. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  3380. * 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
  3381. * from our knowledge of the segment's start and end points.
  3382. */
  3383. this.pointOnPath = function(location) {
  3384. return self.pointAlongPathFrom(location, 0);
  3385. };
  3386. /**
  3387. * returns the gradient of the connector at the given point; the gradient will be either 0 or Infinity, depending on the direction of the
  3388. * segment the point falls in. segment gradients are calculated in the compute method.
  3389. */
  3390. this.gradientAtPoint = function(location) {
  3391. return segmentGradients[findSegmentForLocation(location)["index"]];
  3392. };
  3393. /**
  3394. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  3395. * '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
  3396. * of this connector, it starts to become clear that there's a problem with the overlay paint code: given that this connector makes several
  3397. * 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
  3398. * because jsPlumb uses this method (and pointOnPath) so determine the locations of the various points that go to make up an overlay. a better
  3399. * solution would probably be to just use pointOnPath along with gradientAtPoint, and draw the overlay so that its axis ran along
  3400. * a tangent to the connector. for straight line connectors this would obviously mean the overlay was painted directly on the connector, since a
  3401. * 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
  3402. * advantage is, of course, that there's less computation involved doing it that way.
  3403. */
  3404. this.pointAlongPathFrom = function(location, distance) {
  3405. var s = findSegmentForLocation(location), seg = s.segment, p = s.proportion, sl = segmentLengths[s.index], m = segmentGradients[s.index];
  3406. var e = {
  3407. x : m == Infinity ? seg[2] : seg[2] > seg[0] ? seg[0] + ((1 - p) * sl) - distance : seg[2] + (p * sl) + distance,
  3408. y : m == 0 ? seg[3] : seg[3] > seg[1] ? seg[1] + ((1 - p) * sl) - distance : seg[3] + (p * sl) + distance,
  3409. segmentInfo : s
  3410. };
  3411. return e;
  3412. };
  3413. /**
  3414. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  3415. * the line is 'length' pixels long.
  3416. */
  3417. this.perpendicularToPathAt = function(location, length, distance) {
  3418. var p = self.pointAlongPathFrom(location, distance);
  3419. var m = segmentGradients[p.segmentInfo.index];
  3420. var _theta2 = Math.atan(-1 / m);
  3421. var y = length / 2 * Math.sin(_theta2);
  3422. var x = length / 2 * Math.cos(_theta2);
  3423. return [{x:p.x + x, y:p.y + y}, {x:p.x - x, y:p.y - y}];
  3424. };
  3425. };
  3426. // ********************************* END OF CONNECTOR TYPES *******************************************************************
  3427. // ********************************* ENDPOINT TYPES *******************************************************************
  3428. /**
  3429. * Class: Endpoints.Dot
  3430. * A round endpoint, with default radius 10 pixels.
  3431. */
  3432. /**
  3433. * Function: Constructor
  3434. *
  3435. * Parameters:
  3436. *
  3437. * radius - radius of the endpoint. defaults to 10 pixels.
  3438. */
  3439. jsPlumb.Endpoints.Dot = function(params) {
  3440. var self = this;
  3441. params = params || {};
  3442. this.radius = params.radius || 10;
  3443. this.defaultOffset = 0.5 * this.radius;
  3444. this.defaultInnerRadius = this.radius / 3;
  3445. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3446. var r = endpointStyle.radius || self.radius;
  3447. var x = anchorPoint[0] - r;
  3448. var y = anchorPoint[1] - r;
  3449. return [ x, y, r * 2, r * 2, r ];
  3450. };
  3451. };
  3452. /**
  3453. * Class: Endpoints.Rectangle
  3454. * A Rectangular Endpoint, with default size 20x20.
  3455. */
  3456. /**
  3457. * Function: Constructor
  3458. *
  3459. * Parameters:
  3460. *
  3461. * width - width of the endpoint. defaults to 20 pixels.
  3462. * height - height of the endpoint. defaults to 20 pixels.
  3463. */
  3464. jsPlumb.Endpoints.Rectangle = function(params) {
  3465. var self = this;
  3466. params = params || {};
  3467. this.width = params.width || 20;
  3468. this.height = params.height || 20;
  3469. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3470. var width = endpointStyle.width || self.width;
  3471. var height = endpointStyle.height || self.height;
  3472. var x = anchorPoint[0] - (width/2);
  3473. var y = anchorPoint[1] - (height/2);
  3474. return [ x, y, width, height];
  3475. };
  3476. };
  3477. /**
  3478. * Class: Endpoints.Image
  3479. * Draws an image as the Endpoint.
  3480. */
  3481. /**
  3482. * Function: Constructor
  3483. *
  3484. * Parameters:
  3485. *
  3486. * src - location of the image to use.
  3487. */
  3488. jsPlumb.Endpoints.Image = function(params) {
  3489. jsPlumb.DOMElementComponent.apply(this, arguments);
  3490. var self = this, initialized = false;
  3491. this.img = new Image();
  3492. self.ready = false;
  3493. this.img.onload = function() {
  3494. self.ready = true;
  3495. };
  3496. this.img.src = params.src || params.url;
  3497. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3498. self.anchorPoint = anchorPoint;
  3499. if (self.ready) return [anchorPoint[0] - self.img.width / 2, anchorPoint[1] - self.img.height/ 2, self.img.width, self.img.height];
  3500. else return [0,0,0,0];
  3501. };
  3502. self.canvas = document.createElement("img"), initialized = false;
  3503. self.canvas.style["margin"] = 0;
  3504. self.canvas.style["padding"] = 0;
  3505. self.canvas.style["outline"] = 0;
  3506. self.canvas.style["position"] = "absolute";
  3507. self.canvas.className = jsPlumb.endpointClass;
  3508. jsPlumb.appendElement(self.canvas, params.parent);
  3509. self.attachListeners(self.canvas, self);
  3510. var actuallyPaint = function(d, style, anchor) {
  3511. if (!initialized) {
  3512. self.canvas.setAttribute("src", self.img.src);
  3513. initialized = true;
  3514. }
  3515. var width = self.img.width,
  3516. height = self.img.height,
  3517. x = self.anchorPoint[0] - (width/2),
  3518. y = self.anchorPoint[1] - (height/2);
  3519. jsPlumb.sizeCanvas(self.canvas, x, y, width, height);
  3520. };
  3521. this.paint = function(d, style, anchor) {
  3522. if (self.ready) {
  3523. actuallyPaint(d, style, anchor);
  3524. }
  3525. else {
  3526. window.setTimeout(function() {
  3527. self.paint(d, style, anchor);
  3528. }, 200);
  3529. }
  3530. };
  3531. };
  3532. /**
  3533. * Class: Endpoints.Blank
  3534. * An Endpoint that paints nothing on the screen, and cannot be interacted with using the mouse. There are no constructor parameters for this Endpoint.
  3535. */
  3536. jsPlumb.Endpoints.Blank = function() {
  3537. jsPlumb.DOMElementComponent.apply(this, arguments);
  3538. this.compute = function() {
  3539. return [0,0,0,0];
  3540. };
  3541. self.canvas = document.createElement("div");
  3542. this.paint = function() { };
  3543. };
  3544. /**
  3545. * Class: Endpoints.Triangle
  3546. * A triangular Endpoint.
  3547. */
  3548. /**
  3549. * Function: Constructor
  3550. *
  3551. * Parameters:
  3552. *
  3553. * width - width of the triangle's base. defaults to 55 pixels.
  3554. * height - height of the triangle from base to apex. defaults to 55 pixels.
  3555. */
  3556. jsPlumb.Endpoints.Triangle = function(params) {
  3557. params = params || { };
  3558. params.width = params.width || 55;
  3559. param.height = params.height || 55;
  3560. this.width = params.width;
  3561. this.height = params.height;
  3562. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3563. var width = endpointStyle.width || self.width;
  3564. var height = endpointStyle.height || self.height;
  3565. var x = anchorPoint[0] - (width/2);
  3566. var y = anchorPoint[1] - (height/2);
  3567. return [ x, y, width, height ];
  3568. };
  3569. };
  3570. // ********************************* END OF ENDPOINT TYPES *******************************************************************
  3571. // ********************************* OVERLAY DEFINITIONS ***********************************************************************
  3572. /**
  3573. * Class: Overlays.Arrow
  3574. *
  3575. * 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
  3576. * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
  3577. * 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
  3578. * across the tail.
  3579. */
  3580. /**
  3581. * Function: Constructor
  3582. *
  3583. * Parameters:
  3584. *
  3585. * length - distance in pixels from head to tail baseline. default 20.
  3586. * width - width in pixels of the tail baseline. default 20.
  3587. * fillStyle - style to use when filling the arrow. defaults to "black".
  3588. * strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
  3589. * lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null.
  3590. * 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.
  3591. * location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
  3592. * direction - indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
  3593. */
  3594. jsPlumb.Overlays.Arrow = function(params) {
  3595. params = params || {};
  3596. var self = this;
  3597. this.length = params.length || 20;
  3598. this.width = params.width || 20;
  3599. this.id = params.id;
  3600. this.connection = params.connection;
  3601. var direction = (params.direction || 1) < 0 ? -1 : 1;
  3602. var paintStyle = params.paintStyle || { lineWidth:1 };
  3603. this.loc = params.location == null ? 0.5 : params.location;
  3604. // how far along the arrow the lines folding back in come to. default is 62.3%.
  3605. var foldback = params.foldback || 0.623;
  3606. var _getFoldBackPoint = function(connector, loc) {
  3607. if (foldback == 0.5) return connector.pointOnPath(loc);
  3608. else {
  3609. var adj = 0.5 - foldback; // we calculate relative to the center
  3610. return connector.pointAlongPathFrom(loc, direction * self.length * adj);
  3611. }
  3612. };
  3613. this.computeMaxSize = function() { return self.width * 1.5; };
  3614. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  3615. // this is the arrow head position
  3616. var hxy = connector.pointAlongPathFrom(self.loc, direction * (self.length / 2));
  3617. // this is the center of the tail
  3618. var txy = connector.pointAlongPathFrom(self.loc, -1 * direction * (self.length / 2)), tx = txy.x, ty = txy.y;
  3619. // this is the tail vector
  3620. var tail = connector.perpendicularToPathAt(self.loc, self.width, -1 * direction * (self.length / 2));
  3621. // this is the point the tail goes in to
  3622. var cxy = _getFoldBackPoint(connector, self.loc);
  3623. // if loc = 1, then hxy should be flush with the element, or if direction == -1, the tail midpoint.
  3624. if (self.loc == 1) {
  3625. var lxy = connector.pointOnPath(self.loc);
  3626. // TODO determine why the 1.2.6 released version does not
  3627. // use 'direction' in the two equations below, yet both
  3628. // that and 1.3.0 still paint the arrows correctly.
  3629. var dx = (lxy.x - hxy.x) * direction, dy = (lxy.y - hxy.y) * direction;
  3630. cxy.x += dx; cxy.y += dy;
  3631. txy.x += dx; txy.y += dy;
  3632. tail[0].x += dx; tail[0].y += dy;
  3633. tail[1].x += dx; tail[1].y += dy;
  3634. hxy.x += dx; hxy.y += dy;
  3635. }
  3636. // if loc = 0, then tail midpoint should be flush with the element, or, if direction == -1, hxy should be.
  3637. if (self.loc == 0) {
  3638. var lxy = connector.pointOnPath(self.loc);
  3639. var tailMid = foldback > 1 ? cxy : {
  3640. x:tail[0].x + ((tail[1].x - tail[0].x) / 2),
  3641. y:tail[0].y + ((tail[1].y - tail[0].y) / 2)
  3642. };
  3643. var dx = (lxy.x - tailMid.x) * direction, dy = (lxy.y - tailMid.y) * direction;
  3644. cxy.x += dx; cxy.y += dy;
  3645. txy.x += dx; txy.y += dy;
  3646. tail[0].x += dx; tail[0].y += dy;
  3647. tail[1].x += dx; tail[1].y += dy;
  3648. hxy.x += dx; hxy.y += dy;
  3649. }
  3650. var minx = Math.min(hxy.x, tail[0].x, tail[1].x);
  3651. var maxx = Math.max(hxy.x, tail[0].x, tail[1].x);
  3652. var miny = Math.min(hxy.y, tail[0].y, tail[1].y);
  3653. var maxy = Math.max(hxy.y, tail[0].y, tail[1].y);
  3654. var d = { hxy:hxy, tail:tail, cxy:cxy },
  3655. strokeStyle = paintStyle.strokeStyle || currentConnectionPaintStyle.strokeStyle,
  3656. fillStyle = paintStyle.fillStyle || currentConnectionPaintStyle.strokeStyle,
  3657. lineWidth = paintStyle.lineWidth || currentConnectionPaintStyle.lineWidth;
  3658. self.paint(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions);
  3659. return [ minx, maxx, miny, maxy];
  3660. };
  3661. };
  3662. /**
  3663. * Class: Overlays.PlainArrow
  3664. *
  3665. * 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
  3666. * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
  3667. * a 'call' to Arrow with foldback set appropriately.
  3668. */
  3669. /**
  3670. * Function: Constructor
  3671. * See <Overlays.Arrow> for allowed parameters for this overlay.
  3672. */
  3673. jsPlumb.Overlays.PlainArrow = function(params) {
  3674. params = params || {};
  3675. var p = jsPlumb.extend(params, {foldback:1});
  3676. jsPlumb.Overlays.Arrow.call(this, p);
  3677. };
  3678. /**
  3679. * Class: Overlays.Diamond
  3680. *
  3681. * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
  3682. * happens that in this case, that point is greater than the length of the the arrow.
  3683. *
  3684. * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
  3685. * 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
  3686. * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
  3687. * would be -l/4 in this case - move along one quarter of the total length.
  3688. */
  3689. /**
  3690. * Function: Constructor
  3691. * See <Overlays.Arrow> for allowed parameters for this overlay.
  3692. */
  3693. jsPlumb.Overlays.Diamond = function(params) {
  3694. params = params || {};
  3695. var l = params.length || 40;
  3696. var p = jsPlumb.extend(params, {length:l/2, foldback:2});
  3697. jsPlumb.Overlays.Arrow.call(this, p);
  3698. };
  3699. /**
  3700. * Class: Overlays.Label
  3701. * 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
  3702. * 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
  3703. * 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
  3704. * puts on the Label's 'style' attribute, so the end result is the same.
  3705. */
  3706. /**
  3707. * Function: Constructor
  3708. *
  3709. * Parameters:
  3710. * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
  3711. * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
  3712. * 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
  3713. * label function returns null. empty strings _will_ be painted.
  3714. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  3715. * labelStyle - (deprecated) js object containing style instructions for the label. defaults to jsPlumb.Defaults.LabelStyle.
  3716. * borderWidth - (deprecated) width of a border to paint. defaults to zero.
  3717. * borderStyle - (deprecated) strokeStyle to use when painting the border, if necessary.
  3718. *
  3719. */
  3720. jsPlumb.Overlays.Label = function(params) {
  3721. jsPlumb.DOMElementComponent.apply(this, arguments);
  3722. this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle;
  3723. this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
  3724. this.label = params.label;
  3725. this.connection = params.connection;
  3726. this.id = params.id;
  3727. var self = this;
  3728. var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
  3729. this.location = params.location || 0.5;
  3730. this.cachedDimensions = null; // setting on 'this' rather than using closures uses a lot less memory. just don't monkey with it!
  3731. var initialised = false,
  3732. labelText = null,
  3733. div = document.createElement("div");
  3734. div.style["position"] = "absolute";
  3735. div.style["textAlign"] = "center";
  3736. div.style["cursor"] = "pointer";
  3737. div.style["font"] = self.labelStyle.font;
  3738. div.style["color"] = self.labelStyle.color || "black";
  3739. if (self.labelStyle.fillStyle) div.style["background"] = self.labelStyle.fillStyle;//_convertStyle(self.labelStyle.fillStyle, true);
  3740. if (self.labelStyle.borderWidth > 0) {
  3741. var dStyle = self.labelStyle.borderStyle ? self.labelStyle.borderStyle/*_convertStyle(self.labelStyle.borderStyle, true)*/ : "black";
  3742. div.style["border"] = self.labelStyle.borderWidth + "px solid " + dStyle;
  3743. }
  3744. if (self.labelStyle.padding) div.style["padding"] = self.labelStyle.padding;
  3745. var clazz = params["_jsPlumb"].overlayClass + " " +
  3746. (self.labelStyle.cssClass ? self.labelStyle.cssClass :
  3747. params.cssClass ? params.cssClass : "");
  3748. div.className = clazz;
  3749. jsPlumb.appendElement(div, params.connection.parent);
  3750. jsPlumb.getId(div);
  3751. self.attachListeners(div, self);
  3752. this.paint = function(connector, d, connectorDimensions) {
  3753. if (!initialised) {
  3754. connector.appendDisplayElement(div);
  3755. self.attachListeners(div, connector);
  3756. initialised = true;
  3757. }
  3758. div.style.left = (connectorDimensions[0] + d.minx) + "px";
  3759. div.style.top = (connectorDimensions[1] + d.miny) + "px";
  3760. };
  3761. this.getTextDimensions = function(connector) {
  3762. labelText = typeof self.label == 'function' ? self.label(self) : self.label;
  3763. div.innerHTML = labelText.replace(/\r\n/g, "<br/>");
  3764. var de = jsPlumb.CurrentLibrary.getElementObject(div),
  3765. s = jsPlumb.CurrentLibrary.getSize(de);
  3766. return {width:s[0], height:s[1]};
  3767. };
  3768. this.computeMaxSize = function(connector) {
  3769. var td = self.getTextDimensions(connector);
  3770. return td.width ? Math.max(td.width, td.height) * 1.5 : 0;
  3771. };
  3772. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  3773. var td = self.getTextDimensions(connector);
  3774. if (td.width != null) {
  3775. var cxy = connector.pointOnPath(self.location);
  3776. var minx = cxy.x - (td.width / 2);
  3777. var miny = cxy.y - (td.height / 2);
  3778. self.paint(connector, {
  3779. minx:minx,
  3780. miny:miny,
  3781. td:td,
  3782. cxy:cxy
  3783. }, connectorDimensions);
  3784. return [minx, minx+td.width, miny, miny+td.height];
  3785. }
  3786. else return [0,0,0,0];
  3787. };
  3788. };
  3789. // ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
  3790. // ********************************* OVERLAY CANVAS RENDERERS***********************************************************************
  3791. // ********************************* END OF OVERLAY CANVAS RENDERERS ***********************************************************************
  3792. })();;(function() {
  3793. // http://ajaxian.com/archives/the-vml-changes-in-ie-8
  3794. // http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/
  3795. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  3796. var vmlAttributeMap = {
  3797. "stroke-linejoin":"joinstyle",
  3798. "joinstyle":"joinstyle",
  3799. "endcap":"endcap",
  3800. "miterlimit":"miterlimit"
  3801. };
  3802. if (document.createStyleSheet) {
  3803. // this is the style rule for IE7/6: it uses a CSS class, tidy.
  3804. document.createStyleSheet().addRule(".jsplumb_vml", "behavior:url(#default#VML);position:absolute;");
  3805. // these are for VML in IE8. you have to explicitly call out which elements
  3806. // you're going to expect to support VML!
  3807. //
  3808. // try to avoid IE8. it is recommended you set X-UA-Compatible="IE=7" if you can.
  3809. //
  3810. document.createStyleSheet().addRule("jsplumb\\:textbox", "behavior:url(#default#VML);position:absolute;");
  3811. document.createStyleSheet().addRule("jsplumb\\:oval", "behavior:url(#default#VML);position:absolute;");
  3812. document.createStyleSheet().addRule("jsplumb\\:rect", "behavior:url(#default#VML);position:absolute;");
  3813. document.createStyleSheet().addRule("jsplumb\\:stroke", "behavior:url(#default#VML);position:absolute;");
  3814. document.createStyleSheet().addRule("jsplumb\\:shape", "behavior:url(#default#VML);position:absolute;");
  3815. // in this page it is also mentioned that IE requires the extra arg to the namespace
  3816. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  3817. // but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either.
  3818. // var iev = document.documentMode;
  3819. //if (!iev || iev < 8)
  3820. document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml");
  3821. //else
  3822. // document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML");
  3823. }
  3824. var scale = 1000,
  3825. _atts = function(o, atts) {
  3826. for (var i in atts) {
  3827. // IE8 fix: setattribute does not work after an element has been added to the dom!
  3828. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  3829. //o.setAttribute(i, atts[i]);
  3830. o[i] = atts[i];
  3831. }
  3832. },
  3833. _node = function(name, d, atts) {
  3834. atts = atts || {};
  3835. var o = document.createElement("jsplumb:" + name);
  3836. o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml";
  3837. _pos(o, d);
  3838. _atts(o, atts);
  3839. return o;
  3840. },
  3841. _pos = function(o,d) {
  3842. o.style.left = d[0] + "px";
  3843. o.style.top = d[1] + "px";
  3844. o.style.width= d[2] + "px";
  3845. o.style.height= d[3] + "px";
  3846. o.style.position = "absolute";
  3847. },
  3848. _conv = function(v) {
  3849. return Math.floor(v * scale);
  3850. },
  3851. _convertStyle = function(s, ignoreAlpha) {
  3852. var o = s,
  3853. pad = function(n) { return n.length == 1 ? "0" + n : n; },
  3854. hex = function(k) { return pad(Number(k).toString(16)); },
  3855. pattern = /(rgb[a]?\()(.*)(\))/;
  3856. if (s.match(pattern)) {
  3857. var parts = s.match(pattern)[2].split(",");
  3858. o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
  3859. if (!ignoreAlpha && parts.length == 4)
  3860. o = o + hex(parts[3]);
  3861. }
  3862. return o;
  3863. },
  3864. _applyStyles = function(node, style, component) {
  3865. var styleToWrite = {};
  3866. if (style.strokeStyle) {
  3867. styleToWrite["stroked"] = "true";
  3868. styleToWrite["strokecolor"] =_convertStyle(style.strokeStyle, true);
  3869. styleToWrite["strokeweight"] = style.lineWidth + "px";
  3870. }
  3871. else styleToWrite["stroked"] = "false";
  3872. if (style.fillStyle) {
  3873. styleToWrite["filled"] = "true";
  3874. styleToWrite["fillcolor"] = _convertStyle(style.fillStyle, true);
  3875. }
  3876. else styleToWrite["filled"] = "false";
  3877. if(style["dashstyle"]) {
  3878. if (component.strokeNode == null) {
  3879. component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] });
  3880. node.appendChild(component.strokeNode);
  3881. }
  3882. else
  3883. component.strokeNode.dashstyle = style["dashstyle"];
  3884. }
  3885. else if (style["stroke-dasharray"] && style["lineWidth"]) {
  3886. var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",",
  3887. parts = style["stroke-dasharray"].split(sep),
  3888. styleToUse = "";
  3889. for(var i = 0; i < parts.length; i++) {
  3890. styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep);
  3891. }
  3892. if (component.strokeNode == null) {
  3893. component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse });
  3894. node.appendChild(component.strokeNode);
  3895. }
  3896. else
  3897. component.strokeNode.dashstyle = styleToUse;
  3898. }
  3899. _atts(node, styleToWrite);
  3900. },
  3901. /*
  3902. * Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent.
  3903. */
  3904. VmlComponent = function() {
  3905. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  3906. },
  3907. /*
  3908. * Base class for Vml connectors. extends VmlComponent.
  3909. */
  3910. VmlConnector = function(params) {
  3911. var self = this;
  3912. self.strokeNode = null;
  3913. self.canvas = null;
  3914. VmlComponent.apply(this, arguments);
  3915. clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : "");
  3916. this.paint = function(d, style, anchor) {
  3917. if (style != null) {
  3918. var path = self.getPath(d), p = { "path":path };
  3919. if (style.outlineColor) {
  3920. var outlineWidth = style.outlineWidth || 1,
  3921. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  3922. outlineStyle = {
  3923. strokeStyle:_convertStyle(style.outlineColor),
  3924. lineWidth:outlineStrokeWidth
  3925. };
  3926. if (self.bgCanvas == null) {
  3927. p["class"] = clazz;
  3928. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  3929. self.bgCanvas = _node("shape", d, p);
  3930. jsPlumb.appendElement(self.bgCanvas, params.parent);
  3931. _pos(self.bgCanvas, d);
  3932. displayElements.push(self.bgCanvas);
  3933. }
  3934. else {
  3935. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  3936. _pos(self.bgCanvas, d);
  3937. _atts(self.bgCanvas, p);
  3938. }
  3939. _applyStyles(self.bgCanvas, outlineStyle, self);
  3940. }
  3941. if (self.canvas == null) {
  3942. p["class"] = clazz;
  3943. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  3944. self.canvas = _node("shape", d, p);
  3945. jsPlumb.appendElement(self.canvas, params.parent);
  3946. displayElements.push(self.canvas);
  3947. self.attachListeners(self.canvas, self);
  3948. }
  3949. else {
  3950. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  3951. _pos(self.canvas, d);
  3952. _atts(self.canvas, p);
  3953. }
  3954. _applyStyles(self.canvas, style, self);
  3955. }
  3956. };
  3957. var displayElements = [ self.canvas ];
  3958. this.getDisplayElements = function() {
  3959. return displayElements;
  3960. };
  3961. this.appendDisplayElement = function(el) {
  3962. self.canvas.parentNode.appendChild(el);
  3963. displayElements.push(el);
  3964. };
  3965. },
  3966. /*
  3967. *
  3968. * Base class for Vml Endpoints. extends VmlComponent.
  3969. *
  3970. */
  3971. VmlEndpoint = function(params) {
  3972. VmlComponent.apply(this, arguments);
  3973. var vml = null, self = this;
  3974. self.canvas = document.createElement("div");
  3975. self.canvas.style["position"] = "absolute";
  3976. jsPlumb.appendElement(self.canvas, params.parent);
  3977. this.paint = function(d, style, anchor) {
  3978. var p = { };
  3979. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  3980. if (vml == null) {
  3981. p["class"] = jsPlumb.endpointClass;
  3982. vml = self.getVml([0,0, d[2], d[3]], p, anchor);
  3983. self.canvas.appendChild(vml);
  3984. self.attachListeners(vml, self);
  3985. }
  3986. else {
  3987. //p["coordsize"] = "1,1";//(d[2] * scale) + "," + (d[3] * scale); again, unsure.
  3988. _pos(vml, [0,0, d[2], d[3]]);
  3989. _atts(vml, p);
  3990. }
  3991. _applyStyles(vml, style);
  3992. };
  3993. };
  3994. jsPlumb.Connectors.vml.Bezier = function() {
  3995. jsPlumb.Connectors.Bezier.apply(this, arguments);
  3996. VmlConnector.apply(this, arguments);
  3997. this.getPath = function(d) {
  3998. return "m" + _conv(d[4]) + "," + _conv(d[5]) +
  3999. " c" + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[10]) + "," + _conv(d[11]) + "," + _conv(d[6]) + "," + _conv(d[7]) + " e";
  4000. };
  4001. };
  4002. jsPlumb.Connectors.vml.Straight = function() {
  4003. jsPlumb.Connectors.Straight.apply(this, arguments);
  4004. VmlConnector.apply(this, arguments);
  4005. this.getPath = function(d) {
  4006. return "m" + _conv(d[4]) + "," + _conv(d[5]) + " l" + _conv(d[6]) + "," + _conv(d[7]) + " e";
  4007. };
  4008. };
  4009. jsPlumb.Connectors.vml.Flowchart = function() {
  4010. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  4011. VmlConnector.apply(this, arguments);
  4012. this.getPath = function(dimensions) {
  4013. var p = "m " + _conv(dimensions[4]) + "," + _conv(dimensions[5]) + " l";
  4014. // loop through extra points
  4015. for (var i = 0; i < dimensions[8]; i++) {
  4016. p = p + " " + _conv(dimensions[9 + (i*2)]) + "," + _conv(dimensions[10 + (i*2)]);
  4017. }
  4018. // finally draw a line to the end
  4019. p = p + " " + _conv(dimensions[6]) + "," + _conv(dimensions[7]) + " e";
  4020. return p;
  4021. };
  4022. };
  4023. jsPlumb.Endpoints.vml.Dot = function() {
  4024. jsPlumb.Endpoints.Dot.apply(this, arguments);
  4025. VmlEndpoint.apply(this, arguments);
  4026. this.getVml = function(d, atts, anchor) { return _node("oval", d, atts); };
  4027. };
  4028. jsPlumb.Endpoints.vml.Rectangle = function() {
  4029. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  4030. VmlEndpoint.apply(this, arguments);
  4031. this.getVml = function(d, atts, anchor) { return _node("rect", d, atts); };
  4032. };
  4033. /*
  4034. * VML Image Endpoint is the same as the default image endpoint.
  4035. */
  4036. jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image;
  4037. /**
  4038. * placeholder for Blank endpoint in vml renderer.
  4039. */
  4040. jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank;
  4041. /**
  4042. * VML Label renderer. uses the default label renderer (which adds an element to the DOM)
  4043. */
  4044. jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label;
  4045. var AbstractVmlArrowOverlay = function(superclass, originalArgs) {
  4046. superclass.apply(this, originalArgs);
  4047. VmlComponent.apply(this, arguments);
  4048. var self = this, canvas = null, path =null;
  4049. var getPath = function(d, connectorDimensions) {
  4050. return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) +
  4051. " l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) +
  4052. " " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) +
  4053. " " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) +
  4054. " x e";
  4055. };
  4056. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions) {
  4057. var p = {};
  4058. if (strokeStyle) {
  4059. p["stroked"] = "true";
  4060. p["strokecolor"] =_convertStyle(strokeStyle, true);
  4061. }
  4062. if (lineWidth) p["strokeweight"] = lineWidth + "px";
  4063. if (fillStyle) {
  4064. p["filled"] = "true";
  4065. p["fillcolor"] = fillStyle;
  4066. }
  4067. var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
  4068. ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
  4069. xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
  4070. ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
  4071. w = Math.abs(xmax - xmin),
  4072. h = Math.abs(ymax - ymin),
  4073. dim = [xmin, ymin, w, h];
  4074. // for VML, we create overlays using shapes that have the same dimensions and
  4075. // coordsize as their connector - overlays calculate themselves relative to the
  4076. // connector (it's how it's been done since the original canvas implementation, because
  4077. // for canvas that makes sense).
  4078. p["path"] = getPath(d, connectorDimensions);
  4079. p["coordsize"] = (connectorDimensions[2] * scale) + "," + (connectorDimensions[3] * scale);
  4080. dim[0] = connectorDimensions[0];
  4081. dim[1] = connectorDimensions[1];
  4082. dim[2] = connectorDimensions[2];
  4083. dim[3] = connectorDimensions[3];
  4084. if (canvas == null) {
  4085. //p["class"] = jsPlumb.overlayClass; // TODO currentInstance?
  4086. canvas = _node("shape", dim, p);
  4087. connector.appendDisplayElement(canvas);
  4088. self.attachListeners(canvas, connector);
  4089. }
  4090. else {
  4091. _pos(canvas, dim);
  4092. _atts(canvas, p);
  4093. }
  4094. };
  4095. };
  4096. jsPlumb.Overlays.vml.Arrow = function() {
  4097. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  4098. };
  4099. jsPlumb.Overlays.vml.PlainArrow = function() {
  4100. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  4101. };
  4102. jsPlumb.Overlays.vml.Diamond = function() {
  4103. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  4104. };
  4105. })();/**
  4106. * SVG support for jsPlumb.
  4107. *
  4108. * things to investigate:
  4109. *
  4110. * gradients: https://developer.mozilla.org/en/svg_in_html_introduction
  4111. * css:http://tutorials.jenkov.com/svg/svg-and-css.html
  4112. * text on a path: http://www.w3.org/TR/SVG/text.html#TextOnAPath
  4113. * pointer events: https://developer.mozilla.org/en/css/pointer-events
  4114. *
  4115. */
  4116. ;(function() {
  4117. var svgAttributeMap = {
  4118. "stroke-linejoin":"stroke-linejoin",
  4119. "joinstyle":"stroke-linejoin",
  4120. "stroke-dashoffset":"stroke-dashoffset"
  4121. };
  4122. var ns = {
  4123. svg:"http://www.w3.org/2000/svg",
  4124. xhtml:"http://www.w3.org/1999/xhtml"
  4125. },
  4126. _attr = function(node, attributes) {
  4127. for (var i in attributes)
  4128. node.setAttribute(i, "" + attributes[i]);
  4129. },
  4130. _node = function(name, attributes) {
  4131. var n = document.createElementNS(ns.svg, name);
  4132. attributes = attributes || {};
  4133. attributes["version"] = "1.1";
  4134. attributes["xmnls"] = ns.xhtml;
  4135. _attr(n, attributes);
  4136. return n;
  4137. },
  4138. _pos = function(d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; },
  4139. _convertStyle = function(s, ignoreAlpha) {
  4140. var o = s,
  4141. pad = function(n) { return n.length == 1 ? "0" + n : n; },
  4142. hex = function(k) { return pad(Number(k).toString(16)); },
  4143. pattern = /(rgb[a]?\()(.*)(\))/;
  4144. if (s.match(pattern)) {
  4145. var parts = s.match(pattern)[2].split(",");
  4146. o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
  4147. if (!ignoreAlpha && parts.length == 4)
  4148. o = o + hex(parts[3]);
  4149. }
  4150. return o;
  4151. },
  4152. _clearGradient = function(parent) {
  4153. for (var i = 0; i < parent.childNodes.length; i++) {
  4154. if (parent.childNodes[i].tagName == "linearGradient" || parent.childNodes[i].tagName == "radialGradient")
  4155. parent.removeChild(parent.childNodes[i]);
  4156. }
  4157. },
  4158. _updateGradient = function(parent, node, style, dimensions) {
  4159. var id = "jsplumb_gradient_" + (new Date()).getTime();
  4160. // first clear out any existing gradient
  4161. _clearGradient(parent);
  4162. // this checks for an 'offset' property in the gradient, and in the absence of it, assumes
  4163. // we want a linear gradient. if it's there, we create a radial gradient.
  4164. // it is possible that a more explicit means of defining the gradient type would be
  4165. // better. relying on 'offset' means that we can never have a radial gradient that uses
  4166. // some default offset, for instance.
  4167. if (!style.gradient.offset) {
  4168. var g = _node("linearGradient", {id:id});
  4169. parent.appendChild(g);
  4170. }
  4171. else {
  4172. var g = _node("radialGradient", {
  4173. id:id
  4174. });
  4175. parent.appendChild(g);
  4176. }
  4177. // the svg radial gradient seems to treat stops in the reverse
  4178. // order to how canvas does it. so we want to keep all the maths the same, but
  4179. // iterate the actual style declarations in reverse order, if the x indexes are not in order.
  4180. for (var i = 0; i < style.gradient.stops.length; i++) {
  4181. // Straight Connectors and Bezier connectors act slightly differently; this code is a bit of a kludge. but next version of
  4182. // jsplumb will be replacing both Straight and Bezier to be generic instances of 'Connector', which has a list of segments.
  4183. // so, not too concerned about leaving this in for now.
  4184. var styleToUse = i;
  4185. if (dimensions.length == 8)
  4186. styleToUse = dimensions[4] < dimensions[6] ? i: style.gradient.stops.length - 1 - i;
  4187. else
  4188. styleToUse = dimensions[4] < dimensions[6] ? style.gradient.stops.length - 1 - i : i;
  4189. var stopColor = _convertStyle(style.gradient.stops[styleToUse][1], true);
  4190. var s = _node("stop", {"offset":Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color":stopColor});
  4191. g.appendChild(s);
  4192. }
  4193. var applyGradientTo = style.strokeStyle ? "stroke" : "fill";
  4194. node.setAttribute("style", applyGradientTo + ":url(#" + id + ")");
  4195. },
  4196. _applyStyles = function(parent, node, style, dimensions) {
  4197. if (style.gradient) {
  4198. _updateGradient(parent, node, style, dimensions);
  4199. }
  4200. else {
  4201. // make sure we clear any existing gradient
  4202. _clearGradient(parent);
  4203. node.setAttribute("style", "");
  4204. }
  4205. node.setAttribute("fill", style.fillStyle ? _convertStyle(style.fillStyle, true) : "none");
  4206. node.setAttribute("stroke", style.strokeStyle ? _convertStyle(style.strokeStyle, true) : "none");
  4207. if (style.lineWidth) {
  4208. node.setAttribute("stroke-width", style.lineWidth);
  4209. }
  4210. // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
  4211. // the syntax in VML but is actually kind of nasty: values are given in the pixel
  4212. // coordinate space, whereas in VML they are multiples of the width of the stroked
  4213. // line, which makes a lot more sense. for that reason, jsPlumb is supporting both
  4214. // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
  4215. // VML, which will be the preferred method. the code below this converts a dashstyle
  4216. // attribute given in terms of stroke width into a pixel representation, by using the
  4217. // stroke's lineWidth.
  4218. if(style["stroke-dasharray"]) {
  4219. node.setAttribute("stroke-dasharray", style["stroke-dasharray"]);
  4220. }
  4221. if (style["dashstyle"] && style["lineWidth"]) {
  4222. var sep = style["dashstyle"].indexOf(",") == -1 ? " " : ",",
  4223. parts = style["dashstyle"].split(sep),
  4224. styleToUse = "";
  4225. parts.forEach(function(p) {
  4226. styleToUse += (Math.floor(p * style.lineWidth) + sep);
  4227. });
  4228. node.setAttribute("stroke-dasharray", styleToUse);
  4229. }
  4230. // extra attributes such as join type, dash offset.
  4231. for (var i in svgAttributeMap) {
  4232. if (style[i]) {
  4233. node.setAttribute(svgAttributeMap[i], style[i]);
  4234. }
  4235. }
  4236. },
  4237. _decodeFont = function(f) {
  4238. var r = /([0-9].)(p[xt])\s(.*)/;
  4239. var bits = f.match(r);
  4240. return {size:bits[1] + bits[2], font:bits[3]};
  4241. };
  4242. /*
  4243. * Base class for SVG components.
  4244. */
  4245. var SvgComponent = function(cssClass, originalArgs, pointerEventsSpec) {
  4246. var self = this;
  4247. pointerEventsSpec = pointerEventsSpec || "all";
  4248. jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
  4249. self.canvas = null, self.path = null, self.svg = null;
  4250. this.setHover = function() { };
  4251. self.canvas = document.createElement("div");
  4252. self.canvas.style["position"] = "absolute";
  4253. jsPlumb.sizeCanvas(self.canvas,0,0,1,1);
  4254. var clazz = cssClass + " " + (originalArgs[0].cssClass || "");
  4255. self.svg = _node("svg", {
  4256. "style":"",
  4257. "width":0,
  4258. "height":0,
  4259. "pointer-events":pointerEventsSpec,
  4260. "class": clazz
  4261. });
  4262. jsPlumb.appendElement(self.canvas, originalArgs[0]["parent"]);
  4263. self.canvas.appendChild(self.svg);
  4264. // TODO this displayElement stuff is common between all components, across all
  4265. // renderers. would be best moved to jsPlumbUIComponent.
  4266. var displayElements = [ self.canvas ];
  4267. this.getDisplayElements = function() {
  4268. return displayElements;
  4269. };
  4270. this.appendDisplayElement = function(el) {
  4271. displayElements.push(el);
  4272. };
  4273. this.paint = function(d, style, anchor) {
  4274. if (style != null) {
  4275. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  4276. _attr(self.svg, {
  4277. "style":_pos([0,0,d[2], d[3]]),
  4278. "width": d[2],
  4279. "height": d[3]
  4280. });
  4281. self._paint.apply(this, arguments);
  4282. }
  4283. };
  4284. };
  4285. /*
  4286. * Base class for SVG connectors.
  4287. */
  4288. var SvgConnector = function(params) {
  4289. var self = this;
  4290. SvgComponent.apply(this, [ params["_jsPlumb"].connectorClass, arguments, "none" ]);
  4291. this._paint = function(d, style) {
  4292. var p = self.getPath(d), a = { "d":p }, outlineStyle = null;
  4293. a["pointer-events"] = "all";
  4294. // outline style. actually means drawing an svg object underneath the main one.
  4295. if (style.outlineColor) {
  4296. var outlineWidth = style.outlineWidth || 1,
  4297. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  4298. outlineStyle = {
  4299. strokeStyle:_convertStyle(style.outlineColor),
  4300. lineWidth:outlineStrokeWidth
  4301. };
  4302. if (self.bgPath == null) {
  4303. self.bgPath = _node("path", a);
  4304. self.svg.appendChild(self.bgPath);
  4305. self.attachListeners(self.bgPath, self);
  4306. }
  4307. else {
  4308. _attr(self.bgPath, a);
  4309. }
  4310. _applyStyles(self.svg, self.bgPath, outlineStyle, d);
  4311. }
  4312. if (self.path == null) {
  4313. self.path = _node("path", a);
  4314. self.svg.appendChild(self.path);
  4315. self.attachListeners(self.path, self);
  4316. }
  4317. else {
  4318. _attr(self.path, a);
  4319. }
  4320. _applyStyles(self.svg, self.path, style, d);
  4321. };
  4322. };
  4323. /*
  4324. * SVG Bezier Connector
  4325. */
  4326. jsPlumb.Connectors.svg.Bezier = function(params) {
  4327. jsPlumb.Connectors.Bezier.apply(this, arguments);
  4328. SvgConnector.apply(this, arguments);
  4329. this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " C " + d[8] + " " + d[9] + " " + d[10] + " " + d[11] + " " + d[6] + " " + d[7]; };
  4330. };
  4331. /*
  4332. * SVG straight line Connector
  4333. */
  4334. jsPlumb.Connectors.svg.Straight = function(params) {
  4335. jsPlumb.Connectors.Straight.apply(this, arguments);
  4336. SvgConnector.apply(this, arguments);
  4337. this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " L " + d[6] + " " + d[7]; };
  4338. };
  4339. jsPlumb.Connectors.svg.Flowchart = function() {
  4340. var self = this;
  4341. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  4342. SvgConnector.apply(this, arguments);
  4343. this.getPath = function(dimensions) {
  4344. var p = "M " + dimensions[4] + "," + dimensions[5];
  4345. // loop through extra points
  4346. for (var i = 0; i < dimensions[8]; i++) {
  4347. p = p + " L " + dimensions[9 + (i*2)] + " " + dimensions[10 + (i*2)];
  4348. }
  4349. // finally draw a line to the end
  4350. p = p + " " + dimensions[6] + "," + dimensions[7];
  4351. return p;
  4352. };
  4353. };
  4354. /*
  4355. * Base class for SVG endpoints.
  4356. */
  4357. var SvgEndpoint = function(params) {
  4358. var self = this;
  4359. SvgComponent.apply(this, [ params["_jsPlumb"].endpointClass, arguments, "all" ]);
  4360. this._paint = function(d, style) {
  4361. var s = jsPlumb.extend({}, style);
  4362. if (s.outlineColor) {
  4363. s.strokeWidth = s.outlineWidth;
  4364. s.strokeStyle = _convertStyle(s.outlineColor, true);
  4365. }
  4366. if (self.node == null) {
  4367. self.node = self.makeNode(d, s);
  4368. self.svg.appendChild(self.node);
  4369. self.attachListeners(self.node, self);
  4370. }
  4371. _applyStyles(self.svg, self.node, s, d);
  4372. _pos(self.node, d);
  4373. };
  4374. };
  4375. /*
  4376. * SVG Dot Endpoint
  4377. */
  4378. jsPlumb.Endpoints.svg.Dot = function() {
  4379. jsPlumb.Endpoints.Dot.apply(this, arguments);
  4380. SvgEndpoint.apply(this, arguments);
  4381. this.makeNode = function(d, style) {
  4382. return _node("circle", {
  4383. "cx" : d[2] / 2,
  4384. "cy" : d[3] / 2,
  4385. "r" : d[2] / 2
  4386. });
  4387. };
  4388. };
  4389. /*
  4390. * SVG Rectangle Endpoint
  4391. */
  4392. jsPlumb.Endpoints.svg.Rectangle = function() {
  4393. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  4394. SvgEndpoint.apply(this, arguments);
  4395. this.makeNode = function(d, style) {
  4396. return _node("rect", {
  4397. "width":d[2],
  4398. "height":d[3]
  4399. });
  4400. };
  4401. };
  4402. /*
  4403. * SVG Image Endpoint is the default image endpoint.
  4404. */
  4405. jsPlumb.Endpoints.svg.Image = jsPlumb.Endpoints.Image;
  4406. /*
  4407. * Blank endpoint in svg renderer is the default Blank endpoint.
  4408. */
  4409. jsPlumb.Endpoints.svg.Blank = jsPlumb.Endpoints.Blank;
  4410. /*
  4411. * Label endpoint in svg renderer is the default Label endpoint.
  4412. */
  4413. jsPlumb.Overlays.svg.Label = jsPlumb.Overlays.Label;
  4414. var AbstractSvgArrowOverlay = function(superclass, originalArgs) {
  4415. superclass.apply(this, originalArgs);
  4416. jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
  4417. var self = this, path =null;
  4418. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  4419. if (path == null) {
  4420. path = _node("path");
  4421. connector.svg.appendChild(path);
  4422. self.attachListeners(path, connector);
  4423. self.attachListeners(path, self);
  4424. }
  4425. _attr(path, {
  4426. "d" : makePath(d),
  4427. stroke : strokeStyle ? strokeStyle : null,
  4428. fill : fillStyle ? fillStyle : null
  4429. });
  4430. };
  4431. var makePath = function(d) {
  4432. return "M" + d.hxy.x + "," + d.hxy.y +
  4433. " L" + d.tail[0].x + "," + d.tail[0].y +
  4434. " L" + d.cxy.x + "," + d.cxy.y +
  4435. " L" + d.tail[1].x + "," + d.tail[1].y +
  4436. " L" + d.hxy.x + "," + d.hxy.y;
  4437. };
  4438. };
  4439. jsPlumb.Overlays.svg.Arrow = function() {
  4440. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  4441. };
  4442. jsPlumb.Overlays.svg.PlainArrow = function() {
  4443. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  4444. };
  4445. jsPlumb.Overlays.svg.Diamond = function() {
  4446. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  4447. };
  4448. })();;(function() {
  4449. // ********************************* CANVAS RENDERERS FOR CONNECTORS AND ENDPOINTS *******************************************************************
  4450. // TODO refactor to renderer common script. put a ref to jsPlumb.sizeCanvas in there too.
  4451. var _connectionBeingDragged = null,
  4452. _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); },
  4453. _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); },
  4454. _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); },
  4455. _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
  4456. _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); },
  4457. _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
  4458. _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
  4459. _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); },
  4460. _pageXY = function(el) { return jsPlumb.CurrentLibrary.getPageXY(el); },
  4461. _clientXY = function(el) { return jsPlumb.CurrentLibrary.getClientXY(el); },
  4462. _setOffset = function(el, o) { jsPlumb.CurrentLibrary.setOffset(el, o); };
  4463. /*
  4464. * Class:CanvasMouseAdapter
  4465. * Provides support for mouse events on canvases.
  4466. */
  4467. var CanvasMouseAdapter = function() {
  4468. var self = this;
  4469. self.overlayPlacements = [];
  4470. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  4471. jsPlumb.EventGenerator.apply(this, arguments);
  4472. /**
  4473. * returns whether or not the given event is ojver a painted area of the canvas.
  4474. */
  4475. this._over = function(e) {
  4476. var o = _getOffset(_getElementObject(self.canvas)),
  4477. pageXY = _pageXY(e),
  4478. x = pageXY[0] - o.left, y = pageXY[1] - o.top;
  4479. if (x > 0 && y > 0 && x < self.canvas.width && y < self.canvas.height) {
  4480. // first check overlays
  4481. for ( var i = 0; i < self.overlayPlacements.length; i++) {
  4482. var p = self.overlayPlacements[i];
  4483. if (p && (p[0] <= x && p[1] >= x && p[2] <= y && p[3] >= y))
  4484. return true;
  4485. }
  4486. // then the canvas
  4487. var d = self.canvas.getContext("2d").getImageData(parseInt(x), parseInt(y), 1, 1);
  4488. return d.data[0] != 0 || d.data[1] != 0 || d.data[2] != 0 || d.data[3] != 0;
  4489. }
  4490. return false;
  4491. };
  4492. var _mouseover = false;
  4493. var _mouseDown = false, _posWhenMouseDown = null, _mouseWasDown = false;
  4494. var _nullSafeHasClass = function(el, clazz) {
  4495. return el != null && _hasClass(el, clazz);
  4496. };
  4497. this.mousemove = function(e) {
  4498. var pageXY = _pageXY(e), clientXY = _clientXY(e),
  4499. ee = document.elementFromPoint(clientXY[0], clientXY[1]),
  4500. eventSourceWasOverlay = _nullSafeHasClass(ee, "_jsPlumb_overlay");
  4501. var _continue = _connectionBeingDragged == null && (_nullSafeHasClass(ee, "_jsPlumb_endpoint") || _nullSafeHasClass(ee, "_jsPlumb_connector"));
  4502. if (!_mouseover && _continue && self._over(e)) {
  4503. _mouseover = true;
  4504. self.fire("mouseenter", self, e);
  4505. return true;
  4506. }
  4507. // TODO here there is a remote chance that the overlay the mouse moved onto
  4508. // is actually not an overlay for the current component. a more thorough check would
  4509. // be to ensure the overlay belonged to the current component.
  4510. else if (_mouseover && (!self._over(e) || !_continue) && !eventSourceWasOverlay) {
  4511. _mouseover = false;
  4512. self.fire("mouseexit", self, e);
  4513. }
  4514. self.fire("mousemove", self, e);
  4515. };
  4516. this.click = function(e) {
  4517. if (_mouseover && self._over(e) && !_mouseWasDown)
  4518. self.fire("click", self, e);
  4519. _mouseWasDown = false;
  4520. };
  4521. this.dblclick = function(e) {
  4522. if (_mouseover && self._over(e) && !_mouseWasDown)
  4523. self.fire("dblclick", self, e);
  4524. _mouseWasDown = false;
  4525. };
  4526. this.mousedown = function(e) {
  4527. if(self._over(e) && !_mouseDown) {
  4528. _mouseDown = true;
  4529. _posWhenMouseDown = _getOffset(_getElementObject(self.canvas));
  4530. self.fire("mousedown", self, e);
  4531. }
  4532. };
  4533. this.mouseup = function(e) {
  4534. //if (self == _connectionBeingDragged) _connectionBeingDragged = null;
  4535. _mouseDown = false;
  4536. self.fire("mouseup", self, e);
  4537. };
  4538. };
  4539. var _newCanvas = function(params) {
  4540. var canvas = document.createElement("canvas");
  4541. jsPlumb.appendElement(canvas, params.parent);
  4542. canvas.style.position = "absolute";
  4543. if (params["class"]) canvas.className = params["class"];
  4544. // set an id. if no id on the element and if uuid was supplied it
  4545. // will be used, otherwise we'll create one.
  4546. params["_jsPlumb"].getId(canvas, params.uuid);
  4547. return canvas;
  4548. };
  4549. /**
  4550. * Class:CanvasConnector
  4551. * Superclass for Canvas Connector renderers.
  4552. */
  4553. var CanvasConnector = jsPlumb.CanvasConnector = function(params) {
  4554. CanvasMouseAdapter.apply(this, arguments);
  4555. var _paintOneStyle = function(dim, aStyle) {
  4556. self.ctx.save();
  4557. jsPlumb.extend(self.ctx, aStyle);
  4558. if (aStyle.gradient) {
  4559. var g = self.createGradient(dim, self.ctx);
  4560. for ( var i = 0; i < aStyle.gradient.stops.length; i++)
  4561. g.addColorStop(aStyle.gradient.stops[i][0], aStyle.gradient.stops[i][1]);
  4562. self.ctx.strokeStyle = g;
  4563. }
  4564. self._paint(dim);
  4565. self.ctx.restore();
  4566. };
  4567. var self = this,
  4568. clazz = self._jsPlumb.connectorClass + " " + (params.cssClass || "");
  4569. self.canvas = _newCanvas({
  4570. "class":clazz,
  4571. _jsPlumb:self._jsPlumb,
  4572. parent:params.parent
  4573. });
  4574. self.ctx = self.canvas.getContext("2d");
  4575. var displayElements = [ self.canvas ];
  4576. this.getDisplayElements = function() {
  4577. return displayElements;
  4578. };
  4579. this.appendDisplayElement = function(el) {
  4580. displayElements.push(el);
  4581. };
  4582. self.paint = function(dim, style) {
  4583. if (style != null) {
  4584. jsPlumb.sizeCanvas(self.canvas, dim[0], dim[1], dim[2], dim[3]);
  4585. if (style.outlineColor != null) {
  4586. var outlineWidth = style.outlineWidth || 1,
  4587. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  4588. var outlineStyle = {
  4589. strokeStyle:style.outlineColor,
  4590. lineWidth:outlineStrokeWidth
  4591. };
  4592. _paintOneStyle(dim, outlineStyle);
  4593. }
  4594. _paintOneStyle(dim, style);
  4595. }
  4596. };
  4597. };
  4598. /**
  4599. * Class:CanvasEndpoint
  4600. * Superclass for Canvas Endpoint renderers.
  4601. */
  4602. var CanvasEndpoint = function(params) {
  4603. var self = this;
  4604. CanvasMouseAdapter.apply(this, arguments);
  4605. var clazz = self._jsPlumb.endpointClass + " " + (params.cssClass || "");
  4606. self.canvas = _newCanvas({
  4607. "class":clazz,
  4608. _jsPlumb:self._jsPlumb,
  4609. parent:params.parent
  4610. });
  4611. self.ctx = self.canvas.getContext("2d");
  4612. this.paint = function(d, style, anchor) {
  4613. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  4614. if (style.outlineColor != null) {
  4615. var outlineWidth = style.outlineWidth || 1,
  4616. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  4617. var outlineStyle = {
  4618. strokeStyle:style.outlineColor,
  4619. lineWidth:outlineStrokeWidth
  4620. };
  4621. // _paintOneStyle(d, outlineStyle);
  4622. }
  4623. self._paint.apply(this, arguments);
  4624. };
  4625. };
  4626. jsPlumb.Endpoints.canvas.Dot = function(params) {
  4627. var self = this;
  4628. jsPlumb.Endpoints.Dot.apply(this, arguments);
  4629. CanvasEndpoint.apply(this, arguments);
  4630. var parseValue = function(value) {
  4631. try {
  4632. return parseInt(value);
  4633. }
  4634. catch(e) {
  4635. if (value.substring(value.length - 1) == '%')
  4636. return parseInt(value.substring(0, value - 1));
  4637. }
  4638. };
  4639. var calculateAdjustments = function(gradient) {
  4640. var offsetAdjustment = self.defaultOffset, innerRadius = self.defaultInnerRadius;
  4641. gradient.offset && (offsetAdjustment = parseValue(gradient.offset));
  4642. gradient.innerRadius && (innerRadius = parseValue(gradient.innerRadius));
  4643. return [offsetAdjustment, innerRadius];
  4644. };
  4645. this._paint = function(d, style, anchor) {
  4646. if (style != null) {
  4647. var ctx = self.canvas.getContext('2d'), orientation = anchor.getOrientation();
  4648. jsPlumb.extend(ctx, style);
  4649. if (style.gradient) {
  4650. var adjustments = calculateAdjustments(style.gradient),
  4651. yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0],
  4652. xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0],
  4653. g = ctx.createRadialGradient(d[4], d[4], d[4], d[4] + xAdjust, d[4] + yAdjust, adjustments[1]);
  4654. for (var i = 0; i < style.gradient.stops.length; i++)
  4655. g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
  4656. ctx.fillStyle = g;
  4657. }
  4658. ctx.beginPath();
  4659. ctx.arc(d[4], d[4], d[4], 0, Math.PI*2, true);
  4660. ctx.closePath();
  4661. if (style.fillStyle || style.gradient) ctx.fill();
  4662. if (style.strokeStyle) ctx.stroke();
  4663. }
  4664. };
  4665. };
  4666. jsPlumb.Endpoints.canvas.Rectangle = function(params) {
  4667. var self = this;
  4668. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  4669. CanvasEndpoint.apply(this, arguments);
  4670. this._paint = function(d, style, anchor) {
  4671. var ctx = self.canvas.getContext("2d"), orientation = anchor.getOrientation();
  4672. jsPlumb.extend(ctx, style);
  4673. /* canvas gradient */
  4674. if (style.gradient) {
  4675. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  4676. var y1 = orientation[1] == 1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
  4677. var y2 = orientation[1] == -1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
  4678. var x1 = orientation[0] == 1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
  4679. var x2 = orientation[0] == -1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
  4680. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  4681. for (var i = 0; i < style.gradient.stops.length; i++)
  4682. g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
  4683. ctx.fillStyle = g;
  4684. }
  4685. ctx.beginPath();
  4686. ctx.rect(0, 0, d[2], d[3]);
  4687. ctx.closePath();
  4688. if (style.fillStyle || style.gradient) ctx.fill();
  4689. if (style.strokeStyle) ctx.stroke();
  4690. };
  4691. };
  4692. jsPlumb.Endpoints.canvas.Triangle = function(params) {
  4693. var self = this;
  4694. jsPlumb.Endpoints.Triangle.apply(this, arguments);
  4695. CanvasEndpoint.apply(this, arguments);
  4696. this._paint = function(d, style, anchor)
  4697. {
  4698. var width = d[2], height = d[3], x = d[0], y = d[1];
  4699. var ctx = self.canvas.getContext('2d');
  4700. var offsetX = 0, offsetY = 0, angle = 0;
  4701. if( orientation[0] == 1 )
  4702. {
  4703. offsetX = width;
  4704. offsetY = height;
  4705. angle = 180;
  4706. }
  4707. if( orientation[1] == -1 )
  4708. {
  4709. offsetX = width;
  4710. angle = 90;
  4711. }
  4712. if( orientation[1] == 1 )
  4713. {
  4714. offsetY = height;
  4715. angle = -90;
  4716. }
  4717. ctx.fillStyle = style.fillStyle;
  4718. ctx.translate(offsetX, offsetY);
  4719. ctx.rotate(angle * Math.PI/180);
  4720. ctx.beginPath();
  4721. ctx.moveTo(0, 0);
  4722. ctx.lineTo(width/2, height/2);
  4723. ctx.lineTo(0, height);
  4724. ctx.closePath();
  4725. if (style.fillStyle || style.gradient) ctx.fill();
  4726. if (style.strokeStyle) ctx.stroke();
  4727. };
  4728. };
  4729. /*
  4730. * Canvas Image Endpoint: uses the default version, which creates an <img> tag.
  4731. */
  4732. jsPlumb.Endpoints.canvas.Image = jsPlumb.Endpoints.Image;
  4733. /*
  4734. * Blank endpoint in all renderers is just the default Blank endpoint.
  4735. */
  4736. jsPlumb.Endpoints.canvas.Blank = jsPlumb.Endpoints.Blank;
  4737. /*
  4738. * Canvas Bezier Connector. Draws a Bezier curve onto a Canvas element.
  4739. */
  4740. jsPlumb.Connectors.canvas.Bezier = function() {
  4741. var self = this;
  4742. jsPlumb.Connectors.Bezier.apply(this, arguments);
  4743. CanvasConnector.apply(this, arguments);
  4744. this._paint = function(dimensions) {
  4745. self.ctx.beginPath();
  4746. self.ctx.moveTo(dimensions[4], dimensions[5]);
  4747. self.ctx.bezierCurveTo(dimensions[8], dimensions[9], dimensions[10], dimensions[11], dimensions[6], dimensions[7]);
  4748. self.ctx.stroke();
  4749. };
  4750. // TODO i doubt this handles the case that source and target are swapped.
  4751. this.createGradient = function(dim, ctx, swap) {
  4752. return /*(swap) ? self.ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : */self.ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  4753. };
  4754. };
  4755. /*
  4756. * Canvas straight line Connector. Draws a straight line onto a Canvas element.
  4757. */
  4758. jsPlumb.Connectors.canvas.Straight = function() {
  4759. var self = this;
  4760. jsPlumb.Connectors.Straight.apply(this, arguments);
  4761. CanvasConnector.apply(this, arguments);
  4762. this._paint = function(dimensions) {
  4763. self.ctx.beginPath();
  4764. self.ctx.moveTo(dimensions[4], dimensions[5]);
  4765. self.ctx.lineTo(dimensions[6], dimensions[7]);
  4766. self.ctx.stroke();
  4767. };
  4768. // TODO this does not handle the case that src and target are swapped.
  4769. this.createGradient = function(dim, ctx) {
  4770. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  4771. };
  4772. };
  4773. jsPlumb.Connectors.canvas.Flowchart = function() {
  4774. var self = this;
  4775. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  4776. CanvasConnector.apply(this, arguments);
  4777. this._paint = function(dimensions) {
  4778. self.ctx.beginPath();
  4779. self.ctx.moveTo(dimensions[4], dimensions[5]);
  4780. // loop through extra points
  4781. for (var i = 0; i < dimensions[8]; i++) {
  4782. self.ctx.lineTo(dimensions[9 + (i*2)], dimensions[10 + (i*2)]);
  4783. }
  4784. // finally draw a line to the end
  4785. self.ctx.lineTo(dimensions[6], dimensions[7]);
  4786. self.ctx.stroke();
  4787. };
  4788. this.createGradient = function(dim, ctx) {
  4789. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  4790. };
  4791. };
  4792. // ********************************* END OF CANVAS RENDERERS *******************************************************************
  4793. jsPlumb.Overlays.canvas.Label = jsPlumb.Overlays.Label;
  4794. /**
  4795. * a placeholder right now, really just exists to mirror the fact that there are SVG and VML versions of this.
  4796. */
  4797. var CanvasOverlay = function() {
  4798. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  4799. };
  4800. var AbstractCanvasArrowOverlay = function(superclass, originalArgs) {
  4801. superclass.apply(this, originalArgs);
  4802. CanvasOverlay.apply(this, arguments);
  4803. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  4804. var ctx = connector.ctx;
  4805. ctx.lineWidth = lineWidth;
  4806. ctx.beginPath();
  4807. ctx.moveTo(d.hxy.x, d.hxy.y);
  4808. ctx.lineTo(d.tail[0].x, d.tail[0].y);
  4809. ctx.lineTo(d.cxy.x, d.cxy.y);
  4810. ctx.lineTo(d.tail[1].x, d.tail[1].y);
  4811. ctx.lineTo(d.hxy.x, d.hxy.y);
  4812. ctx.closePath();
  4813. if (strokeStyle) {
  4814. ctx.strokeStyle = strokeStyle;
  4815. ctx.stroke();
  4816. }
  4817. if (fillStyle) {
  4818. ctx.fillStyle = fillStyle;
  4819. ctx.fill();
  4820. }
  4821. };
  4822. };
  4823. jsPlumb.Overlays.canvas.Arrow = function() {
  4824. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  4825. };
  4826. jsPlumb.Overlays.canvas.PlainArrow = function() {
  4827. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  4828. };
  4829. jsPlumb.Overlays.canvas.Diamond = function() {
  4830. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  4831. };
  4832. })();/*
  4833. * mootools.jsPlumb 1.3.0-RC1
  4834. *
  4835. * MooTools specific functionality for jsPlumb.
  4836. *
  4837. * http://morrisonpitt.com/jsPlumb/demo.html
  4838. * http://code.google.com/p/jsPlumb
  4839. *
  4840. * NOTE: for production usage you should use mootools.jsPlumb-all-x.x.x-min.js, which contains the main jsPlumb script and this script together,
  4841. * in a minified file.
  4842. *
  4843. * Dual licensed under MIT and GPL2.
  4844. *
  4845. */
  4846. ;(function() {
  4847. /*
  4848. * overrides the FX class to inject 'step' functionality, which MooTools does not
  4849. * offer, and which makes me sad. they don't seem keen to add it, either, despite
  4850. * the fact that it could be useful:
  4851. *
  4852. * https://mootools.lighthouseapp.com/projects/2706/tickets/668
  4853. *
  4854. */
  4855. var jsPlumbMorph = new Class({
  4856. Extends:Fx.Morph,
  4857. onStep : null,
  4858. initialize : function(el, options) {
  4859. this.parent(el, options);
  4860. if (options['onStep']) {
  4861. this.onStep = options['onStep'];
  4862. }
  4863. },
  4864. step : function(now) {
  4865. this.parent(now);
  4866. if (this.onStep) {
  4867. try { this.onStep(); }
  4868. catch(e) { }
  4869. }
  4870. }
  4871. });
  4872. var _droppables = {},
  4873. _droppableOptions = {},
  4874. _draggablesByScope = {},
  4875. _draggablesById = {};
  4876. /*
  4877. *
  4878. */
  4879. var _executeDroppableOption = function(el, dr, event) {
  4880. if (dr) {
  4881. var id = dr.get("id");
  4882. if (id) {
  4883. var options = _droppableOptions[id];
  4884. if (options) {
  4885. if (options[event]) {
  4886. options[event](el, dr);
  4887. }
  4888. }
  4889. }
  4890. }
  4891. };
  4892. var _checkHover = function(el, entering) {
  4893. if (el) {
  4894. var id = el.get("id");
  4895. if (id) {
  4896. var options = _droppableOptions[id];
  4897. if (options) {
  4898. if (options['hoverClass']) {
  4899. if (entering) el.addClass(options['hoverClass']);
  4900. else el.removeClass(options['hoverClass']);
  4901. }
  4902. }
  4903. }
  4904. }
  4905. };
  4906. /**
  4907. * adds the given value to the given list, with the given scope. creates the scoped list
  4908. * if necessary.
  4909. * used by initDraggable and initDroppable.
  4910. */
  4911. var _add = function(list, scope, value) {
  4912. var l = list[scope];
  4913. if (!l) {
  4914. l = [];
  4915. list[scope] = l;
  4916. }
  4917. l.push(value);
  4918. };
  4919. /*
  4920. * gets an "element object" from the given input. this means an object that is used by the
  4921. * underlying library on which jsPlumb is running. 'el' may already be one of these objects,
  4922. * in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
  4923. * function is used to find the element, using the given String as the element's id.
  4924. */
  4925. var _getElementObject = function(el) {
  4926. return $(el);
  4927. };
  4928. jsPlumb.CurrentLibrary = {
  4929. /**
  4930. * adds the given class to the element object.
  4931. */
  4932. addClass : function(el, clazz) {
  4933. el.addClass(clazz);
  4934. },
  4935. animate : function(el, properties, options) {
  4936. var m = new jsPlumbMorph(el, options);
  4937. m.start(properties);
  4938. },
  4939. appendElement : function(child, parent) {
  4940. _getElementObject(parent).grab(child);
  4941. },
  4942. bind : function(el, event, callback) {
  4943. el = _getElementObject(el);
  4944. el.addEvent(event, callback);
  4945. },
  4946. dragEvents : {
  4947. 'start':'onStart', 'stop':'onComplete', 'drag':'onDrag', 'step':'onStep',
  4948. 'over':'onEnter', 'out':'onLeave','drop':'onDrop', 'complete':'onComplete'
  4949. },
  4950. /*
  4951. * wrapper around the library's 'extend' functionality (which it hopefully has.
  4952. * otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
  4953. * instead. it's not like its hard.
  4954. */
  4955. extend : function(o1, o2) {
  4956. return $extend(o1, o2);
  4957. },
  4958. /**
  4959. * gets the named attribute from the given element object.
  4960. */
  4961. getAttribute : function(el, attName) {
  4962. return el.get(attName);
  4963. },
  4964. getClientXY : function(eventObject) {
  4965. return [eventObject.event.clientX, eventObject.event.clientY];
  4966. },
  4967. getDragObject : function(eventArgs) {
  4968. return eventArgs[0];
  4969. },
  4970. getDragScope : function(el) {
  4971. var id = jsPlumb.getId(el);
  4972. var drags = _draggablesById[id];
  4973. return drags[0].scope;
  4974. },
  4975. getElementObject : _getElementObject,
  4976. /*
  4977. gets the offset for the element object. this should return a js object like this:
  4978. { left:xxx, top: xxx}
  4979. */
  4980. getOffset : function(el) {
  4981. var p = el.getPosition();
  4982. return { left:p.x, top:p.y };
  4983. },
  4984. getPageXY : function(eventObject) {
  4985. return [eventObject.event.pageX, eventObject.event.pageY];
  4986. },
  4987. getParent : function(el) {
  4988. return jsPlumb.CurrentLibrary.getElementObject(el).getParent();
  4989. },
  4990. getScrollLeft : function(el) {
  4991. return null;
  4992. },
  4993. getScrollTop : function(el) {
  4994. return null;
  4995. },
  4996. getSize : function(el) {
  4997. var s = el.getSize();
  4998. return [s.x, s.y];
  4999. },
  5000. /*
  5001. * takes the args passed to an event function and returns you an object that gives the
  5002. * position of the object being moved, as a js object with the same params as the result of
  5003. * getOffset, ie: { left: xxx, top: xxx }.
  5004. */
  5005. getUIPosition : function(eventArgs) {
  5006. var ui = eventArgs[0],
  5007. p = jsPlumb.CurrentLibrary.getElementObject(ui).getPosition();
  5008. return { left:p.x, top:p.y };
  5009. },
  5010. hasClass : function(el, clazz) {
  5011. return el.hasClass(clazz);
  5012. },
  5013. initDraggable : function(el, options) {
  5014. var id = jsPlumb.getId(el);
  5015. var drag = _draggablesById[id];
  5016. if (!drag) {
  5017. var originalZIndex = 0, originalCursor = null;
  5018. var dragZIndex = jsPlumb.Defaults.DragOptions.zIndex || 2000;
  5019. options['onStart'] = jsPlumb.wrap(options['onStart'], function()
  5020. {
  5021. originalZIndex = this.element.getStyle('z-index');
  5022. this.element.setStyle('z-index', dragZIndex);
  5023. if (jsPlumb.Defaults.DragOptions.cursor) {
  5024. originalCursor = this.element.getStyle('cursor');
  5025. this.element.setStyle('cursor', jsPlumb.Defaults.DragOptions.cursor);
  5026. }
  5027. });
  5028. options['onComplete'] = jsPlumb.wrap(options['onComplete'], function()
  5029. {
  5030. this.element.setStyle('z-index', originalZIndex);
  5031. if (originalCursor) {
  5032. this.element.setStyle('cursor', originalCursor);
  5033. }
  5034. });
  5035. // DROPPABLES:
  5036. var scope = options['scope'] || jsPlumb.Defaults.Scope;
  5037. var filterFunc = function(entry) {
  5038. return entry.get("id") != el.get("id");
  5039. };
  5040. var droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
  5041. options['droppables'] = droppables;
  5042. options['onLeave'] = jsPlumb.wrap(options['onLeave'], function(el, dr) {
  5043. if (dr) {
  5044. _checkHover(dr, false);
  5045. _executeDroppableOption(el, dr, 'onLeave');
  5046. }
  5047. });
  5048. options['onEnter'] = jsPlumb.wrap(options['onEnter'], function(el, dr) {
  5049. if (dr) {
  5050. _checkHover(dr, true);
  5051. _executeDroppableOption(el, dr, 'onEnter');
  5052. }
  5053. });
  5054. options['onDrop'] = function(el, dr) {
  5055. if (dr) {
  5056. _checkHover(dr, false);
  5057. _executeDroppableOption(el, dr, 'onDrop');
  5058. }
  5059. };
  5060. drag = new Drag.Move(el, options);
  5061. drag.scope = scope;
  5062. //console.log("drag scope initialized to ", scope);
  5063. _add(_draggablesByScope, scope, drag);
  5064. _add(_draggablesById, el.get("id"), drag);
  5065. // test for disabled.
  5066. if (options.disabled) drag.detach();
  5067. }
  5068. return drag;
  5069. },
  5070. initDroppable : function(el, options) {
  5071. var scope = options['scope'] || jsPlumb.Defaults.Scope;
  5072. _add(_droppables, scope, el);
  5073. var id = jsPlumb.getId(el);
  5074. _droppableOptions[id] = options;
  5075. var filterFunc = function(entry) { return entry.element != el; };
  5076. var draggables = _draggablesByScope[scope] ? _draggablesByScope[scope].filter(filterFunc) : [];
  5077. for (var i = 0; i < draggables.length; i++) {
  5078. draggables[i].droppables.push(el);
  5079. }
  5080. },
  5081. isAlreadyDraggable : function(el) {
  5082. return _draggablesById[jsPlumb.getId(el)] != null;
  5083. },
  5084. isDragSupported : function(el, options) {
  5085. return typeof Drag != 'undefined' ;
  5086. },
  5087. /*
  5088. * you need Drag.Move imported to make drop work.
  5089. */
  5090. isDropSupported : function(el, options) {
  5091. return (typeof Drag != undefined && typeof Drag.Move != undefined);
  5092. },
  5093. /**
  5094. * removes the given class from the element object.
  5095. */
  5096. removeClass : function(el, clazz) {
  5097. el.removeClass(clazz);
  5098. },
  5099. removeElement : function(element, parent) {
  5100. _getElementObject(element).dispose(); // ??
  5101. },
  5102. /**
  5103. * sets the named attribute on the given element object.
  5104. */
  5105. setAttribute : function(el, attName, attValue) {
  5106. el.set(attName, attValue);
  5107. },
  5108. setDraggable : function(el, draggable) {
  5109. var draggables = _draggablesById[el.get("id")];
  5110. if (draggables) {
  5111. draggables.each(function(d) {
  5112. if (draggable) d.attach(); else d.detach();
  5113. });
  5114. }
  5115. },
  5116. setDragScope : function(el, scope) {
  5117. var drag = _draggablesById[el.get("id")];
  5118. var filterFunc = function(entry) {
  5119. return entry.get("id") != el.get("id");
  5120. };
  5121. var droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
  5122. drag[0].droppables = droppables;
  5123. },
  5124. setOffset : function(el, o) {
  5125. _getElementObject(el).setPosition({x:o.left, y:o.top});
  5126. }
  5127. };
  5128. window.addEvent('domready', jsPlumb.init);
  5129. })();
  5130. (function(){if(typeof Math.sgn=="undefined")Math.sgn=function(a){return a==0?0:a>0?1:-1};var p={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}}},y=Math.pow(2,-65),u=function(a,b){for(var g=[],d=b.length-1,h=2*d-1,f=[],c=[],l=[],k=[],i=[[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++)f[e]=p.subtract(b[e],a);for(e=0;e<=d-1;e++){c[e]=
  5131. p.subtract(b[e+1],b[e]);c[e]=p.scale(c[e],3)}for(e=0;e<=d-1;e++)for(var m=0;m<=d;m++){l[e]||(l[e]=[]);l[e][m]=p.dotProduct(c[e],f[m])}for(e=0;e<=h;e++){k[e]||(k[e]=[]);k[e].y=0;k[e].x=parseFloat(e)/h}h=d-1;for(f=0;f<=d+h;f++){c=Math.min(f,d);for(e=Math.max(0,f-h);e<=c;e++){j=f-e;k[e+j].y+=l[j][e]*i[j][e]}}d=b.length-1;k=s(k,2*d-1,g,0);h=p.subtract(a,b[0]);l=p.square(h);for(e=i=0;e<k;e++){h=p.subtract(a,t(b,d,g[e],null,null));h=p.square(h);if(h<l){l=h;i=g[e]}}h=p.subtract(a,b[d]);h=p.square(h);if(h<
  5132. l){l=h;i=1}return{location:i,distance:l}},s=function(a,b,g,d){var h=[],f=[],c=[],l=[],k=0,i,e;e=Math.sgn(a[0].y);for(var m=1;m<=b;m++){i=Math.sgn(a[m].y);i!=e&&k++;e=i}switch(k){case 0:return 0;case 1:if(d>=64){g[0]=(a[0].x+a[b].x)/2;return 1}var n,o,q;k=a[0].y-a[b].y;i=a[b].x-a[0].x;e=a[0].x*a[b].y-a[b].x*a[0].y;m=max_distance_below=0;for(o=1;o<b;o++){q=k*a[o].x+i*a[o].y+e;if(q>m)m=q;else if(q<max_distance_below)max_distance_below=q}n=k;o=i;q=e-m;n=0*o-n*1;n=1/n;m=(1*q-o*0)*n;n=k;o=i;q=e-max_distance_below;
  5133. n=0*o-n*1;n=1/n;k=(1*q-o*0)*n;if(Math.max(m,k)-Math.min(m,k)<y?1:0){c=a[b].x-a[0].x;l=a[b].y-a[0].y;g[0]=0+1*(c*(a[0].y-0)-l*(a[0].x-0))*(1/(c*0-l*1));return 1}}t(a,b,0.5,h,f);a=s(h,b,c,d+1);b=s(f,b,l,d+1);for(d=0;d<a;d++)g[d]=c[d];for(d=0;d<b;d++)g[d+a]=l[d];return a+b},t=function(a,b,g,d,h){for(var f=[[]],c=0;c<=b;c++)f[0][c]=a[c];for(a=1;a<=b;a++)for(c=0;c<=b-a;c++){f[a]||(f[a]=[]);f[a][c]||(f[a][c]={});f[a][c].x=(1-g)*f[a-1][c].x+g*f[a-1][c+1].x;f[a][c].y=(1-g)*f[a-1][c].y+g*f[a-1][c+1].y}if(d!=
  5134. null)for(c=0;c<=b;c++)d[c]=f[c][0];if(h!=null)for(c=0;c<=b;c++)h[c]=f[b-c][c];return f[b][0]},v={},z=function(a){var b=v[a];if(!b){b=[];var g=function(i){return function(){return i}},d=function(){return function(i){return i}},h=function(){return function(i){return 1-i}},f=function(i){return function(e){for(var m=1,n=0;n<i.length;n++)m*=i[n](e);return m}};b.push(new function(){return function(i){return Math.pow(i,a)}});for(var c=1;c<a;c++){for(var l=[new g(a)],k=0;k<a-c;k++)l.push(new d);for(k=0;k<
  5135. c;k++)l.push(new h);b.push(new f(l))}b.push(new function(){return function(i){return Math.pow(1-i,a)}});v[a]=b}return b},r=function(a,b){for(var g=z(a.length-1),d=0,h=0,f=0;f<a.length;f++){d+=a[f].x*g[f](b);h+=a[f].y*g[f](b)}return{x:d,y:h}},w=function(a,b,g){var d=r(a,b),h=0;b=b;for(var f=g>0?1:-1,c=null;h<Math.abs(g);){b+=0.0050*f;c=r(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}},x=function(a,b){var g=r(a,b),d=r(a.slice(0,a.length-1),b);return Math.atan((d.y-
  5136. g.y)/(d.x-g.x))};window.jsBezier={distanceFromCurve:u,gradientAtPoint:x,nearestPointOnCurve:function(a,b){var g=u(a,b);return{point:t(b,b.length-1,g.location,null,null),location:g.location}},pointOnCurve:r,pointAlongCurveFrom:function(a,b,g){return w(a,b,g).point},perpendicularToCurveAt:function(a,b,g,d){d=d==null?0:d;b=w(a,b,d);a=x(a,b.location);d=Math.atan(-1/a);a=g/2*Math.sin(d);g=g/2*Math.cos(d);return[{x:b.point.x+g,y:b.point.y+a},{x:b.point.x-g,y:b.point.y-a}]}}})();