jquery.jsPlumb.all.js 342 KB

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