jsplumb2.js 608 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645
  1. /**
  2. * jsBezier
  3. *
  4. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  5. *
  6. * licensed under the MIT license.
  7. *
  8. * a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier
  9. * curves of arbitrary degree.
  10. *
  11. * - functions are all in the 'jsBezier' namespace.
  12. *
  13. * - all input points should be in the format {x:.., y:..}. all output points are in this format too.
  14. *
  15. * - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ]
  16. *
  17. * - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length
  18. * of the curve. location as output has the same format and meaning.
  19. *
  20. *
  21. * Function List:
  22. * --------------
  23. *
  24. * distanceFromCurve(point, curve)
  25. *
  26. * Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier,
  27. * so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values
  28. * of the curve and the point - it will most likely be pixels.
  29. *
  30. * gradientAtPoint(curve, location)
  31. *
  32. * Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive.
  33. *
  34. * gradientAtPointAlongCurveFrom (curve, location)
  35. *
  36. * Calculates the gradient at the point on the given curve that is 'distance' units from location.
  37. *
  38. * nearestPointOnCurve(point, curve)
  39. *
  40. * Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the
  41. *point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }.
  42. *
  43. * pointOnCurve(curve, location)
  44. *
  45. * Calculates the coordinates of the point on the given Bezier curve at the given location.
  46. *
  47. * pointAlongCurveFrom(curve, location, distance)
  48. *
  49. * Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
  50. * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
  51. *
  52. * locationAlongCurveFrom(curve, location, distance)
  53. *
  54. * Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
  55. * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
  56. *
  57. * perpendicularToCurveAt(curve, location, length, distance)
  58. *
  59. * Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered
  60. * on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of
  61. * the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ].
  62. *
  63. *
  64. */
  65. (function() {
  66. var root = this;
  67. if(typeof Math.sgn == "undefined") {
  68. Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; };
  69. }
  70. var Vectors = {
  71. subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; },
  72. dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); },
  73. square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); },
  74. scale : function(v, s) { return {x:v.x * s, y:v.y * s }; }
  75. },
  76. maxRecursion = 64,
  77. flatnessTolerance = Math.pow(2.0,-maxRecursion-1);
  78. /**
  79. * Calculates the distance that the point lies from the curve.
  80. *
  81. * @param point a point in the form {x:567, y:3342}
  82. * @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently
  83. * hardcoded to assume cubiz beziers, but would be better off supporting any degree.
  84. * @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location
  85. * argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from
  86. * the point to the curve.
  87. */
  88. var _distanceFromCurve = function(point, curve) {
  89. var candidates = [],
  90. w = _convertToBezier(point, curve),
  91. degree = curve.length - 1, higherDegree = (2 * degree) - 1,
  92. numSolutions = _findRoots(w, higherDegree, candidates, 0),
  93. v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0;
  94. for (var i = 0; i < numSolutions; i++) {
  95. v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null));
  96. var newDist = Vectors.square(v);
  97. if (newDist < dist) {
  98. dist = newDist;
  99. t = candidates[i];
  100. }
  101. }
  102. v = Vectors.subtract(point, curve[degree]);
  103. newDist = Vectors.square(v);
  104. if (newDist < dist) {
  105. dist = newDist;
  106. t = 1.0;
  107. }
  108. return {location:t, distance:dist};
  109. };
  110. /**
  111. * finds the nearest point on the curve to the given point.
  112. */
  113. var _nearestPointOnCurve = function(point, curve) {
  114. var td = _distanceFromCurve(point, curve);
  115. return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location};
  116. };
  117. var _convertToBezier = function(point, curve) {
  118. var degree = curve.length - 1, higherDegree = (2 * degree) - 1,
  119. c = [], d = [], cdTable = [], w = [],
  120. z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ];
  121. for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point);
  122. for (var i = 0; i <= degree - 1; i++) {
  123. d[i] = Vectors.subtract(curve[i+1], curve[i]);
  124. d[i] = Vectors.scale(d[i], 3.0);
  125. }
  126. for (var row = 0; row <= degree - 1; row++) {
  127. for (var column = 0; column <= degree; column++) {
  128. if (!cdTable[row]) cdTable[row] = [];
  129. cdTable[row][column] = Vectors.dotProduct(d[row], c[column]);
  130. }
  131. }
  132. for (i = 0; i <= higherDegree; i++) {
  133. if (!w[i]) w[i] = [];
  134. w[i].y = 0.0;
  135. w[i].x = parseFloat(i) / higherDegree;
  136. }
  137. var n = degree, m = degree-1;
  138. for (var k = 0; k <= n + m; k++) {
  139. var lb = Math.max(0, k - m),
  140. ub = Math.min(k, n);
  141. for (i = lb; i <= ub; i++) {
  142. j = k - i;
  143. w[i+j].y += cdTable[j][i] * z[j][i];
  144. }
  145. }
  146. return w;
  147. };
  148. /**
  149. * counts how many roots there are.
  150. */
  151. var _findRoots = function(w, degree, t, depth) {
  152. var left = [], right = [],
  153. left_count, right_count,
  154. left_t = [], right_t = [];
  155. switch (_getCrossingCount(w, degree)) {
  156. case 0 : {
  157. return 0;
  158. }
  159. case 1 : {
  160. if (depth >= maxRecursion) {
  161. t[0] = (w[0].x + w[degree].x) / 2.0;
  162. return 1;
  163. }
  164. if (_isFlatEnough(w, degree)) {
  165. t[0] = _computeXIntercept(w, degree);
  166. return 1;
  167. }
  168. break;
  169. }
  170. }
  171. _bezier(w, degree, 0.5, left, right);
  172. left_count = _findRoots(left, degree, left_t, depth+1);
  173. right_count = _findRoots(right, degree, right_t, depth+1);
  174. for (var i = 0; i < left_count; i++) t[i] = left_t[i];
  175. for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i];
  176. return (left_count+right_count);
  177. };
  178. var _getCrossingCount = function(curve, degree) {
  179. var n_crossings = 0, sign, old_sign;
  180. sign = old_sign = Math.sgn(curve[0].y);
  181. for (var i = 1; i <= degree; i++) {
  182. sign = Math.sgn(curve[i].y);
  183. if (sign != old_sign) n_crossings++;
  184. old_sign = sign;
  185. }
  186. return n_crossings;
  187. };
  188. var _isFlatEnough = function(curve, degree) {
  189. var error,
  190. intercept_1, intercept_2, left_intercept, right_intercept,
  191. a, b, c, det, dInv, a1, b1, c1, a2, b2, c2;
  192. a = curve[0].y - curve[degree].y;
  193. b = curve[degree].x - curve[0].x;
  194. c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y;
  195. var max_distance_above = max_distance_below = 0.0;
  196. for (var i = 1; i < degree; i++) {
  197. var value = a * curve[i].x + b * curve[i].y + c;
  198. if (value > max_distance_above)
  199. max_distance_above = value;
  200. else if (value < max_distance_below)
  201. max_distance_below = value;
  202. }
  203. a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b;
  204. c2 = c - max_distance_above;
  205. det = a1 * b2 - a2 * b1;
  206. dInv = 1.0/det;
  207. intercept_1 = (b1 * c2 - b2 * c1) * dInv;
  208. a2 = a; b2 = b; c2 = c - max_distance_below;
  209. det = a1 * b2 - a2 * b1;
  210. dInv = 1.0/det;
  211. intercept_2 = (b1 * c2 - b2 * c1) * dInv;
  212. left_intercept = Math.min(intercept_1, intercept_2);
  213. right_intercept = Math.max(intercept_1, intercept_2);
  214. error = right_intercept - left_intercept;
  215. return (error < flatnessTolerance)? 1 : 0;
  216. };
  217. var _computeXIntercept = function(curve, degree) {
  218. var XLK = 1.0, YLK = 0.0,
  219. XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y,
  220. XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0,
  221. det = XNM*YLK - YNM*XLK, detInv = 1.0/det,
  222. S = (XNM*YMK - YNM*XMK) * detInv;
  223. return 0.0 + XLK * S;
  224. };
  225. var _bezier = function(curve, degree, t, left, right) {
  226. var temp = [[]];
  227. for (var j =0; j <= degree; j++) temp[0][j] = curve[j];
  228. for (var i = 1; i <= degree; i++) {
  229. for (var j =0 ; j <= degree - i; j++) {
  230. if (!temp[i]) temp[i] = [];
  231. if (!temp[i][j]) temp[i][j] = {};
  232. temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x;
  233. temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y;
  234. }
  235. }
  236. if (left != null)
  237. for (j = 0; j <= degree; j++) left[j] = temp[j][0];
  238. if (right != null)
  239. for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j];
  240. return (temp[degree][0]);
  241. };
  242. var _curveFunctionCache = {};
  243. var _getCurveFunctions = function(order) {
  244. var fns = _curveFunctionCache[order];
  245. if (!fns) {
  246. fns = [];
  247. var f_term = function() { return function(t) { return Math.pow(t, order); }; },
  248. l_term = function() { return function(t) { return Math.pow((1-t), order); }; },
  249. c_term = function(c) { return function(t) { return c; }; },
  250. t_term = function() { return function(t) { return t; }; },
  251. one_minus_t_term = function() { return function(t) { return 1-t; }; },
  252. _termFunc = function(terms) {
  253. return function(t) {
  254. var p = 1;
  255. for (var i = 0; i < terms.length; i++) p = p * terms[i](t);
  256. return p;
  257. };
  258. };
  259. fns.push(new f_term()); // first is t to the power of the curve order
  260. for (var i = 1; i < order; i++) {
  261. var terms = [new c_term(order)];
  262. for (var j = 0 ; j < (order - i); j++) terms.push(new t_term());
  263. for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term());
  264. fns.push(new _termFunc(terms));
  265. }
  266. fns.push(new l_term()); // last is (1-t) to the power of the curve order
  267. _curveFunctionCache[order] = fns;
  268. }
  269. return fns;
  270. };
  271. /**
  272. * calculates a point on the curve, for a Bezier of arbitrary order.
  273. * @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points.
  274. * @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive.
  275. */
  276. var _pointOnPath = function(curve, location) {
  277. var cc = _getCurveFunctions(curve.length - 1),
  278. _x = 0, _y = 0;
  279. for (var i = 0; i < curve.length ; i++) {
  280. _x = _x + (curve[i].x * cc[i](location));
  281. _y = _y + (curve[i].y * cc[i](location));
  282. }
  283. return {x:_x, y:_y};
  284. };
  285. var _dist = function(p1,p2) {
  286. return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
  287. };
  288. var _isPoint = function(curve) {
  289. return curve[0].x == curve[1].x && curve[0].y == curve[1].y;
  290. };
  291. /**
  292. * finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also
  293. * its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the
  294. * point.
  295. */
  296. var _pointAlongPath = function(curve, location, distance) {
  297. if (_isPoint(curve)) {
  298. return {
  299. point:curve[0],
  300. location:location
  301. };
  302. }
  303. var prev = _pointOnPath(curve, location),
  304. tally = 0,
  305. curLoc = location,
  306. direction = distance > 0 ? 1 : -1,
  307. cur = null;
  308. while (tally < Math.abs(distance)) {
  309. curLoc += (0.005 * direction);
  310. cur = _pointOnPath(curve, curLoc);
  311. tally += _dist(cur, prev);
  312. prev = cur;
  313. }
  314. return {point:cur, location:curLoc};
  315. };
  316. var _length = function(curve) {
  317. if (_isPoint(curve)) return 0;
  318. var prev = _pointOnPath(curve, 0),
  319. tally = 0,
  320. curLoc = 0,
  321. direction = 1,
  322. cur = null;
  323. while (curLoc < 1) {
  324. curLoc += (0.005 * direction);
  325. cur = _pointOnPath(curve, curLoc);
  326. tally += _dist(cur, prev);
  327. prev = cur;
  328. }
  329. return tally;
  330. };
  331. /**
  332. * finds the point that is 'distance' along the path from 'location'.
  333. */
  334. var _pointAlongPathFrom = function(curve, location, distance) {
  335. return _pointAlongPath(curve, location, distance).point;
  336. };
  337. /**
  338. * finds the location that is 'distance' along the path from 'location'.
  339. */
  340. var _locationAlongPathFrom = function(curve, location, distance) {
  341. return _pointAlongPath(curve, location, distance).location;
  342. };
  343. /**
  344. * returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive.
  345. *
  346. * thanks // http://bimixual.org/AnimationLibrary/beziertangents.html
  347. */
  348. var _gradientAtPoint = function(curve, location) {
  349. var p1 = _pointOnPath(curve, location),
  350. p2 = _pointOnPath(curve.slice(0, curve.length - 1), location),
  351. dy = p2.y - p1.y, dx = p2.x - p1.x;
  352. return dy == 0 ? Infinity : Math.atan(dy / dx);
  353. };
  354. /**
  355. returns the gradient of the curve at the point which is 'distance' from the given location.
  356. if this point is greater than location 1, the gradient at location 1 is returned.
  357. if this point is less than location 0, the gradient at location 0 is returned.
  358. */
  359. var _gradientAtPointAlongPathFrom = function(curve, location, distance) {
  360. var p = _pointAlongPath(curve, location, distance);
  361. if (p.location > 1) p.location = 1;
  362. if (p.location < 0) p.location = 0;
  363. return _gradientAtPoint(curve, p.location);
  364. };
  365. /**
  366. * calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  367. * if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero).
  368. */
  369. var _perpendicularToPathAt = function(curve, location, length, distance) {
  370. distance = distance == null ? 0 : distance;
  371. var p = _pointAlongPath(curve, location, distance),
  372. m = _gradientAtPoint(curve, p.location),
  373. _theta2 = Math.atan(-1 / m),
  374. y = length / 2 * Math.sin(_theta2),
  375. x = length / 2 * Math.cos(_theta2);
  376. return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}];
  377. };
  378. var jsBezier = this.jsBezier = {
  379. distanceFromCurve : _distanceFromCurve,
  380. gradientAtPoint : _gradientAtPoint,
  381. gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom,
  382. nearestPointOnCurve : _nearestPointOnCurve,
  383. pointOnCurve : _pointOnPath,
  384. pointAlongCurveFrom : _pointAlongPathFrom,
  385. perpendicularToCurveAt : _perpendicularToPathAt,
  386. locationAlongCurveFrom:_locationAlongPathFrom,
  387. getLength:_length,
  388. version:"0.9.0"
  389. };
  390. if (typeof exports !== "undefined") {
  391. exports.jsBezier = jsBezier;
  392. }
  393. }).call(typeof window !== 'undefined' ? window : this);
  394. /**
  395. * Biltong v0.4.0
  396. *
  397. * Various geometry functions written as part of jsPlumb and perhaps useful for others.
  398. *
  399. * Copyright (c) 2017 jsPlumb
  400. * https://jsplumbtoolkit.com
  401. *
  402. * Permission is hereby granted, free of charge, to any person
  403. * obtaining a copy of this software and associated documentation
  404. * files (the "Software"), to deal in the Software without
  405. * restriction, including without limitation the rights to use,
  406. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  407. * copies of the Software, and to permit persons to whom the
  408. * Software is furnished to do so, subject to the following
  409. * conditions:
  410. *
  411. * The above copyright notice and this permission notice shall be
  412. * included in all copies or substantial portions of the Software.
  413. *
  414. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  415. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  416. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  417. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  418. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  419. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  420. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  421. * OTHER DEALINGS IN THE SOFTWARE.
  422. */
  423. ;(function() {
  424. "use strict";
  425. var root = this;
  426. var Biltong = root.Biltong = {
  427. version:"0.4.0"
  428. };
  429. if (typeof exports !== "undefined") {
  430. exports.Biltong = Biltong;
  431. }
  432. var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; },
  433. _pointHelper = function(p1, p2, fn) {
  434. p1 = _isa(p1) ? p1 : [p1.x, p1.y];
  435. p2 = _isa(p2) ? p2 : [p2.x, p2.y];
  436. return fn(p1, p2);
  437. },
  438. /**
  439. * @name Biltong.gradient
  440. * @function
  441. * @desc Calculates the gradient of a line between the two points.
  442. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  443. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  444. * @return {Float} The gradient of a line between the two points.
  445. */
  446. _gradient = Biltong.gradient = function(p1, p2) {
  447. return _pointHelper(p1, p2, function(_p1, _p2) {
  448. if (_p2[0] == _p1[0])
  449. return _p2[1] > _p1[1] ? Infinity : -Infinity;
  450. else if (_p2[1] == _p1[1])
  451. return _p2[0] > _p1[0] ? 0 : -0;
  452. else
  453. return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]);
  454. });
  455. },
  456. /**
  457. * @name Biltong.normal
  458. * @function
  459. * @desc Calculates the gradient of a normal to a line between the two points.
  460. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  461. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  462. * @return {Float} The gradient of a normal to a line between the two points.
  463. */
  464. _normal = Biltong.normal = function(p1, p2) {
  465. return -1 / _gradient(p1, p2);
  466. },
  467. /**
  468. * @name Biltong.lineLength
  469. * @function
  470. * @desc Calculates the length of a line between the two points.
  471. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  472. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  473. * @return {Float} The length of a line between the two points.
  474. */
  475. _lineLength = Biltong.lineLength = function(p1, p2) {
  476. return _pointHelper(p1, p2, function(_p1, _p2) {
  477. return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2));
  478. });
  479. },
  480. /**
  481. * @name Biltong.quadrant
  482. * @function
  483. * @desc Calculates the quadrant in which the angle between the two points lies.
  484. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  485. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  486. * @return {Integer} The quadrant - 1 for upper right, 2 for lower right, 3 for lower left, 4 for upper left.
  487. */
  488. _quadrant = Biltong.quadrant = function(p1, p2) {
  489. return _pointHelper(p1, p2, function(_p1, _p2) {
  490. if (_p2[0] > _p1[0]) {
  491. return (_p2[1] > _p1[1]) ? 2 : 1;
  492. }
  493. else if (_p2[0] == _p1[0]) {
  494. return _p2[1] > _p1[1] ? 2 : 1;
  495. }
  496. else {
  497. return (_p2[1] > _p1[1]) ? 3 : 4;
  498. }
  499. });
  500. },
  501. /**
  502. * @name Biltong.theta
  503. * @function
  504. * @desc Calculates the angle between the two points.
  505. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  506. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  507. * @return {Float} The angle between the two points.
  508. */
  509. _theta = Biltong.theta = function(p1, p2) {
  510. return _pointHelper(p1, p2, function(_p1, _p2) {
  511. var m = _gradient(_p1, _p2),
  512. t = Math.atan(m),
  513. s = _quadrant(_p1, _p2);
  514. if ((s == 4 || s== 3)) t += Math.PI;
  515. if (t < 0) t += (2 * Math.PI);
  516. return t;
  517. });
  518. },
  519. /**
  520. * @name Biltong.intersects
  521. * @function
  522. * @desc Calculates whether or not the two rectangles intersect.
  523. * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
  524. * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
  525. * @return {Boolean} True if the rectangles intersect, false otherwise.
  526. */
  527. _intersects = Biltong.intersects = function(r1, r2) {
  528. var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
  529. a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h;
  530. return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
  531. ( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
  532. ( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
  533. ( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
  534. ( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
  535. ( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
  536. ( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) ||
  537. ( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) );
  538. },
  539. /**
  540. * @name Biltong.encloses
  541. * @function
  542. * @desc Calculates whether or not r2 is completely enclosed by r1.
  543. * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
  544. * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
  545. * @param {Boolean} [allowSharedEdges=false] If true, the concept of enclosure allows for one or more edges to be shared by the two rectangles.
  546. * @return {Boolean} True if r1 encloses r2, false otherwise.
  547. */
  548. _encloses = Biltong.encloses = function(r1, r2, allowSharedEdges) {
  549. var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
  550. a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h,
  551. c = function(v1, v2, v3, v4) { return allowSharedEdges ? v1 <= v2 && v3>= v4 : v1 < v2 && v3 > v4; };
  552. return c(x1,a1,x2,a2) && c(y1,b1,y2,b2);
  553. },
  554. _segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
  555. _inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
  556. /**
  557. * @name Biltong.pointOnLine
  558. * @function
  559. * @desc Calculates a point on the line from `fromPoint` to `toPoint` that is `distance` units along the length of the line.
  560. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  561. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  562. * @return {Point} Point on the line, in the form `{ x:..., y:... }`.
  563. */
  564. _pointOnLine = Biltong.pointOnLine = function(fromPoint, toPoint, distance) {
  565. var m = _gradient(fromPoint, toPoint),
  566. s = _quadrant(fromPoint, toPoint),
  567. segmentMultiplier = distance > 0 ? _segmentMultipliers[s] : _inverseSegmentMultipliers[s],
  568. theta = Math.atan(m),
  569. y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
  570. x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
  571. return { x:fromPoint.x + x, y:fromPoint.y + y };
  572. },
  573. /**
  574. * @name Biltong.perpendicularLineTo
  575. * @function
  576. * @desc Calculates a line of length `length` that is perpendicular to the line from `fromPoint` to `toPoint` and passes through `toPoint`.
  577. * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
  578. * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
  579. * @return {Line} Perpendicular line, in the form `[ { x:..., y:... }, { x:..., y:... } ]`.
  580. */
  581. _perpendicularLineTo = Biltong.perpendicularLineTo = function(fromPoint, toPoint, length) {
  582. var m = _gradient(fromPoint, toPoint),
  583. theta2 = Math.atan(-1 / m),
  584. y = length / 2 * Math.sin(theta2),
  585. x = length / 2 * Math.cos(theta2);
  586. return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
  587. };
  588. }).call(typeof window !== 'undefined' ? window : this);
  589. ;
  590. (function () {
  591. "use strict";
  592. var root = this,
  593. Sniff = {
  594. android: navigator.userAgent.toLowerCase().indexOf("android") > -1
  595. },
  596. matchesSelector = function (el, selector, ctx) {
  597. ctx = ctx || el.parentNode;
  598. var possibles = ctx.querySelectorAll(selector);
  599. for (var i = 0; i < possibles.length; i++) {
  600. if (possibles[i] === el) {
  601. return true;
  602. }
  603. }
  604. return false;
  605. },
  606. _gel = function (el) {
  607. return (typeof el == "string" || el.constructor === String) ? document.getElementById(el) : el;
  608. },
  609. _t = function (e) {
  610. return e.srcElement || e.target;
  611. },
  612. //
  613. // gets path info for the given event - the path from target to obj, in the event's bubble chain. if doCompute
  614. // is false we just return target for the path.
  615. //
  616. _pi = function(e, target, obj, doCompute) {
  617. if (!doCompute) return { path:[target], end:1 };
  618. else if (typeof e.path !== "undefined" && e.path.indexOf) {
  619. return { path: e.path, end: e.path.indexOf(obj) };
  620. } else {
  621. var out = { path:[], end:-1 }, _one = function(el) {
  622. out.path.push(el);
  623. if (el === obj) {
  624. out.end = out.path.length - 1;
  625. }
  626. else if (el.parentNode != null) {
  627. _one(el.parentNode)
  628. }
  629. };
  630. _one(target);
  631. return out;
  632. }
  633. },
  634. _d = function (l, fn) {
  635. for (var i = 0, j = l.length; i < j; i++) {
  636. if (l[i] == fn) break;
  637. }
  638. if (i < l.length) l.splice(i, 1);
  639. },
  640. guid = 1,
  641. //
  642. // this function generates a guid for every handler, sets it on the handler, then adds
  643. // it to the associated object's map of handlers for the given event. this is what enables us
  644. // to unbind all events of some type, or all events (the second of which can be requested by the user,
  645. // but it also used by Mottle when an element is removed.)
  646. _store = function (obj, event, fn) {
  647. var g = guid++;
  648. obj.__ta = obj.__ta || {};
  649. obj.__ta[event] = obj.__ta[event] || {};
  650. // store each handler with a unique guid.
  651. obj.__ta[event][g] = fn;
  652. // set the guid on the handler.
  653. fn.__tauid = g;
  654. return g;
  655. },
  656. _unstore = function (obj, event, fn) {
  657. obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid];
  658. // a handler might have attached extra functions, so we unbind those too.
  659. if (fn.__taExtra) {
  660. for (var i = 0; i < fn.__taExtra.length; i++) {
  661. _unbind(obj, fn.__taExtra[i][0], fn.__taExtra[i][1]);
  662. }
  663. fn.__taExtra.length = 0;
  664. }
  665. // a handler might have attached an unstore callback
  666. fn.__taUnstore && fn.__taUnstore();
  667. },
  668. _curryChildFilter = function (children, obj, fn, evt) {
  669. if (children == null) return fn;
  670. else {
  671. var c = children.split(","),
  672. _fn = function (e) {
  673. _fn.__tauid = fn.__tauid;
  674. var t = _t(e), target = t; // t is the target element on which the event occurred. it is the
  675. // element we will wish to pass to any callbacks.
  676. var pathInfo = _pi(e, t, obj, children != null)
  677. if (pathInfo.end != -1) {
  678. for (var p = 0; p < pathInfo.end; p++) {
  679. target = pathInfo.path[p];
  680. for (var i = 0; i < c.length; i++) {
  681. if (matchesSelector(target, c[i], obj)) {
  682. fn.apply(target, arguments);
  683. }
  684. }
  685. }
  686. }
  687. };
  688. registerExtraFunction(fn, evt, _fn);
  689. return _fn;
  690. }
  691. },
  692. //
  693. // registers an 'extra' function on some event listener function we were given - a function that we
  694. // created and bound to the element as part of our housekeeping, and which we want to unbind and remove
  695. // whenever the given function is unbound.
  696. registerExtraFunction = function (fn, evt, newFn) {
  697. fn.__taExtra = fn.__taExtra || [];
  698. fn.__taExtra.push([evt, newFn]);
  699. },
  700. DefaultHandler = function (obj, evt, fn, children) {
  701. if (isTouchDevice && touchMap[evt]) {
  702. var tfn = _curryChildFilter(children, obj, fn, touchMap[evt]);
  703. _bind(obj, touchMap[evt], tfn , fn);
  704. }
  705. if (evt === "focus" && obj.getAttribute("tabindex") == null) {
  706. obj.setAttribute("tabindex", "1");
  707. }
  708. _bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn);
  709. },
  710. SmartClickHandler = function (obj, evt, fn, children) {
  711. if (obj.__taSmartClicks == null) {
  712. var down = function (e) {
  713. obj.__tad = _pageLocation(e);
  714. },
  715. up = function (e) {
  716. obj.__tau = _pageLocation(e);
  717. },
  718. click = function (e) {
  719. if (obj.__tad && obj.__tau && obj.__tad[0] === obj.__tau[0] && obj.__tad[1] === obj.__tau[1]) {
  720. for (var i = 0; i < obj.__taSmartClicks.length; i++)
  721. obj.__taSmartClicks[i].apply(_t(e), [ e ]);
  722. }
  723. };
  724. DefaultHandler(obj, "mousedown", down, children);
  725. DefaultHandler(obj, "mouseup", up, children);
  726. DefaultHandler(obj, "click", click, children);
  727. obj.__taSmartClicks = [];
  728. }
  729. // store in the list of callbacks
  730. obj.__taSmartClicks.push(fn);
  731. // the unstore function removes this function from the object's listener list for this type.
  732. fn.__taUnstore = function () {
  733. _d(obj.__taSmartClicks, fn);
  734. };
  735. },
  736. _tapProfiles = {
  737. "tap": {touches: 1, taps: 1},
  738. "dbltap": {touches: 1, taps: 2},
  739. "contextmenu": {touches: 2, taps: 1}
  740. },
  741. TapHandler = function (clickThreshold, dblClickThreshold) {
  742. return function (obj, evt, fn, children) {
  743. // if event is contextmenu, for devices which are mouse only, we want to
  744. // use the default bind.
  745. if (evt == "contextmenu" && isMouseDevice)
  746. DefaultHandler(obj, evt, fn, children);
  747. else {
  748. // the issue here is that this down handler gets registered only for the
  749. // child nodes in the first registration. in fact it should be registered with
  750. // no child selector and then on down we should cycle through the registered
  751. // functions to see if one of them matches. on mouseup we should execute ALL of
  752. // the functions whose children are either null or match the element.
  753. if (obj.__taTapHandler == null) {
  754. var tt = obj.__taTapHandler = {
  755. tap: [],
  756. dbltap: [],
  757. contextmenu: [],
  758. down: false,
  759. taps: 0,
  760. downSelectors: []
  761. };
  762. var down = function (e) {
  763. var target = _t(e), pathInfo = _pi(e, target, obj, children != null), finished = false;
  764. for (var p = 0; p < pathInfo.end; p++) {
  765. if (finished) return;
  766. target = pathInfo.path[p];
  767. for (var i = 0; i < tt.downSelectors.length; i++) {
  768. if (tt.downSelectors[i] == null || matchesSelector(target, tt.downSelectors[i], obj)) {
  769. tt.down = true;
  770. setTimeout(clearSingle, clickThreshold);
  771. setTimeout(clearDouble, dblClickThreshold);
  772. finished = true;
  773. break; // we only need one match on mousedown
  774. }
  775. }
  776. }
  777. },
  778. up = function (e) {
  779. if (tt.down) {
  780. var target = _t(e), currentTarget, pathInfo;
  781. tt.taps++;
  782. var tc = _touchCount(e);
  783. for (var eventId in _tapProfiles) {
  784. if (_tapProfiles.hasOwnProperty(eventId)) {
  785. var p = _tapProfiles[eventId];
  786. if (p.touches === tc && (p.taps === 1 || p.taps === tt.taps)) {
  787. for (var i = 0; i < tt[eventId].length; i++) {
  788. pathInfo = _pi(e, target, obj, tt[eventId][i][1] != null);
  789. for (var pLoop = 0; pLoop < pathInfo.end; pLoop++) {
  790. currentTarget = pathInfo.path[pLoop];
  791. // this is a single event registration handler.
  792. if (tt[eventId][i][1] == null || matchesSelector(currentTarget, tt[eventId][i][1], obj)) {
  793. tt[eventId][i][0].apply(currentTarget, [ e ]);
  794. break;
  795. }
  796. }
  797. }
  798. }
  799. }
  800. }
  801. }
  802. },
  803. clearSingle = function () {
  804. tt.down = false;
  805. },
  806. clearDouble = function () {
  807. tt.taps = 0;
  808. };
  809. DefaultHandler(obj, "mousedown", down);
  810. DefaultHandler(obj, "mouseup", up);
  811. }
  812. // add this child selector (it can be null, that's fine).
  813. obj.__taTapHandler.downSelectors.push(children);
  814. obj.__taTapHandler[evt].push([fn, children]);
  815. // the unstore function removes this function from the object's listener list for this type.
  816. fn.__taUnstore = function () {
  817. _d(obj.__taTapHandler[evt], fn);
  818. };
  819. }
  820. };
  821. },
  822. meeHelper = function (type, evt, obj, target) {
  823. for (var i in obj.__tamee[type]) {
  824. if (obj.__tamee[type].hasOwnProperty(i)) {
  825. obj.__tamee[type][i].apply(target, [ evt ]);
  826. }
  827. }
  828. },
  829. MouseEnterExitHandler = function () {
  830. var activeElements = [];
  831. return function (obj, evt, fn, children) {
  832. if (!obj.__tamee) {
  833. // __tamee holds a flag saying whether the mouse is currently "in" the element, and a list of
  834. // both mouseenter and mouseexit functions.
  835. obj.__tamee = { over: false, mouseenter: [], mouseexit: [] };
  836. // register over and out functions
  837. var over = function (e) {
  838. var t = _t(e);
  839. if ((children == null && (t == obj && !obj.__tamee.over)) || (matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over))) {
  840. meeHelper("mouseenter", e, obj, t);
  841. t.__tamee = t.__tamee || {};
  842. t.__tamee.over = true;
  843. activeElements.push(t);
  844. }
  845. },
  846. out = function (e) {
  847. var t = _t(e);
  848. // is the current target one of the activeElements? and is the
  849. // related target NOT a descendant of it?
  850. for (var i = 0; i < activeElements.length; i++) {
  851. if (t == activeElements[i] && !matchesSelector((e.relatedTarget || e.toElement), "*", t)) {
  852. t.__tamee.over = false;
  853. activeElements.splice(i, 1);
  854. meeHelper("mouseexit", e, obj, t);
  855. }
  856. }
  857. };
  858. _bind(obj, "mouseover", _curryChildFilter(children, obj, over, "mouseover"), over);
  859. _bind(obj, "mouseout", _curryChildFilter(children, obj, out, "mouseout"), out);
  860. }
  861. fn.__taUnstore = function () {
  862. delete obj.__tamee[evt][fn.__tauid];
  863. };
  864. _store(obj, evt, fn);
  865. obj.__tamee[evt][fn.__tauid] = fn;
  866. };
  867. },
  868. isTouchDevice = "ontouchstart" in document.documentElement,
  869. isMouseDevice = "onmousedown" in document.documentElement,
  870. touchMap = { "mousedown": "touchstart", "mouseup": "touchend", "mousemove": "touchmove" },
  871. touchstart = "touchstart", touchend = "touchend", touchmove = "touchmove",
  872. iev = (function () {
  873. var rv = -1;
  874. if (navigator.appName == 'Microsoft Internet Explorer') {
  875. var ua = navigator.userAgent,
  876. re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  877. if (re.exec(ua) != null)
  878. rv = parseFloat(RegExp.$1);
  879. }
  880. return rv;
  881. })(),
  882. isIELT9 = iev > -1 && iev < 9,
  883. _genLoc = function (e, prefix) {
  884. if (e == null) return [ 0, 0 ];
  885. var ts = _touches(e), t = _getTouch(ts, 0);
  886. return [t[prefix + "X"], t[prefix + "Y"]];
  887. },
  888. _pageLocation = function (e) {
  889. if (e == null) return [ 0, 0 ];
  890. if (isIELT9) {
  891. return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
  892. }
  893. else {
  894. return _genLoc(e, "page");
  895. }
  896. },
  897. _screenLocation = function (e) {
  898. return _genLoc(e, "screen");
  899. },
  900. _clientLocation = function (e) {
  901. return _genLoc(e, "client");
  902. },
  903. _getTouch = function (touches, idx) {
  904. return touches.item ? touches.item(idx) : touches[idx];
  905. },
  906. _touches = function (e) {
  907. return e.touches && e.touches.length > 0 ? e.touches :
  908. e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
  909. e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
  910. [ e ];
  911. },
  912. _touchCount = function (e) {
  913. return _touches(e).length;
  914. },
  915. //http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  916. _bind = function (obj, type, fn, originalFn) {
  917. _store(obj, type, fn);
  918. originalFn.__tauid = fn.__tauid;
  919. if (obj.addEventListener)
  920. obj.addEventListener(type, fn, false);
  921. else if (obj.attachEvent) {
  922. var key = type + fn.__tauid;
  923. obj["e" + key] = fn;
  924. // TODO look at replacing with .call(..)
  925. obj[key] = function () {
  926. obj["e" + key] && obj["e" + key](window.event);
  927. };
  928. obj.attachEvent("on" + type, obj[key]);
  929. }
  930. },
  931. _unbind = function (obj, type, fn) {
  932. if (fn == null) return;
  933. _each(obj, function () {
  934. var _el = _gel(this);
  935. _unstore(_el, type, fn);
  936. // it has been bound if there is a tauid. otherwise it was not bound and we can ignore it.
  937. if (fn.__tauid != null) {
  938. if (_el.removeEventListener) {
  939. _el.removeEventListener(type, fn, false);
  940. if (isTouchDevice && touchMap[type]) _el.removeEventListener(touchMap[type], fn, false);
  941. }
  942. else if (this.detachEvent) {
  943. var key = type + fn.__tauid;
  944. _el[key] && _el.detachEvent("on" + type, _el[key]);
  945. _el[key] = null;
  946. _el["e" + key] = null;
  947. }
  948. }
  949. // if a touch event was also registered, deregister now.
  950. if (fn.__taTouchProxy) {
  951. _unbind(obj, fn.__taTouchProxy[1], fn.__taTouchProxy[0]);
  952. }
  953. });
  954. },
  955. _each = function (obj, fn) {
  956. if (obj == null) return;
  957. // if a list (or list-like), use it. if a string, get a list
  958. // by running the string through querySelectorAll. else, assume
  959. // it's an Element.
  960. // obj.top is "unknown" in IE8.
  961. obj = (typeof Window !== "undefined" && (typeof obj.top !== "unknown" && obj == obj.top)) ? [ obj ] :
  962. (typeof obj !== "string") && (obj.tagName == null && obj.length != null) ? obj :
  963. typeof obj === "string" ? document.querySelectorAll(obj)
  964. : [ obj ];
  965. for (var i = 0; i < obj.length; i++)
  966. fn.apply(obj[i]);
  967. };
  968. /**
  969. * Mottle offers support for abstracting out the differences
  970. * between touch and mouse devices, plus "smart click" functionality
  971. * (don't fire click if the mouse has moved between mousedown and mouseup),
  972. * and synthesized click/tap events.
  973. * @class Mottle
  974. * @constructor
  975. * @param {Object} params Constructor params
  976. * @param {Number} [params.clickThreshold=250] Threshold, in milliseconds beyond which a touchstart followed by a touchend is not considered to be a click.
  977. * @param {Number} [params.dblClickThreshold=450] Threshold, in milliseconds beyond which two successive tap events are not considered to be a click.
  978. * @param {Boolean} [params.smartClicks=false] If true, won't fire click events if the mouse has moved between mousedown and mouseup. Note that this functionality
  979. * requires that Mottle consume the mousedown event, and so may not be viable in all use cases.
  980. */
  981. root.Mottle = function (params) {
  982. params = params || {};
  983. var clickThreshold = params.clickThreshold || 250,
  984. dblClickThreshold = params.dblClickThreshold || 450,
  985. mouseEnterExitHandler = new MouseEnterExitHandler(),
  986. tapHandler = new TapHandler(clickThreshold, dblClickThreshold),
  987. _smartClicks = params.smartClicks,
  988. _doBind = function (obj, evt, fn, children) {
  989. if (fn == null) return;
  990. _each(obj, function () {
  991. var _el = _gel(this);
  992. if (_smartClicks && evt === "click")
  993. SmartClickHandler(_el, evt, fn, children);
  994. else if (evt === "tap" || evt === "dbltap" || evt === "contextmenu") {
  995. tapHandler(_el, evt, fn, children);
  996. }
  997. else if (evt === "mouseenter" || evt == "mouseexit")
  998. mouseEnterExitHandler(_el, evt, fn, children);
  999. else
  1000. DefaultHandler(_el, evt, fn, children);
  1001. });
  1002. };
  1003. /**
  1004. * Removes an element from the DOM, and deregisters all event handlers for it. You should use this
  1005. * to ensure you don't leak memory.
  1006. * @method remove
  1007. * @param {String|Element} el Element, or id of the element, to remove.
  1008. * @return {Mottle} The current Mottle instance; you can chain this method.
  1009. */
  1010. this.remove = function (el) {
  1011. _each(el, function () {
  1012. var _el = _gel(this);
  1013. if (_el.__ta) {
  1014. for (var evt in _el.__ta) {
  1015. if (_el.__ta.hasOwnProperty(evt)) {
  1016. for (var h in _el.__ta[evt]) {
  1017. if (_el.__ta[evt].hasOwnProperty(h))
  1018. _unbind(_el, evt, _el.__ta[evt][h]);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. _el.parentNode && _el.parentNode.removeChild(_el);
  1024. });
  1025. return this;
  1026. };
  1027. /**
  1028. * Register an event handler, optionally as a delegate for some set of descendant elements. Note
  1029. * that this method takes either 3 or 4 arguments - if you supply 3 arguments it is assumed you have
  1030. * omitted the `children` parameter, and that the event handler should be bound directly to the given element.
  1031. * @method on
  1032. * @param {Element[]|Element|String} el Either an Element, or a CSS spec for a list of elements, or an array of Elements.
  1033. * @param {String} [children] Comma-delimited list of selectors identifying allowed children.
  1034. * @param {String} event Event ID.
  1035. * @param {Function} fn Event handler function.
  1036. * @return {Mottle} The current Mottle instance; you can chain this method.
  1037. */
  1038. this.on = function (el, event, children, fn) {
  1039. var _el = arguments[0],
  1040. _c = arguments.length == 4 ? arguments[2] : null,
  1041. _e = arguments[1],
  1042. _f = arguments[arguments.length - 1];
  1043. _doBind(_el, _e, _f, _c);
  1044. return this;
  1045. };
  1046. /**
  1047. * Cancel delegate event handling for the given function. Note that unlike with 'on' you do not supply
  1048. * a list of child selectors here: it removes event delegation from all of the child selectors for which the
  1049. * given function was registered (if any).
  1050. * @method off
  1051. * @param {Element[]|Element|String} el Element - or ID of element - from which to remove event listener.
  1052. * @param {String} event Event ID.
  1053. * @param {Function} fn Event handler function.
  1054. * @return {Mottle} The current Mottle instance; you can chain this method.
  1055. */
  1056. this.off = function (el, event, fn) {
  1057. _unbind(el, event, fn);
  1058. return this;
  1059. };
  1060. /**
  1061. * Triggers some event for a given element.
  1062. * @method trigger
  1063. * @param {Element} el Element for which to trigger the event.
  1064. * @param {String} event Event ID.
  1065. * @param {Event} originalEvent The original event. Should be optional of course, but currently is not, due
  1066. * to the jsPlumb use case that caused this method to be added.
  1067. * @param {Object} [payload] Optional object to set as `payload` on the generated event; useful for message passing.
  1068. * @return {Mottle} The current Mottle instance; you can chain this method.
  1069. */
  1070. this.trigger = function (el, event, originalEvent, payload) {
  1071. // MouseEvent undefined in old IE; that's how we know it's a mouse event. A fine Microsoft paradox.
  1072. var originalIsMouse = isMouseDevice && (typeof MouseEvent === "undefined" || originalEvent == null || originalEvent.constructor === MouseEvent);
  1073. var eventToBind = (isTouchDevice && !isMouseDevice && touchMap[event]) ? touchMap[event] : event,
  1074. bindingAMouseEvent = !(isTouchDevice && !isMouseDevice && touchMap[event]);
  1075. var pl = _pageLocation(originalEvent), sl = _screenLocation(originalEvent), cl = _clientLocation(originalEvent);
  1076. _each(el, function () {
  1077. var _el = _gel(this), evt;
  1078. originalEvent = originalEvent || {
  1079. screenX: sl[0],
  1080. screenY: sl[1],
  1081. clientX: cl[0],
  1082. clientY: cl[1]
  1083. };
  1084. var _decorate = function (_evt) {
  1085. if (payload) _evt.payload = payload;
  1086. };
  1087. var eventGenerators = {
  1088. "TouchEvent": function (evt) {
  1089. var touch = document.createTouch(window, _el, 0, pl[0], pl[1],
  1090. sl[0], sl[1],
  1091. cl[0], cl[1],
  1092. 0, 0, 0, 0);
  1093. // https://gist.github.com/sstephenson/448808
  1094. var touches = document.createTouchList(touch);
  1095. var targetTouches = document.createTouchList(touch);
  1096. var changedTouches = document.createTouchList(touch);
  1097. evt.initTouchEvent(eventToBind, true, true, window, null, sl[0], sl[1],
  1098. cl[0], cl[1], false, false, false, false,
  1099. touches, targetTouches, changedTouches, 1, 0);
  1100. },
  1101. "MouseEvents": function (evt) {
  1102. evt.initMouseEvent(eventToBind, true, true, window, 0,
  1103. sl[0], sl[1],
  1104. cl[0], cl[1],
  1105. false, false, false, false, 1, _el);
  1106. if (Sniff.android) {
  1107. // Android's touch events are not standard.
  1108. var t = document.createTouch(window, _el, 0, pl[0], pl[1],
  1109. sl[0], sl[1],
  1110. cl[0], cl[1],
  1111. 0, 0, 0, 0);
  1112. evt.touches = evt.targetTouches = evt.changedTouches = document.createTouchList(t);
  1113. }
  1114. }
  1115. };
  1116. if (document.createEvent) {
  1117. var ite = !bindingAMouseEvent && !originalIsMouse && (isTouchDevice && touchMap[event] && !Sniff.android),
  1118. evtName = ite ? "TouchEvent" : "MouseEvents";
  1119. evt = document.createEvent(evtName);
  1120. eventGenerators[evtName](evt);
  1121. _decorate(evt);
  1122. _el.dispatchEvent(evt);
  1123. }
  1124. else if (document.createEventObject) {
  1125. evt = document.createEventObject();
  1126. evt.eventType = evt.eventName = eventToBind;
  1127. evt.screenX = sl[0];
  1128. evt.screenY = sl[1];
  1129. evt.clientX = cl[0];
  1130. evt.clientY = cl[1];
  1131. _decorate(evt);
  1132. _el.fireEvent('on' + eventToBind, evt);
  1133. }
  1134. });
  1135. return this;
  1136. }
  1137. };
  1138. /**
  1139. * Static method to assist in 'consuming' an element: uses `stopPropagation` where available, or sets
  1140. * `e.returnValue=false` where it is not.
  1141. * @method Mottle.consume
  1142. * @param {Event} e Event to consume
  1143. * @param {Boolean} [doNotPreventDefault=false] If true, does not call `preventDefault()` on the event.
  1144. */
  1145. root.Mottle.consume = function (e, doNotPreventDefault) {
  1146. if (e.stopPropagation)
  1147. e.stopPropagation();
  1148. else
  1149. e.returnValue = false;
  1150. if (!doNotPreventDefault && e.preventDefault)
  1151. e.preventDefault();
  1152. };
  1153. /**
  1154. * Gets the page location corresponding to the given event. For touch events this means get the page location of the first touch.
  1155. * @method Mottle.pageLocation
  1156. * @param {Event} e Event to get page location for.
  1157. * @return {Number[]} [left, top] for the given event.
  1158. */
  1159. root.Mottle.pageLocation = _pageLocation;
  1160. /**
  1161. * Forces touch events to be turned "on". Useful for testing: even if you don't have a touch device, you can still
  1162. * trigger a touch event when this is switched on and it will be captured and acted on.
  1163. * @method setForceTouchEvents
  1164. * @param {Boolean} value If true, force touch events to be on.
  1165. */
  1166. root.Mottle.setForceTouchEvents = function (value) {
  1167. isTouchDevice = value;
  1168. };
  1169. /**
  1170. * Forces mouse events to be turned "on". Useful for testing: even if you don't have a mouse, you can still
  1171. * trigger a mouse event when this is switched on and it will be captured and acted on.
  1172. * @method setForceMouseEvents
  1173. * @param {Boolean} value If true, force mouse events to be on.
  1174. */
  1175. root.Mottle.setForceMouseEvents = function (value) {
  1176. isMouseDevice = value;
  1177. };
  1178. root.Mottle.version = "0.8.0";
  1179. if (typeof exports !== "undefined") {
  1180. exports.Mottle = root.Mottle;
  1181. }
  1182. }).call(typeof window === "undefined" ? this : window);
  1183. /**
  1184. drag/drop functionality for use with jsPlumb but with
  1185. no knowledge of jsPlumb. supports multiple scopes (separated by whitespace), dragging
  1186. multiple elements, constrain to parent, drop filters, drag start filters, custom
  1187. css classes.
  1188. a lot of the functionality of this script is expected to be plugged in:
  1189. addClass
  1190. removeClass
  1191. addEvent
  1192. removeEvent
  1193. getPosition
  1194. setPosition
  1195. getSize
  1196. indexOf
  1197. intersects
  1198. the name came from here:
  1199. http://mrsharpoblunto.github.io/foswig.js/
  1200. copyright 2016 jsPlumb
  1201. */
  1202. ;(function() {
  1203. "use strict";
  1204. var root = this;
  1205. var _suggest = function(list, item, head) {
  1206. if (list.indexOf(item) === -1) {
  1207. head ? list.unshift(item) : list.push(item);
  1208. return true;
  1209. }
  1210. return false;
  1211. };
  1212. var _vanquish = function(list, item) {
  1213. var idx = list.indexOf(item);
  1214. if (idx !== -1) list.splice(idx, 1);
  1215. };
  1216. var _difference = function(l1, l2) {
  1217. var d = [];
  1218. for (var i = 0; i < l1.length; i++) {
  1219. if (l2.indexOf(l1[i]) === -1)
  1220. d.push(l1[i]);
  1221. }
  1222. return d;
  1223. };
  1224. var _isString = function(f) {
  1225. return f == null ? false : (typeof f === "string" || f.constructor === String);
  1226. };
  1227. var getOffsetRect = function (elem) {
  1228. // (1)
  1229. var box = elem.getBoundingClientRect(),
  1230. body = document.body,
  1231. docElem = document.documentElement,
  1232. // (2)
  1233. scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
  1234. scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
  1235. // (3)
  1236. clientTop = docElem.clientTop || body.clientTop || 0,
  1237. clientLeft = docElem.clientLeft || body.clientLeft || 0,
  1238. // (4)
  1239. top = box.top + scrollTop - clientTop,
  1240. left = box.left + scrollLeft - clientLeft;
  1241. return { top: Math.round(top), left: Math.round(left) };
  1242. };
  1243. var matchesSelector = function(el, selector, ctx) {
  1244. ctx = ctx || el.parentNode;
  1245. var possibles = ctx.querySelectorAll(selector);
  1246. for (var i = 0; i < possibles.length; i++) {
  1247. if (possibles[i] === el)
  1248. return true;
  1249. }
  1250. return false;
  1251. };
  1252. var iev = (function() {
  1253. var rv = -1;
  1254. if (navigator.appName === 'Microsoft Internet Explorer') {
  1255. var ua = navigator.userAgent,
  1256. re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  1257. if (re.exec(ua) != null)
  1258. rv = parseFloat(RegExp.$1);
  1259. }
  1260. return rv;
  1261. })(),
  1262. DEFAULT_GRID_X = 10,
  1263. DEFAULT_GRID_Y = 10,
  1264. isIELT9 = iev > -1 && iev < 9,
  1265. isIE9 = iev === 9,
  1266. _pl = function(e) {
  1267. if (isIELT9) {
  1268. return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
  1269. }
  1270. else {
  1271. var ts = _touches(e), t = _getTouch(ts, 0);
  1272. // for IE9 pageX might be null if the event was synthesized. We try for pageX/pageY first,
  1273. // falling back to clientX/clientY if necessary. In every other browser we want to use pageX/pageY.
  1274. return isIE9 ? [t.pageX || t.clientX, t.pageY || t.clientY] : [t.pageX, t.pageY];
  1275. }
  1276. },
  1277. _getTouch = function(touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; },
  1278. _touches = function(e) {
  1279. return e.touches && e.touches.length > 0 ? e.touches :
  1280. e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
  1281. e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
  1282. [ e ];
  1283. },
  1284. _classes = {
  1285. draggable:"katavorio-draggable", // draggable elements
  1286. droppable:"katavorio-droppable", // droppable elements
  1287. drag : "katavorio-drag", // elements currently being dragged
  1288. selected:"katavorio-drag-selected", // elements in current drag selection
  1289. active : "katavorio-drag-active", // droppables that are targets of a currently dragged element
  1290. hover : "katavorio-drag-hover", // droppables over which a matching drag element is hovering
  1291. noSelect : "katavorio-drag-no-select", // added to the body to provide a hook to suppress text selection
  1292. ghostProxy:"katavorio-ghost-proxy", // added to a ghost proxy element in use when a drag has exited the bounds of its parent.
  1293. clonedDrag:"katavorio-clone-drag" // added to a node that is a clone of an element created at the start of a drag
  1294. },
  1295. _defaultScope = "katavorio-drag-scope",
  1296. _events = [ "stop", "start", "drag", "drop", "over", "out", "beforeStart" ],
  1297. _devNull = function() {},
  1298. _true = function() { return true; },
  1299. _foreach = function(l, fn, from) {
  1300. for (var i = 0; i < l.length; i++) {
  1301. if (l[i] != from)
  1302. fn(l[i]);
  1303. }
  1304. },
  1305. _setDroppablesActive = function(dd, val, andHover, drag) {
  1306. _foreach(dd, function(e) {
  1307. e.setActive(val);
  1308. if (val) e.updatePosition();
  1309. if (andHover) e.setHover(drag, val);
  1310. });
  1311. },
  1312. _each = function(obj, fn) {
  1313. if (obj == null) return;
  1314. obj = !_isString(obj) && (obj.tagName == null && obj.length != null) ? obj : [ obj ];
  1315. for (var i = 0; i < obj.length; i++)
  1316. fn.apply(obj[i], [ obj[i] ]);
  1317. },
  1318. _consume = function(e) {
  1319. if (e.stopPropagation) {
  1320. e.stopPropagation();
  1321. e.preventDefault();
  1322. }
  1323. else {
  1324. e.returnValue = false;
  1325. }
  1326. },
  1327. _defaultInputFilterSelector = "input,textarea,select,button,option",
  1328. //
  1329. // filters out events on all input elements, like textarea, checkbox, input, select.
  1330. _inputFilter = function(e, el, _katavorio) {
  1331. var t = e.srcElement || e.target;
  1332. return !matchesSelector(t, _katavorio.getInputFilterSelector(), el);
  1333. };
  1334. var Super = function(el, params, css, scope) {
  1335. this.params = params || {};
  1336. this.el = el;
  1337. this.params.addClass(this.el, this._class);
  1338. this.uuid = _uuid();
  1339. var enabled = true;
  1340. this.setEnabled = function(e) { enabled = e; };
  1341. this.isEnabled = function() { return enabled; };
  1342. this.toggleEnabled = function() { enabled = !enabled; };
  1343. this.setScope = function(scopes) {
  1344. this.scopes = scopes ? scopes.split(/\s+/) : [ scope ];
  1345. };
  1346. this.addScope = function(scopes) {
  1347. var m = {};
  1348. _each(this.scopes, function(s) { m[s] = true;});
  1349. _each(scopes ? scopes.split(/\s+/) : [], function(s) { m[s] = true;});
  1350. this.scopes = [];
  1351. for (var i in m) this.scopes.push(i);
  1352. };
  1353. this.removeScope = function(scopes) {
  1354. var m = {};
  1355. _each(this.scopes, function(s) { m[s] = true;});
  1356. _each(scopes ? scopes.split(/\s+/) : [], function(s) { delete m[s];});
  1357. this.scopes = [];
  1358. for (var i in m) this.scopes.push(i);
  1359. };
  1360. this.toggleScope = function(scopes) {
  1361. var m = {};
  1362. _each(this.scopes, function(s) { m[s] = true;});
  1363. _each(scopes ? scopes.split(/\s+/) : [], function(s) {
  1364. if (m[s]) delete m[s];
  1365. else m[s] = true;
  1366. });
  1367. this.scopes = [];
  1368. for (var i in m) this.scopes.push(i);
  1369. };
  1370. this.setScope(params.scope);
  1371. this.k = params.katavorio;
  1372. return params.katavorio;
  1373. };
  1374. var TRUE = function() { return true; };
  1375. var FALSE = function() { return false; };
  1376. var Drag = function(el, params, css, scope) {
  1377. this._class = css.draggable;
  1378. var k = Super.apply(this, arguments);
  1379. this.rightButtonCanDrag = this.params.rightButtonCanDrag;
  1380. var downAt = [0,0], posAtDown = null, pagePosAtDown = null, pageDelta = [0,0], moving = false,
  1381. consumeStartEvent = this.params.consumeStartEvent !== false,
  1382. dragEl = this.el,
  1383. clone = this.params.clone,
  1384. scroll = this.params.scroll,
  1385. _multipleDrop = params.multipleDrop !== false,
  1386. isConstrained = false,
  1387. useGhostProxy = params.ghostProxy === true ? TRUE : params.ghostProxy && typeof params.ghostProxy === "function" ? params.ghostProxy : FALSE,
  1388. ghostProxy = function(el) { return el.cloneNode(true); };
  1389. var snapThreshold = params.snapThreshold,
  1390. _snap = function(pos, gridX, gridY, thresholdX, thresholdY) {
  1391. var _dx = Math.floor(pos[0] / gridX),
  1392. _dxl = gridX * _dx,
  1393. _dxt = _dxl + gridX,
  1394. _x = Math.abs(pos[0] - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos[0]) <= thresholdX ? _dxt : pos[0];
  1395. var _dy = Math.floor(pos[1] / gridY),
  1396. _dyl = gridY * _dy,
  1397. _dyt = _dyl + gridY,
  1398. _y = Math.abs(pos[1] - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos[1]) <= thresholdY ? _dyt : pos[1];
  1399. return [ _x, _y];
  1400. };
  1401. this.posses = [];
  1402. this.posseRoles = {};
  1403. this.toGrid = function(pos) {
  1404. if (this.params.grid == null) {
  1405. return pos;
  1406. }
  1407. else {
  1408. var tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_X / 2,
  1409. ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_Y / 2;
  1410. return _snap(pos, this.params.grid[0], this.params.grid[1], tx, ty);
  1411. }
  1412. };
  1413. this.snap = function(x, y) {
  1414. if (dragEl == null) return;
  1415. x = x || (this.params.grid ? this.params.grid[0] : DEFAULT_GRID_X);
  1416. y = y || (this.params.grid ? this.params.grid[1] : DEFAULT_GRID_Y);
  1417. var p = this.params.getPosition(dragEl),
  1418. tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold,
  1419. ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold;
  1420. this.params.setPosition(dragEl, _snap(p, x, y, tx, ty));
  1421. };
  1422. this.setUseGhostProxy = function(val) {
  1423. useGhostProxy = val ? TRUE : FALSE;
  1424. };
  1425. var constrain;
  1426. var negativeFilter = function(pos) {
  1427. return (params.allowNegative === false) ? [ Math.max (0, pos[0]), Math.max(0, pos[1]) ] : pos;
  1428. };
  1429. var _setConstrain = function(value) {
  1430. constrain = typeof value === "function" ? value : value ? function(pos) {
  1431. return negativeFilter([
  1432. Math.max(0, Math.min(constrainRect.w - this.size[0], pos[0])),
  1433. Math.max(0, Math.min(constrainRect.h - this.size[1], pos[1]))
  1434. ]);
  1435. }.bind(this) : function(pos) { return negativeFilter(pos); };
  1436. }.bind(this);
  1437. _setConstrain(typeof this.params.constrain === "function" ? this.params.constrain : (this.params.constrain || this.params.containment));
  1438. /**
  1439. * Sets whether or not the Drag is constrained. A value of 'true' means constrain to parent bounds; a function
  1440. * will be executed and returns true if the position is allowed.
  1441. * @param value
  1442. */
  1443. this.setConstrain = function(value) {
  1444. _setConstrain(value);
  1445. };
  1446. var revertFunction;
  1447. /**
  1448. * Sets a function to call on drag stop, which, if it returns true, indicates that the given element should
  1449. * revert to its position before the previous drag.
  1450. * @param fn
  1451. */
  1452. this.setRevert = function(fn) {
  1453. revertFunction = fn;
  1454. };
  1455. var _assignId = function(obj) {
  1456. if (typeof obj === "function") {
  1457. obj._katavorioId = _uuid();
  1458. return obj._katavorioId;
  1459. } else {
  1460. return obj;
  1461. }
  1462. },
  1463. // a map of { spec -> [ fn, exclusion ] } entries.
  1464. _filters = {},
  1465. _testFilter = function(e) {
  1466. for (var key in _filters) {
  1467. var f = _filters[key];
  1468. var rv = f[0](e);
  1469. if (f[1]) rv = !rv;
  1470. if (!rv) return false;
  1471. }
  1472. return true;
  1473. },
  1474. _setFilter = this.setFilter = function(f, _exclude) {
  1475. if (f) {
  1476. var key = _assignId(f);
  1477. _filters[key] = [
  1478. function(e) {
  1479. var t = e.srcElement || e.target, m;
  1480. if (_isString(f)) {
  1481. m = matchesSelector(t, f, el);
  1482. }
  1483. else if (typeof f === "function") {
  1484. m = f(e, el);
  1485. }
  1486. return m;
  1487. },
  1488. _exclude !== false
  1489. ];
  1490. }
  1491. },
  1492. _addFilter = this.addFilter = _setFilter,
  1493. _removeFilter = this.removeFilter = function(f) {
  1494. var key = typeof f === "function" ? f._katavorioId : f;
  1495. delete _filters[key];
  1496. };
  1497. this.clearAllFilters = function() {
  1498. _filters = {};
  1499. };
  1500. this.canDrag = this.params.canDrag || _true;
  1501. var constrainRect,
  1502. matchingDroppables = [], intersectingDroppables = [];
  1503. this.downListener = function(e) {
  1504. var isNotRightClick = this.rightButtonCanDrag || (e.which !== 3 && e.button !== 2);
  1505. if (isNotRightClick && this.isEnabled() && this.canDrag()) {
  1506. var _f = _testFilter(e) && _inputFilter(e, this.el, this.k);
  1507. if (_f) {
  1508. if (!clone)
  1509. dragEl = this.el;
  1510. else {
  1511. dragEl = this.el.cloneNode(true);
  1512. dragEl.setAttribute("id", null);
  1513. dragEl.style.position = "absolute";
  1514. // the clone node is added to the body; getOffsetRect gives us a value
  1515. // relative to the body.
  1516. var b = getOffsetRect(this.el);
  1517. dragEl.style.left = b.left + "px";
  1518. dragEl.style.top = b.top + "px";
  1519. this.params.addClass(dragEl, _classes.clonedDrag);
  1520. document.body.appendChild(dragEl);
  1521. }
  1522. consumeStartEvent && _consume(e);
  1523. downAt = _pl(e);
  1524. //
  1525. this.params.bind(document, "mousemove", this.moveListener);
  1526. this.params.bind(document, "mouseup", this.upListener);
  1527. k.markSelection(this);
  1528. k.markPosses(this);
  1529. this.params.addClass(document.body, css.noSelect);
  1530. _dispatch("beforeStart", {el:this.el, pos:posAtDown, e:e, drag:this});
  1531. }
  1532. else if (this.params.consumeFilteredEvents) {
  1533. _consume(e);
  1534. }
  1535. }
  1536. }.bind(this);
  1537. this.moveListener = function(e) {
  1538. if (downAt) {
  1539. if (!moving) {
  1540. var _continue = _dispatch("start", {el:this.el, pos:posAtDown, e:e, drag:this});
  1541. if (_continue !== false) {
  1542. if (!downAt) {
  1543. return;
  1544. }
  1545. this.mark(true);
  1546. moving = true;
  1547. } else {
  1548. this.abort();
  1549. }
  1550. }
  1551. // it is possible that the start event caused the drag to be aborted. So we check
  1552. // again that we are currently dragging.
  1553. if (downAt) {
  1554. intersectingDroppables.length = 0;
  1555. var pos = _pl(e), dx = pos[0] - downAt[0], dy = pos[1] - downAt[1],
  1556. z = this.params.ignoreZoom ? 1 : k.getZoom();
  1557. dx /= z;
  1558. dy /= z;
  1559. this.moveBy(dx, dy, e);
  1560. k.updateSelection(dx, dy, this);
  1561. k.updatePosses(dx, dy, this);
  1562. }
  1563. }
  1564. }.bind(this);
  1565. this.upListener = function(e) {
  1566. if (downAt) {
  1567. downAt = null;
  1568. this.params.unbind(document, "mousemove", this.moveListener);
  1569. this.params.unbind(document, "mouseup", this.upListener);
  1570. this.params.removeClass(document.body, css.noSelect);
  1571. this.unmark(e);
  1572. k.unmarkSelection(this, e);
  1573. k.unmarkPosses(this, e);
  1574. this.stop(e);
  1575. k.notifySelectionDragStop(this, e);
  1576. k.notifyPosseDragStop(this, e);
  1577. moving = false;
  1578. if (clone) {
  1579. dragEl && dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
  1580. dragEl = null;
  1581. }
  1582. intersectingDroppables.length = 0;
  1583. if (revertFunction && revertFunction(this.el, this.params.getPosition(this.el)) === true) {
  1584. this.params.setPosition(this.el, posAtDown);
  1585. _dispatch("revert", this.el);
  1586. }
  1587. }
  1588. }.bind(this);
  1589. this.getFilters = function() { return _filters; };
  1590. this.abort = function() {
  1591. if (downAt != null)
  1592. this.upListener();
  1593. };
  1594. this.getDragElement = function() {
  1595. return dragEl || this.el;
  1596. };
  1597. var listeners = {"start":[], "drag":[], "stop":[], "over":[], "out":[], "beforeStart":[], "revert":[] };
  1598. if (params.events.start) listeners.start.push(params.events.start);
  1599. if (params.events.beforeStart) listeners.beforeStart.push(params.events.beforeStart);
  1600. if (params.events.stop) listeners.stop.push(params.events.stop);
  1601. if (params.events.drag) listeners.drag.push(params.events.drag);
  1602. if (params.events.revert) listeners.revert.push(params.events.revert);
  1603. this.on = function(evt, fn) {
  1604. if (listeners[evt]) listeners[evt].push(fn);
  1605. };
  1606. this.off = function(evt, fn) {
  1607. if (listeners[evt]) {
  1608. var l = [];
  1609. for (var i = 0; i < listeners[evt].length; i++) {
  1610. if (listeners[evt][i] !== fn) l.push(listeners[evt][i]);
  1611. }
  1612. listeners[evt] = l;
  1613. }
  1614. };
  1615. var _dispatch = function(evt, value) {
  1616. var result = null;
  1617. if (listeners[evt]) {
  1618. for (var i = 0; i < listeners[evt].length; i++) {
  1619. try {
  1620. var v = listeners[evt][i](value);
  1621. if (v != null) {
  1622. result = v;
  1623. }
  1624. }
  1625. catch (e) { }
  1626. }
  1627. }
  1628. return result;
  1629. };
  1630. this.notifyStart = function(e) {
  1631. _dispatch("start", {el:this.el, pos:this.params.getPosition(dragEl), e:e, drag:this});
  1632. };
  1633. this.stop = function(e, force) {
  1634. if (force || moving) {
  1635. var positions = [],
  1636. sel = k.getSelection(),
  1637. dPos = this.params.getPosition(dragEl);
  1638. if (sel.length > 1) {
  1639. for (var i = 0; i < sel.length; i++) {
  1640. var p = this.params.getPosition(sel[i].el);
  1641. positions.push([ sel[i].el, { left: p[0], top: p[1] }, sel[i] ]);
  1642. }
  1643. }
  1644. else {
  1645. positions.push([ dragEl, {left:dPos[0], top:dPos[1]}, this ]);
  1646. }
  1647. _dispatch("stop", {
  1648. el: dragEl,
  1649. pos: ghostProxyOffsets || dPos,
  1650. finalPos:dPos,
  1651. e: e,
  1652. drag: this,
  1653. selection:positions
  1654. });
  1655. }
  1656. };
  1657. this.mark = function(andNotify) {
  1658. posAtDown = this.params.getPosition(dragEl);
  1659. pagePosAtDown = this.params.getPosition(dragEl, true);
  1660. pageDelta = [pagePosAtDown[0] - posAtDown[0], pagePosAtDown[1] - posAtDown[1]];
  1661. this.size = this.params.getSize(dragEl);
  1662. matchingDroppables = k.getMatchingDroppables(this);
  1663. _setDroppablesActive(matchingDroppables, true, false, this);
  1664. this.params.addClass(dragEl, this.params.dragClass || css.drag);
  1665. var cs;
  1666. if (this.params.getConstrainingRectangle) {
  1667. cs = this.params.getConstrainingRectangle(dragEl)
  1668. } else {
  1669. cs = this.params.getSize(dragEl.parentNode);
  1670. }
  1671. constrainRect = {w: cs[0], h: cs[1]};
  1672. if (andNotify) {
  1673. k.notifySelectionDragStart(this);
  1674. }
  1675. };
  1676. var ghostProxyOffsets;
  1677. this.unmark = function(e, doNotCheckDroppables) {
  1678. _setDroppablesActive(matchingDroppables, false, true, this);
  1679. if (isConstrained && useGhostProxy(this.el)) {
  1680. ghostProxyOffsets = [dragEl.offsetLeft, dragEl.offsetTop];
  1681. this.el.parentNode.removeChild(dragEl);
  1682. dragEl = this.el;
  1683. }
  1684. else {
  1685. ghostProxyOffsets = null;
  1686. }
  1687. this.params.removeClass(dragEl, this.params.dragClass || css.drag);
  1688. matchingDroppables.length = 0;
  1689. isConstrained = false;
  1690. if (!doNotCheckDroppables) {
  1691. if (intersectingDroppables.length > 0 && ghostProxyOffsets) {
  1692. params.setPosition(this.el, ghostProxyOffsets);
  1693. }
  1694. intersectingDroppables.sort(_rankSort);
  1695. for (var i = 0; i < intersectingDroppables.length; i++) {
  1696. var retVal = intersectingDroppables[i].drop(this, e);
  1697. if (retVal === true) break;
  1698. }
  1699. }
  1700. };
  1701. this.moveBy = function(dx, dy, e) {
  1702. intersectingDroppables.length = 0;
  1703. var desiredLoc = this.toGrid([posAtDown[0] + dx, posAtDown[1] + dy]),
  1704. cPos = constrain(desiredLoc, dragEl);
  1705. if (useGhostProxy(this.el)) {
  1706. if (desiredLoc[0] !== cPos[0] || desiredLoc[1] !== cPos[1]) {
  1707. if (!isConstrained) {
  1708. var gp = ghostProxy(this.el);
  1709. params.addClass(gp, _classes.ghostProxy);
  1710. this.el.parentNode.appendChild(gp);
  1711. dragEl = gp;
  1712. isConstrained = true;
  1713. }
  1714. cPos = desiredLoc;
  1715. }
  1716. else {
  1717. if (isConstrained) {
  1718. this.el.parentNode.removeChild(dragEl);
  1719. dragEl = this.el;
  1720. isConstrained = false;
  1721. }
  1722. }
  1723. }
  1724. var rect = { x:cPos[0], y:cPos[1], w:this.size[0], h:this.size[1]},
  1725. pageRect = { x:rect.x + pageDelta[0], y:rect.y + pageDelta[1], w:rect.w, h:rect.h},
  1726. focusDropElement = null;
  1727. this.params.setPosition(dragEl, cPos);
  1728. for (var i = 0; i < matchingDroppables.length; i++) {
  1729. var r2 = { x:matchingDroppables[i].pagePosition[0], y:matchingDroppables[i].pagePosition[1], w:matchingDroppables[i].size[0], h:matchingDroppables[i].size[1]};
  1730. if (this.params.intersects(pageRect, r2) && (_multipleDrop || focusDropElement == null || focusDropElement === matchingDroppables[i].el) && matchingDroppables[i].canDrop(this)) {
  1731. if (!focusDropElement) focusDropElement = matchingDroppables[i].el;
  1732. intersectingDroppables.push(matchingDroppables[i]);
  1733. matchingDroppables[i].setHover(this, true, e);
  1734. }
  1735. else if (matchingDroppables[i].isHover()) {
  1736. matchingDroppables[i].setHover(this, false, e);
  1737. }
  1738. }
  1739. _dispatch("drag", {el:this.el, pos:cPos, e:e, drag:this});
  1740. /* test to see if the parent needs to be scrolled (future)
  1741. if (scroll) {
  1742. var pnsl = dragEl.parentNode.scrollLeft, pnst = dragEl.parentNode.scrollTop;
  1743. console.log("scroll!", pnsl, pnst);
  1744. }*/
  1745. };
  1746. this.destroy = function() {
  1747. this.params.unbind(this.el, "mousedown", this.downListener);
  1748. this.params.unbind(document, "mousemove", this.moveListener);
  1749. this.params.unbind(document, "mouseup", this.upListener);
  1750. this.downListener = null;
  1751. this.upListener = null;
  1752. this.moveListener = null;
  1753. };
  1754. // init:register mousedown, and perhaps set a filter
  1755. this.params.bind(this.el, "mousedown", this.downListener);
  1756. // if handle provded, use that. otherwise, try to set a filter.
  1757. // note that a `handle` selector always results in filterExclude being set to false, ie.
  1758. // the selector defines the handle element(s).
  1759. if (this.params.handle)
  1760. _setFilter(this.params.handle, false);
  1761. else
  1762. _setFilter(this.params.filter, this.params.filterExclude);
  1763. };
  1764. var Drop = function(el, params, css, scope) {
  1765. this._class = css.droppable;
  1766. this.params = params || {};
  1767. this.rank = params.rank || 0;
  1768. this._activeClass = this.params.activeClass || css.active;
  1769. this._hoverClass = this.params.hoverClass || css.hover;
  1770. Super.apply(this, arguments);
  1771. var hover = false;
  1772. this.allowLoopback = this.params.allowLoopback !== false;
  1773. this.setActive = function(val) {
  1774. this.params[val ? "addClass" : "removeClass"](this.el, this._activeClass);
  1775. };
  1776. this.updatePosition = function() {
  1777. this.position = this.params.getPosition(this.el);
  1778. this.pagePosition = this.params.getPosition(this.el, true);
  1779. this.size = this.params.getSize(this.el);
  1780. };
  1781. this.canDrop = this.params.canDrop || function(drag) {
  1782. return true;
  1783. };
  1784. this.isHover = function() { return hover; };
  1785. this.setHover = function(drag, val, e) {
  1786. // if turning off hover but this was not the drag that caused the hover, ignore.
  1787. if (val || this.el._katavorioDragHover == null || this.el._katavorioDragHover === drag.el._katavorio) {
  1788. this.params[val ? "addClass" : "removeClass"](this.el, this._hoverClass);
  1789. //this.el._katavorioDragHover = val ? drag.el._katavorio : null;
  1790. this.el._katavorioDragHover = val ? drag.el._katavorio : null;
  1791. if (hover !== val)
  1792. this.params.events[val ? "over" : "out"]({el:this.el, e:e, drag:drag, drop:this});
  1793. hover = val;
  1794. }
  1795. };
  1796. this.drop = function(drag, event) {
  1797. return this.params.events["drop"]({ drag:drag, e:event, drop:this });
  1798. };
  1799. this.destroy = function() {
  1800. this._class = null;
  1801. this._activeClass = null;
  1802. this._hoverClass = null;
  1803. //this.params = null;
  1804. hover = null;
  1805. //this.el = null;
  1806. };
  1807. };
  1808. var _uuid = function() {
  1809. return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  1810. var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
  1811. return v.toString(16);
  1812. }));
  1813. };
  1814. var _rankSort = function(a,b) {
  1815. return a.rank < b.rank ? 1 : a.rank > b.rank ? -1 : 0;
  1816. };
  1817. var _gel = function(el) {
  1818. if (el == null) return null;
  1819. el = (typeof el === "string" || el.constructor === String) ? document.getElementById(el) : el;
  1820. if (el == null) return null;
  1821. el._katavorio = el._katavorio || _uuid();
  1822. return el;
  1823. };
  1824. root.Katavorio = function(katavorioParams) {
  1825. var _selection = [],
  1826. _selectionMap = {};
  1827. this._dragsByScope = {};
  1828. this._dropsByScope = {};
  1829. var _zoom = 1,
  1830. _reg = function(obj, map) {
  1831. _each(obj, function(_obj) {
  1832. for(var i = 0; i < _obj.scopes.length; i++) {
  1833. map[_obj.scopes[i]] = map[_obj.scopes[i]] || [];
  1834. map[_obj.scopes[i]].push(_obj);
  1835. }
  1836. });
  1837. },
  1838. _unreg = function(obj, map) {
  1839. var c = 0;
  1840. _each(obj, function(_obj) {
  1841. for(var i = 0; i < _obj.scopes.length; i++) {
  1842. if (map[_obj.scopes[i]]) {
  1843. var idx = katavorioParams.indexOf(map[_obj.scopes[i]], _obj);
  1844. if (idx !== -1) {
  1845. map[_obj.scopes[i]].splice(idx, 1);
  1846. c++;
  1847. }
  1848. }
  1849. }
  1850. });
  1851. return c > 0 ;
  1852. },
  1853. _getMatchingDroppables = this.getMatchingDroppables = function(drag) {
  1854. var dd = [], _m = {};
  1855. for (var i = 0; i < drag.scopes.length; i++) {
  1856. var _dd = this._dropsByScope[drag.scopes[i]];
  1857. if (_dd) {
  1858. for (var j = 0; j < _dd.length; j++) {
  1859. if (_dd[j].canDrop(drag) && !_m[_dd[j].uuid] && (_dd[j].allowLoopback || _dd[j].el !== drag.el)) {
  1860. _m[_dd[j].uuid] = true;
  1861. dd.push(_dd[j]);
  1862. }
  1863. }
  1864. }
  1865. }
  1866. dd.sort(_rankSort);
  1867. return dd;
  1868. },
  1869. _prepareParams = function(p) {
  1870. p = p || {};
  1871. var _p = {
  1872. events:{}
  1873. }, i;
  1874. for (i in katavorioParams) _p[i] = katavorioParams[i];
  1875. for (i in p) _p[i] = p[i];
  1876. // events
  1877. for (i = 0; i < _events.length; i++) {
  1878. _p.events[_events[i]] = p[_events[i]] || _devNull;
  1879. }
  1880. _p.katavorio = this;
  1881. return _p;
  1882. }.bind(this),
  1883. _mistletoe = function(existingDrag, params) {
  1884. for (var i = 0; i < _events.length; i++) {
  1885. if (params[_events[i]]) {
  1886. existingDrag.on(_events[i], params[_events[i]]);
  1887. }
  1888. }
  1889. }.bind(this),
  1890. _css = {},
  1891. overrideCss = katavorioParams.css || {},
  1892. _scope = katavorioParams.scope || _defaultScope;
  1893. // prepare map of css classes based on defaults frst, then optional overrides
  1894. for (var i in _classes) _css[i] = _classes[i];
  1895. for (var i in overrideCss) _css[i] = overrideCss[i];
  1896. var inputFilterSelector = katavorioParams.inputFilterSelector || _defaultInputFilterSelector;
  1897. /**
  1898. * Gets the selector identifying which input elements to filter from drag events.
  1899. * @method getInputFilterSelector
  1900. * @return {String} Current input filter selector.
  1901. */
  1902. this.getInputFilterSelector = function() { return inputFilterSelector; };
  1903. /**
  1904. * Sets the selector identifying which input elements to filter from drag events.
  1905. * @method setInputFilterSelector
  1906. * @param {String} selector Input filter selector to set.
  1907. * @return {Katavorio} Current instance; method may be chained.
  1908. */
  1909. this.setInputFilterSelector = function(selector) {
  1910. inputFilterSelector = selector;
  1911. return this;
  1912. };
  1913. this.draggable = function(el, params) {
  1914. var o = [];
  1915. _each(el, function(_el) {
  1916. _el = _gel(_el);
  1917. if (_el != null) {
  1918. if (_el._katavorioDrag == null) {
  1919. var p = _prepareParams(params);
  1920. _el._katavorioDrag = new Drag(_el, p, _css, _scope);
  1921. _reg(_el._katavorioDrag, this._dragsByScope);
  1922. o.push(_el._katavorioDrag);
  1923. katavorioParams.addClass(_el, _css.draggable);
  1924. }
  1925. else {
  1926. _mistletoe(_el._katavorioDrag, params);
  1927. }
  1928. }
  1929. }.bind(this));
  1930. return o;
  1931. };
  1932. this.droppable = function(el, params) {
  1933. var o = [];
  1934. _each(el, function(_el) {
  1935. _el = _gel(_el);
  1936. if (_el != null) {
  1937. var drop = new Drop(_el, _prepareParams(params), _css, _scope);
  1938. _el._katavorioDrop = _el._katavorioDrop || [];
  1939. _el._katavorioDrop.push(drop);
  1940. _reg(drop, this._dropsByScope);
  1941. o.push(drop);
  1942. katavorioParams.addClass(_el, _css.droppable);
  1943. }
  1944. }.bind(this));
  1945. return o;
  1946. };
  1947. /**
  1948. * @name Katavorio#select
  1949. * @function
  1950. * @desc Adds an element to the current selection (for multiple node drag)
  1951. * @param {Element|String} DOM element - or id of the element - to add.
  1952. */
  1953. this.select = function(el) {
  1954. _each(el, function() {
  1955. var _el = _gel(this);
  1956. if (_el && _el._katavorioDrag) {
  1957. if (!_selectionMap[_el._katavorio]) {
  1958. _selection.push(_el._katavorioDrag);
  1959. _selectionMap[_el._katavorio] = [ _el, _selection.length - 1 ];
  1960. katavorioParams.addClass(_el, _css.selected);
  1961. }
  1962. }
  1963. });
  1964. return this;
  1965. };
  1966. /**
  1967. * @name Katavorio#deselect
  1968. * @function
  1969. * @desc Removes an element from the current selection (for multiple node drag)
  1970. * @param {Element|String} DOM element - or id of the element - to remove.
  1971. */
  1972. this.deselect = function(el) {
  1973. _each(el, function() {
  1974. var _el = _gel(this);
  1975. if (_el && _el._katavorio) {
  1976. var e = _selectionMap[_el._katavorio];
  1977. if (e) {
  1978. var _s = [];
  1979. for (var i = 0; i < _selection.length; i++)
  1980. if (_selection[i].el !== _el) _s.push(_selection[i]);
  1981. _selection = _s;
  1982. delete _selectionMap[_el._katavorio];
  1983. katavorioParams.removeClass(_el, _css.selected);
  1984. }
  1985. }
  1986. });
  1987. return this;
  1988. };
  1989. this.deselectAll = function() {
  1990. for (var i in _selectionMap) {
  1991. var d = _selectionMap[i];
  1992. katavorioParams.removeClass(d[0], _css.selected);
  1993. }
  1994. _selection.length = 0;
  1995. _selectionMap = {};
  1996. };
  1997. this.markSelection = function(drag) {
  1998. _foreach(_selection, function(e) { e.mark(); }, drag);
  1999. };
  2000. this.markPosses = function(drag) {
  2001. if (drag.posses) {
  2002. _each(drag.posses, function(p) {
  2003. if (drag.posseRoles[p] && _posses[p]) {
  2004. _foreach(_posses[p].members, function (d) {
  2005. d.mark();
  2006. }, drag);
  2007. }
  2008. })
  2009. }
  2010. };
  2011. this.unmarkSelection = function(drag, event) {
  2012. _foreach(_selection, function(e) { e.unmark(event); }, drag);
  2013. };
  2014. this.unmarkPosses = function(drag, event) {
  2015. if (drag.posses) {
  2016. _each(drag.posses, function(p) {
  2017. if (drag.posseRoles[p] && _posses[p]) {
  2018. _foreach(_posses[p].members, function (d) {
  2019. d.unmark(event, true);
  2020. }, drag);
  2021. }
  2022. });
  2023. }
  2024. };
  2025. this.getSelection = function() { return _selection.slice(0); };
  2026. this.updateSelection = function(dx, dy, drag) {
  2027. _foreach(_selection, function(e) { e.moveBy(dx, dy); }, drag);
  2028. };
  2029. var _posseAction = function(fn, drag) {
  2030. if (drag.posses) {
  2031. _each(drag.posses, function(p) {
  2032. if (drag.posseRoles[p] && _posses[p]) {
  2033. _foreach(_posses[p].members, function (e) {
  2034. fn(e);
  2035. }, drag);
  2036. }
  2037. });
  2038. }
  2039. };
  2040. this.updatePosses = function(dx, dy, drag) {
  2041. _posseAction(function(e) { e.moveBy(dx, dy); }, drag);
  2042. };
  2043. this.notifyPosseDragStop = function(drag, evt) {
  2044. _posseAction(function(e) { e.stop(evt, true); }, drag);
  2045. };
  2046. this.notifySelectionDragStop = function(drag, evt) {
  2047. _foreach(_selection, function(e) { e.stop(evt, true); }, drag);
  2048. };
  2049. this.notifySelectionDragStart = function(drag, evt) {
  2050. _foreach(_selection, function(e) { e.notifyStart(evt);}, drag);
  2051. };
  2052. this.setZoom = function(z) { _zoom = z; };
  2053. this.getZoom = function() { return _zoom; };
  2054. // does the work of changing scopes
  2055. var _scopeManip = function(kObj, scopes, map, fn) {
  2056. _each(kObj, function(_kObj) {
  2057. _unreg(_kObj, map); // deregister existing scopes
  2058. _kObj[fn](scopes); // set scopes
  2059. _reg(_kObj, map); // register new ones
  2060. });
  2061. };
  2062. _each([ "set", "add", "remove", "toggle"], function(v) {
  2063. this[v + "Scope"] = function(el, scopes) {
  2064. _scopeManip(el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
  2065. _scopeManip(el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
  2066. }.bind(this);
  2067. this[v + "DragScope"] = function(el, scopes) {
  2068. _scopeManip(el.constructor === Drag ? el : el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
  2069. }.bind(this);
  2070. this[v + "DropScope"] = function(el, scopes) {
  2071. _scopeManip(el.constructor === Drop ? el : el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
  2072. }.bind(this);
  2073. }.bind(this));
  2074. this.snapToGrid = function(x, y) {
  2075. for (var s in this._dragsByScope) {
  2076. _foreach(this._dragsByScope[s], function(d) { d.snap(x, y); });
  2077. }
  2078. };
  2079. this.getDragsForScope = function(s) { return this._dragsByScope[s]; };
  2080. this.getDropsForScope = function(s) { return this._dropsByScope[s]; };
  2081. var _destroy = function(el, type, map) {
  2082. el = _gel(el);
  2083. if (el[type]) {
  2084. // remove from selection, if present.
  2085. var selIdx = _selection.indexOf(el[type]);
  2086. if (selIdx >= 0) {
  2087. _selection.splice(selIdx, 1);
  2088. }
  2089. if (_unreg(el[type], map)) {
  2090. _each(el[type], function(kObj) { kObj.destroy() });
  2091. }
  2092. delete el[type];
  2093. }
  2094. };
  2095. this.elementRemoved = function(el) {
  2096. this.destroyDraggable(el);
  2097. this.destroyDroppable(el);
  2098. };
  2099. this.destroyDraggable = function(el) {
  2100. _destroy(el, "_katavorioDrag", this._dragsByScope);
  2101. };
  2102. this.destroyDroppable = function(el) {
  2103. _destroy(el, "_katavorioDrop", this._dropsByScope);
  2104. };
  2105. this.reset = function() {
  2106. this._dragsByScope = {};
  2107. this._dropsByScope = {};
  2108. _selection = [];
  2109. _selectionMap = {};
  2110. _posses = {};
  2111. };
  2112. // ----- groups
  2113. var _posses = {};
  2114. var _processOneSpec = function(el, _spec, dontAddExisting) {
  2115. var posseId = _isString(_spec) ? _spec : _spec.id;
  2116. var active = _isString(_spec) ? true : _spec.active !== false;
  2117. var posse = _posses[posseId] || (function() {
  2118. var g = {name:posseId, members:[]};
  2119. _posses[posseId] = g;
  2120. return g;
  2121. })();
  2122. _each(el, function(_el) {
  2123. if (_el._katavorioDrag) {
  2124. if (dontAddExisting && _el._katavorioDrag.posseRoles[posse.name] != null) return;
  2125. _suggest(posse.members, _el._katavorioDrag);
  2126. _suggest(_el._katavorioDrag.posses, posse.name);
  2127. _el._katavorioDrag.posseRoles[posse.name] = active;
  2128. }
  2129. });
  2130. return posse;
  2131. };
  2132. /**
  2133. * Add the given element to the posse with the given id, creating the group if it at first does not exist.
  2134. * @method addToPosse
  2135. * @param {Element} el Element to add.
  2136. * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
  2137. * the ID of a Posse to which the element should be added as an active participant, or an Object containing
  2138. * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
  2139. * true.
  2140. * @returns {Posse|Posse[]} The Posse(s) to which the element(s) was/were added.
  2141. */
  2142. this.addToPosse = function(el, spec) {
  2143. var posses = [];
  2144. for (var i = 1; i < arguments.length; i++) {
  2145. posses.push(_processOneSpec(el, arguments[i]));
  2146. }
  2147. return posses.length === 1 ? posses[0] : posses;
  2148. };
  2149. /**
  2150. * Sets the posse(s) for the element with the given id, creating those that do not yet exist, and removing from
  2151. * the element any current Posses that are not specified by this method call. This method will not change the
  2152. * active/passive state if it is given a posse in which the element is already a member.
  2153. * @method setPosse
  2154. * @param {Element} el Element to set posse(s) on.
  2155. * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
  2156. * the ID of a Posse to which the element should be added as an active participant, or an Object containing
  2157. * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
  2158. * true.
  2159. * @returns {Posse|Posse[]} The Posse(s) to which the element(s) now belongs.
  2160. */
  2161. this.setPosse = function(el, spec) {
  2162. var posses = [];
  2163. for (var i = 1; i < arguments.length; i++) {
  2164. posses.push(_processOneSpec(el, arguments[i], true).name);
  2165. }
  2166. _each(el, function(_el) {
  2167. if (_el._katavorioDrag) {
  2168. var diff = _difference(_el._katavorioDrag.posses, posses);
  2169. var p = [];
  2170. Array.prototype.push.apply(p, _el._katavorioDrag.posses);
  2171. for (var i = 0; i < diff.length; i++) {
  2172. this.removeFromPosse(_el, diff[i]);
  2173. }
  2174. }
  2175. }.bind(this));
  2176. return posses.length === 1 ? posses[0] : posses;
  2177. };
  2178. /**
  2179. * Remove the given element from the given posse(s).
  2180. * @method removeFromPosse
  2181. * @param {Element} el Element to remove.
  2182. * @param {String...} posseId Varargs parameter: one value for each posse to remove the element from.
  2183. */
  2184. this.removeFromPosse = function(el, posseId) {
  2185. if (arguments.length < 2) throw new TypeError("No posse id provided for remove operation");
  2186. for(var i = 1; i < arguments.length; i++) {
  2187. posseId = arguments[i];
  2188. _each(el, function (_el) {
  2189. if (_el._katavorioDrag && _el._katavorioDrag.posses) {
  2190. var d = _el._katavorioDrag;
  2191. _each(posseId, function (p) {
  2192. _vanquish(_posses[p].members, d);
  2193. _vanquish(d.posses, p);
  2194. delete d.posseRoles[p];
  2195. });
  2196. }
  2197. });
  2198. }
  2199. };
  2200. /**
  2201. * Remove the given element from all Posses to which it belongs.
  2202. * @method removeFromAllPosses
  2203. * @param {Element|Element[]} el Element to remove from Posses.
  2204. */
  2205. this.removeFromAllPosses = function(el) {
  2206. _each(el, function(_el) {
  2207. if (_el._katavorioDrag && _el._katavorioDrag.posses) {
  2208. var d = _el._katavorioDrag;
  2209. _each(d.posses, function(p) {
  2210. _vanquish(_posses[p].members, d);
  2211. });
  2212. d.posses.length = 0;
  2213. d.posseRoles = {};
  2214. }
  2215. });
  2216. };
  2217. /**
  2218. * Changes the participation state for the element in the Posse with the given ID.
  2219. * @param {Element|Element[]} el Element(s) to change state for.
  2220. * @param {String} posseId ID of the Posse to change element state for.
  2221. * @param {Boolean} state True to make active, false to make passive.
  2222. */
  2223. this.setPosseState = function(el, posseId, state) {
  2224. var posse = _posses[posseId];
  2225. if (posse) {
  2226. _each(el, function(_el) {
  2227. if (_el._katavorioDrag && _el._katavorioDrag.posses) {
  2228. _el._katavorioDrag.posseRoles[posse.name] = state;
  2229. }
  2230. });
  2231. }
  2232. };
  2233. };
  2234. root.Katavorio.version = "0.23.0";
  2235. if (typeof exports !== "undefined") {
  2236. exports.Katavorio = root.Katavorio;
  2237. }
  2238. }).call(typeof window !== 'undefined' ? window : this);
  2239. /*
  2240. * This file contains utility functions that run in both browsers and headless.
  2241. *
  2242. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  2243. *
  2244. * https://jsplumbtoolkit.com
  2245. * https://github.com/jsplumb/jsplumb
  2246. *
  2247. * Dual licensed under the MIT and GPL2 licenses.
  2248. */
  2249. ;
  2250. (function () {
  2251. var _isa = function (a) {
  2252. return Object.prototype.toString.call(a) === "[object Array]";
  2253. },
  2254. _isnum = function (n) {
  2255. return Object.prototype.toString.call(n) === "[object Number]";
  2256. },
  2257. _iss = function (s) {
  2258. return typeof s === "string";
  2259. },
  2260. _isb = function (s) {
  2261. return typeof s === "boolean";
  2262. },
  2263. _isnull = function (s) {
  2264. return s == null;
  2265. },
  2266. _iso = function (o) {
  2267. return o == null ? false : Object.prototype.toString.call(o) === "[object Object]";
  2268. },
  2269. _isd = function (o) {
  2270. return Object.prototype.toString.call(o) === "[object Date]";
  2271. },
  2272. _isf = function (o) {
  2273. return Object.prototype.toString.call(o) === "[object Function]";
  2274. },
  2275. _isNamedFunction = function(o) {
  2276. return _isf(o) && o.name != null && o.name.length > 0;
  2277. },
  2278. _ise = function (o) {
  2279. for (var i in o) {
  2280. if (o.hasOwnProperty(i)) {
  2281. return false;
  2282. }
  2283. }
  2284. return true;
  2285. };
  2286. var root = this;
  2287. root.jsPlumbUtil = {
  2288. isArray: _isa,
  2289. isString: _iss,
  2290. isBoolean: _isb,
  2291. isNull: _isnull,
  2292. isObject: _iso,
  2293. isDate: _isd,
  2294. isFunction: _isf,
  2295. isEmpty: _ise,
  2296. isNumber: _isnum,
  2297. clone: function (a) {
  2298. if (_iss(a)) {
  2299. return "" + a;
  2300. }
  2301. else if (_isb(a)) {
  2302. return !!a;
  2303. }
  2304. else if (_isd(a)) {
  2305. return new Date(a.getTime());
  2306. }
  2307. else if (_isf(a)) {
  2308. return a;
  2309. }
  2310. else if (_isa(a)) {
  2311. var b = [];
  2312. for (var i = 0; i < a.length; i++) {
  2313. b.push(this.clone(a[i]));
  2314. }
  2315. return b;
  2316. }
  2317. else if (_iso(a)) {
  2318. var c = {};
  2319. for (var j in a) {
  2320. c[j] = this.clone(a[j]);
  2321. }
  2322. return c;
  2323. }
  2324. else {
  2325. return a;
  2326. }
  2327. },
  2328. merge: function (a, b, collations) {
  2329. // first change the collations array - if present - into a lookup table, because its faster.
  2330. var cMap = {}, ar, i;
  2331. collations = collations || [];
  2332. for (i = 0; i < collations.length; i++) {
  2333. cMap[collations[i]] = true;
  2334. }
  2335. var c = this.clone(a);
  2336. for (i in b) {
  2337. if (c[i] == null) {
  2338. c[i] = b[i];
  2339. }
  2340. else if (_iss(b[i]) || _isb(b[i])) {
  2341. if (!cMap[i]) {
  2342. c[i] = b[i]; // if we dont want to collate, just copy it in.
  2343. }
  2344. else {
  2345. ar = [];
  2346. // if c's object is also an array we can keep its values.
  2347. ar.push.apply(ar, _isa(c[i]) ? c[i] : [ c[i] ]);
  2348. ar.push.apply(ar, _isa(b[i]) ? b[i] : [ b[i] ]);
  2349. c[i] = ar;
  2350. }
  2351. }
  2352. else {
  2353. if (_isa(b[i])) {
  2354. ar = [];
  2355. // if c's object is also an array we can keep its values.
  2356. if (_isa(c[i])) {
  2357. ar.push.apply(ar, c[i]);
  2358. }
  2359. ar.push.apply(ar, b[i]);
  2360. c[i] = ar;
  2361. }
  2362. else if (_iso(b[i])) {
  2363. // overwite c's value with an object if it is not already one.
  2364. if (!_iso(c[i])) {
  2365. c[i] = {};
  2366. }
  2367. for (var j in b[i]) {
  2368. c[i][j] = b[i][j];
  2369. }
  2370. }
  2371. }
  2372. }
  2373. return c;
  2374. },
  2375. replace: function (inObj, path, value) {
  2376. if (inObj == null) {
  2377. return;
  2378. }
  2379. var q = inObj, t = q;
  2380. path.replace(/([^\.])+/g, function (term, lc, pos, str) {
  2381. var array = term.match(/([^\[0-9]+){1}(\[)([0-9+])/),
  2382. last = pos + term.length >= str.length,
  2383. _getArray = function () {
  2384. return t[array[1]] || (function () {
  2385. t[array[1]] = [];
  2386. return t[array[1]];
  2387. })();
  2388. };
  2389. if (last) {
  2390. // set term = value on current t, creating term as array if necessary.
  2391. if (array) {
  2392. _getArray()[array[3]] = value;
  2393. }
  2394. else {
  2395. t[term] = value;
  2396. }
  2397. }
  2398. else {
  2399. // set to current t[term], creating t[term] if necessary.
  2400. if (array) {
  2401. var a = _getArray();
  2402. t = a[array[3]] || (function () {
  2403. a[array[3]] = {};
  2404. return a[array[3]];
  2405. })();
  2406. }
  2407. else {
  2408. t = t[term] || (function () {
  2409. t[term] = {};
  2410. return t[term];
  2411. })();
  2412. }
  2413. }
  2414. });
  2415. return inObj;
  2416. },
  2417. //
  2418. // chain a list of functions, supplied by [ object, method name, args ], and return on the first
  2419. // one that returns the failValue. if none return the failValue, return the successValue.
  2420. //
  2421. functionChain: function (successValue, failValue, fns) {
  2422. for (var i = 0; i < fns.length; i++) {
  2423. var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]);
  2424. if (o === failValue) {
  2425. return o;
  2426. }
  2427. }
  2428. return successValue;
  2429. },
  2430. // take the given model and expand out any parameters.
  2431. // 'functionPrefix' is optional, and if present, helps jsplumb figure out what to do if a value is a Function.
  2432. // if you do not provide it, jsplumb will run the given values through any functions it finds, and use the function's
  2433. // output as the value in the result. if you do provide the prefix, only functions that are named and have this prefix
  2434. // will be executed; other functions will be passed as values to the output.
  2435. populate: function (model, values, functionPrefix) {
  2436. // for a string, see if it has parameter matches, and if so, try to make the substitutions.
  2437. var getValue = function (fromString) {
  2438. var matches = fromString.match(/(\${.*?})/g);
  2439. if (matches != null) {
  2440. for (var i = 0; i < matches.length; i++) {
  2441. var val = values[matches[i].substring(2, matches[i].length - 1)] || "";
  2442. if (val != null) {
  2443. fromString = fromString.replace(matches[i], val);
  2444. }
  2445. }
  2446. }
  2447. return fromString;
  2448. },
  2449. // process one entry.
  2450. _one = function (d) {
  2451. if (d != null) {
  2452. if (_iss(d)) {
  2453. return getValue(d);
  2454. }
  2455. else if (_isf(d) && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) {
  2456. return d(values);
  2457. }
  2458. else if (_isa(d)) {
  2459. var r = [];
  2460. for (var i = 0; i < d.length; i++) {
  2461. r.push(_one(d[i]));
  2462. }
  2463. return r;
  2464. }
  2465. else if (_iso(d)) {
  2466. var s = {};
  2467. for (var j in d) {
  2468. s[j] = _one(d[j]);
  2469. }
  2470. return s;
  2471. }
  2472. else {
  2473. return d;
  2474. }
  2475. }
  2476. };
  2477. return _one(model);
  2478. },
  2479. findWithFunction: function (a, f) {
  2480. // CONVERTED
  2481. if (a) {
  2482. for (var i = 0; i < a.length; i++) {
  2483. if (f(a[i])) {
  2484. return i;
  2485. }
  2486. }
  2487. }
  2488. return -1;
  2489. },
  2490. removeWithFunction: function (a, f) {
  2491. // CONVERTED
  2492. var idx = root.jsPlumbUtil.findWithFunction(a, f);
  2493. if (idx > -1) {
  2494. a.splice(idx, 1);
  2495. }
  2496. return idx !== -1;
  2497. },
  2498. remove: function (l, v) {
  2499. // CONVERTED
  2500. var idx = l.indexOf(v);
  2501. if (idx > -1) {
  2502. l.splice(idx, 1);
  2503. }
  2504. return idx !== -1;
  2505. },
  2506. // TODO support insert index
  2507. addWithFunction: function (list, item, hashFunction) {
  2508. if (root.jsPlumbUtil.findWithFunction(list, hashFunction) === -1) {
  2509. list.push(item);
  2510. }
  2511. },
  2512. addToList: function (map, key, value, insertAtStart) {
  2513. var l = map[key];
  2514. if (l == null) {
  2515. l = [];
  2516. map[key] = l;
  2517. }
  2518. l[insertAtStart ? "unshift" : "push"](value);
  2519. return l;
  2520. },
  2521. suggest : function(list, item, insertAtHead) {
  2522. if (list.indexOf(item) === -1) {
  2523. if (insertAtHead) {
  2524. list.unshift(item);
  2525. } else {
  2526. list.push(item);
  2527. }
  2528. return true;
  2529. }
  2530. return false;
  2531. },
  2532. //
  2533. // extends the given obj (which can be an array) with the given constructor function, prototype functions, and
  2534. // class members, any of which may be null.
  2535. //
  2536. extend: function (child, parent, _protoFn) {
  2537. var i;
  2538. parent = _isa(parent) ? parent : [ parent ];
  2539. for (i = 0; i < parent.length; i++) {
  2540. for (var j in parent[i].prototype) {
  2541. if (parent[i].prototype.hasOwnProperty(j)) {
  2542. child.prototype[j] = parent[i].prototype[j];
  2543. }
  2544. }
  2545. }
  2546. var _makeFn = function (name, protoFn) {
  2547. return function () {
  2548. for (i = 0; i < parent.length; i++) {
  2549. if (parent[i].prototype[name]) {
  2550. parent[i].prototype[name].apply(this, arguments);
  2551. }
  2552. }
  2553. return protoFn.apply(this, arguments);
  2554. };
  2555. };
  2556. var _oneSet = function (fns) {
  2557. for (var k in fns) {
  2558. child.prototype[k] = _makeFn(k, fns[k]);
  2559. }
  2560. };
  2561. if (arguments.length > 2) {
  2562. for (i = 2; i < arguments.length; i++) {
  2563. _oneSet(arguments[i]);
  2564. }
  2565. }
  2566. return child;
  2567. },
  2568. uuid: function () {
  2569. return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2570. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2571. return v.toString(16);
  2572. }));
  2573. },
  2574. logEnabled: true,
  2575. log: function () {
  2576. if (root.jsPlumbUtil.logEnabled && typeof console !== "undefined") {
  2577. try {
  2578. var msg = arguments[arguments.length - 1];
  2579. console.log(msg);
  2580. }
  2581. catch (e) {
  2582. }
  2583. }
  2584. },
  2585. /**
  2586. * Wraps one function with another, creating a placeholder for the
  2587. * wrapped function if it was null. this is used to wrap the various
  2588. * drag/drop event functions - to allow jsPlumb to be notified of
  2589. * important lifecycle events without imposing itself on the user's
  2590. * drag/drop functionality.
  2591. * @method jsPlumbUtil.wrap
  2592. * @param {Function} wrappedFunction original function to wrap; may be null.
  2593. * @param {Function} newFunction function to wrap the original with.
  2594. * @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should
  2595. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  2596. * note that this is a simple comparison and only works for primitives right now.
  2597. */
  2598. wrap: function (wrappedFunction, newFunction, returnOnThisValue) {
  2599. return function () {
  2600. var r = null;
  2601. try {
  2602. if (newFunction != null) {
  2603. r = newFunction.apply(this, arguments);
  2604. }
  2605. } catch (e) {
  2606. root.jsPlumbUtil.log("jsPlumb function failed : " + e);
  2607. }
  2608. if ((wrappedFunction != null) && (returnOnThisValue == null || (r !== returnOnThisValue))) {
  2609. try {
  2610. r = wrappedFunction.apply(this, arguments);
  2611. } catch (e) {
  2612. root.jsPlumbUtil.log("wrapped function failed : " + e);
  2613. }
  2614. }
  2615. return r;
  2616. };
  2617. }
  2618. };
  2619. root.jsPlumbUtil.EventGenerator = function () {
  2620. var _listeners = {},
  2621. eventsSuspended = false,
  2622. tick = false,
  2623. // this is a list of events that should re-throw any errors that occur during their dispatch. it is current private.
  2624. eventsToDieOn = { "ready": true },
  2625. queue = [];
  2626. this.bind = function (event, listener, insertAtStart) {
  2627. var _one = function(evt) {
  2628. root.jsPlumbUtil.addToList(_listeners, evt, listener, insertAtStart);
  2629. listener.__jsPlumb = listener.__jsPlumb || {};
  2630. listener.__jsPlumb[root.jsPlumbUtil.uuid()] = evt;
  2631. };
  2632. if (typeof event === "string") {
  2633. _one(event);
  2634. }
  2635. else if (event.length != null) {
  2636. for (var i = 0; i < event.length; i++) {
  2637. _one(event[i]);
  2638. }
  2639. }
  2640. return this;
  2641. };
  2642. this.fire = function (event, value, originalEvent) {
  2643. if (!tick) {
  2644. tick = true;
  2645. if (!eventsSuspended && _listeners[event]) {
  2646. var l = _listeners[event].length, i = 0, _gone = false, ret = null;
  2647. if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) {
  2648. while (!_gone && i < l && ret !== false) {
  2649. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  2650. // method will have the whole call stack available in the debugger.
  2651. if (eventsToDieOn[event]) {
  2652. _listeners[event][i].apply(this, [value, originalEvent]);
  2653. }
  2654. else {
  2655. try {
  2656. ret = _listeners[event][i].apply(this, [value, originalEvent]);
  2657. } catch (e) {
  2658. root.jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e);
  2659. }
  2660. }
  2661. i++;
  2662. if (_listeners == null || _listeners[event] == null) {
  2663. _gone = true;
  2664. }
  2665. }
  2666. }
  2667. }
  2668. tick = false;
  2669. _drain();
  2670. } else {
  2671. queue.unshift(arguments);
  2672. }
  2673. return this;
  2674. };
  2675. var _drain = function() {
  2676. var n = queue.pop();
  2677. if (n) {
  2678. this.fire.apply(this, n);
  2679. }
  2680. }.bind(this);
  2681. this.unbind = function (eventOrListener, listener) {
  2682. if (arguments.length === 0) {
  2683. _listeners = {};
  2684. }
  2685. else if (arguments.length === 1) {
  2686. if (typeof eventOrListener === "string") {
  2687. delete _listeners[eventOrListener];
  2688. }
  2689. else if (eventOrListener.__jsPlumb) {
  2690. var evt;
  2691. for (var i in eventOrListener.__jsPlumb) {
  2692. evt = eventOrListener.__jsPlumb[i];
  2693. root.jsPlumbUtil.remove(_listeners[evt] || [], eventOrListener);
  2694. }
  2695. }
  2696. }
  2697. else if (arguments.length === 2) {
  2698. root.jsPlumbUtil.remove(_listeners[eventOrListener] || [], listener);
  2699. }
  2700. return this;
  2701. };
  2702. this.getListener = function (forEvent) {
  2703. return _listeners[forEvent];
  2704. };
  2705. this.setSuspendEvents = function (val) {
  2706. eventsSuspended = val;
  2707. };
  2708. this.isSuspendEvents = function () {
  2709. return eventsSuspended;
  2710. };
  2711. this.silently = function(fn) {
  2712. this.setSuspendEvents(true);
  2713. try {
  2714. fn();
  2715. }
  2716. catch (e) {
  2717. root.jsPlumbUtil.log("Cannot execute silent function " + e);
  2718. }
  2719. this.setSuspendEvents(false);
  2720. };
  2721. this.cleanupListeners = function () {
  2722. for (var i in _listeners) {
  2723. _listeners[i] = null;
  2724. }
  2725. };
  2726. };
  2727. root.jsPlumbUtil.EventGenerator.prototype = {
  2728. cleanup: function () {
  2729. this.cleanupListeners();
  2730. }
  2731. };
  2732. if (typeof exports !== "undefined") {
  2733. exports.jsPlumbUtil = root.jsPlumbUtil;
  2734. }
  2735. }).call(typeof window !== 'undefined' ? window : this);
  2736. /*
  2737. * This file contains utility functions that run in browsers only.
  2738. *
  2739. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  2740. *
  2741. * https://jsplumbtoolkit.com
  2742. * https://github.com/jsplumb/jsplumb
  2743. *
  2744. * Dual licensed under the MIT and GPL2 licenses.
  2745. */
  2746. ;(function() {
  2747. "use strict";
  2748. var root = this;
  2749. root.jsPlumbUtil.matchesSelector = function(el, selector, ctx) {
  2750. ctx = ctx || el.parentNode;
  2751. var possibles = ctx.querySelectorAll(selector);
  2752. for (var i = 0; i < possibles.length; i++) {
  2753. if (possibles[i] === el) {
  2754. return true;
  2755. }
  2756. }
  2757. return false;
  2758. };
  2759. root.jsPlumbUtil.consume = function(e, doNotPreventDefault) {
  2760. if (e.stopPropagation) {
  2761. e.stopPropagation();
  2762. }
  2763. else {
  2764. e.returnValue = false;
  2765. }
  2766. if (!doNotPreventDefault && e.preventDefault){
  2767. e.preventDefault();
  2768. }
  2769. };
  2770. /*
  2771. * Function: sizeElement
  2772. * Helper to size and position an element. You would typically use
  2773. * this when writing your own Connector or Endpoint implementation.
  2774. *
  2775. * Parameters:
  2776. * x - [int] x position for the element origin
  2777. * y - [int] y position for the element origin
  2778. * w - [int] width of the element
  2779. * h - [int] height of the element
  2780. *
  2781. */
  2782. root.jsPlumbUtil.sizeElement = function(el, x, y, w, h) {
  2783. if (el) {
  2784. el.style.height = h + "px";
  2785. el.height = h;
  2786. el.style.width = w + "px";
  2787. el.width = w;
  2788. el.style.left = x + "px";
  2789. el.style.top = y + "px";
  2790. }
  2791. };
  2792. }).call(typeof window !== 'undefined' ? window : this);
  2793. /*
  2794. * This file contains the core code.
  2795. *
  2796. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  2797. *
  2798. * https://jsplumbtoolkit.com
  2799. * https://github.com/jsplumb/jsplumb
  2800. *
  2801. * Dual licensed under the MIT and GPL2 licenses.
  2802. */
  2803. ;(function () {
  2804. "use strict";
  2805. var root = this;
  2806. var _ju = root.jsPlumbUtil,
  2807. /**
  2808. * creates a timestamp, using milliseconds since 1970, but as a string.
  2809. */
  2810. _timestamp = function () {
  2811. return "" + (new Date()).getTime();
  2812. },
  2813. // helper method to update the hover style whenever it, or paintStyle, changes.
  2814. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  2815. // top.
  2816. _updateHoverStyle = function (component) {
  2817. if (component._jsPlumb.paintStyle && component._jsPlumb.hoverPaintStyle) {
  2818. var mergedHoverStyle = {};
  2819. jsPlumb.extend(mergedHoverStyle, component._jsPlumb.paintStyle);
  2820. jsPlumb.extend(mergedHoverStyle, component._jsPlumb.hoverPaintStyle);
  2821. delete component._jsPlumb.hoverPaintStyle;
  2822. // we want the fill of paintStyle to override a gradient, if possible.
  2823. if (mergedHoverStyle.gradient && component._jsPlumb.paintStyle.fill) {
  2824. delete mergedHoverStyle.gradient;
  2825. }
  2826. component._jsPlumb.hoverPaintStyle = mergedHoverStyle;
  2827. }
  2828. },
  2829. events = ["tap", "dbltap", "click", "dblclick", "mouseover", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ],
  2830. eventFilters = { "mouseout": "mouseleave", "mouseexit": "mouseleave" },
  2831. _updateAttachedElements = function (component, state, timestamp, sourceElement) {
  2832. var affectedElements = component.getAttachedElements();
  2833. if (affectedElements) {
  2834. for (var i = 0, j = affectedElements.length; i < j; i++) {
  2835. if (!sourceElement || sourceElement !== affectedElements[i]) {
  2836. affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements.
  2837. }
  2838. }
  2839. }
  2840. },
  2841. _splitType = function (t) {
  2842. return t == null ? null : t.split(" ");
  2843. },
  2844. _mapType = function(map, obj, typeId) {
  2845. for (var i in obj) {
  2846. map[i] = typeId;
  2847. }
  2848. },
  2849. _each = function(fn, obj) {
  2850. obj = _ju.isArray(obj) || (obj.length != null && !_ju.isString(obj)) ? obj : [ obj ];
  2851. for (var i = 0; i < obj.length; i++) {
  2852. try {
  2853. fn.apply(obj[i], [ obj[i] ]);
  2854. }
  2855. catch (e) {
  2856. _ju.log(".each iteration failed : " + e);
  2857. }
  2858. }
  2859. },
  2860. _applyTypes = function (component, params, doNotRepaint) {
  2861. if (component.getDefaultType) {
  2862. var td = component.getTypeDescriptor(), map = {};
  2863. var defType = component.getDefaultType();
  2864. var o = _ju.merge({}, defType);
  2865. _mapType(map, defType, "__default");
  2866. for (var i = 0, j = component._jsPlumb.types.length; i < j; i++) {
  2867. var tid = component._jsPlumb.types[i];
  2868. if (tid !== "__default") {
  2869. var _t = component._jsPlumb.instance.getType(tid, td);
  2870. if (_t != null) {
  2871. o = _ju.merge(o, _t, [ "cssClass" ]);
  2872. _mapType(map, _t, tid);
  2873. }
  2874. }
  2875. }
  2876. if (params) {
  2877. o = _ju.populate(o, params, "_");
  2878. }
  2879. component.applyType(o, doNotRepaint, map);
  2880. if (!doNotRepaint) {
  2881. component.repaint();
  2882. }
  2883. }
  2884. },
  2885. // ------------------------------ BEGIN jsPlumbUIComponent --------------------------------------------
  2886. jsPlumbUIComponent = root.jsPlumbUIComponent = function (params) {
  2887. _ju.EventGenerator.apply(this, arguments);
  2888. var self = this,
  2889. a = arguments,
  2890. idPrefix = self.idPrefix,
  2891. id = idPrefix + (new Date()).getTime();
  2892. this._jsPlumb = {
  2893. instance: params._jsPlumb,
  2894. parameters: params.parameters || {},
  2895. paintStyle: null,
  2896. hoverPaintStyle: null,
  2897. paintStyleInUse: null,
  2898. hover: false,
  2899. beforeDetach: params.beforeDetach,
  2900. beforeDrop: params.beforeDrop,
  2901. overlayPlacements: [],
  2902. hoverClass: params.hoverClass || params._jsPlumb.Defaults.HoverClass,
  2903. types: [],
  2904. typeCache:{}
  2905. };
  2906. this.cacheTypeItem = function(key, item, typeId) {
  2907. this._jsPlumb.typeCache[typeId] = this._jsPlumb.typeCache[typeId] || {};
  2908. this._jsPlumb.typeCache[typeId][key] = item;
  2909. };
  2910. this.getCachedTypeItem = function(key, typeId) {
  2911. return this._jsPlumb.typeCache[typeId] ? this._jsPlumb.typeCache[typeId][key] : null;
  2912. };
  2913. this.getId = function () {
  2914. return id;
  2915. };
  2916. // ----------------------------- default type --------------------------------------------
  2917. var o = params.overlays || [], oo = {};
  2918. if (this.defaultOverlayKeys) {
  2919. for (var i = 0; i < this.defaultOverlayKeys.length; i++) {
  2920. Array.prototype.push.apply(o, this._jsPlumb.instance.Defaults[this.defaultOverlayKeys[i]] || []);
  2921. }
  2922. for (i = 0; i < o.length; i++) {
  2923. // if a string, convert to object representation so that we can store the typeid on it.
  2924. // also assign an id.
  2925. var fo = jsPlumb.convertToFullOverlaySpec(o[i]);
  2926. oo[fo[1].id] = fo;
  2927. }
  2928. }
  2929. var _defaultType = {
  2930. overlays:oo,
  2931. parameters: params.parameters || {},
  2932. scope: params.scope || this._jsPlumb.instance.getDefaultScope()
  2933. };
  2934. this.getDefaultType = function() {
  2935. return _defaultType;
  2936. };
  2937. this.appendToDefaultType = function(obj) {
  2938. for (var i in obj) {
  2939. _defaultType[i] = obj[i];
  2940. }
  2941. };
  2942. // ----------------------------- end default type --------------------------------------------
  2943. // all components can generate events
  2944. if (params.events) {
  2945. for (var evtName in params.events) {
  2946. self.bind(evtName, params.events[evtName]);
  2947. }
  2948. }
  2949. // all components get this clone function.
  2950. // TODO issue 116 showed a problem with this - it seems 'a' that is in
  2951. // the clone function's scope is shared by all invocations of it, the classic
  2952. // JS closure problem. for now, jsPlumb does a version of this inline where
  2953. // it used to call clone. but it would be nice to find some time to look
  2954. // further at this.
  2955. this.clone = function () {
  2956. var o = Object.create(this.constructor.prototype);
  2957. this.constructor.apply(o, a);
  2958. return o;
  2959. }.bind(this);
  2960. // user can supply a beforeDetach callback, which will be executed before a detach
  2961. // is performed; returning false prevents the detach.
  2962. this.isDetachAllowed = function (connection) {
  2963. var r = true;
  2964. if (this._jsPlumb.beforeDetach) {
  2965. try {
  2966. r = this._jsPlumb.beforeDetach(connection);
  2967. }
  2968. catch (e) {
  2969. _ju.log("jsPlumb: beforeDetach callback failed", e);
  2970. }
  2971. }
  2972. return r;
  2973. };
  2974. // user can supply a beforeDrop callback, which will be executed before a dropped
  2975. // connection is confirmed. user can return false to reject connection.
  2976. this.isDropAllowed = function (sourceId, targetId, scope, connection, dropEndpoint, source, target) {
  2977. var r = this._jsPlumb.instance.checkCondition("beforeDrop", {
  2978. sourceId: sourceId,
  2979. targetId: targetId,
  2980. scope: scope,
  2981. connection: connection,
  2982. dropEndpoint: dropEndpoint,
  2983. source: source, target: target
  2984. });
  2985. if (this._jsPlumb.beforeDrop) {
  2986. try {
  2987. r = this._jsPlumb.beforeDrop({
  2988. sourceId: sourceId,
  2989. targetId: targetId,
  2990. scope: scope,
  2991. connection: connection,
  2992. dropEndpoint: dropEndpoint,
  2993. source: source, target: target
  2994. });
  2995. }
  2996. catch (e) {
  2997. _ju.log("jsPlumb: beforeDrop callback failed", e);
  2998. }
  2999. }
  3000. return r;
  3001. };
  3002. var domListeners = [];
  3003. // sets the component associated with listener events. for instance, an overlay delegates
  3004. // its events back to a connector. but if the connector is swapped on the underlying connection,
  3005. // then this component must be changed. This is called by setConnector in the Connection class.
  3006. this.setListenerComponent = function (c) {
  3007. for (var i = 0; i < domListeners.length; i++) {
  3008. domListeners[i][3] = c;
  3009. }
  3010. };
  3011. };
  3012. var _removeTypeCssHelper = function (component, typeIndex) {
  3013. var typeId = component._jsPlumb.types[typeIndex],
  3014. type = component._jsPlumb.instance.getType(typeId, component.getTypeDescriptor());
  3015. if (type != null && type.cssClass && component.canvas) {
  3016. component._jsPlumb.instance.removeClass(component.canvas, type.cssClass);
  3017. }
  3018. };
  3019. _ju.extend(root.jsPlumbUIComponent, _ju.EventGenerator, {
  3020. getParameter: function (name) {
  3021. return this._jsPlumb.parameters[name];
  3022. },
  3023. setParameter: function (name, value) {
  3024. this._jsPlumb.parameters[name] = value;
  3025. },
  3026. getParameters: function () {
  3027. return this._jsPlumb.parameters;
  3028. },
  3029. setParameters: function (p) {
  3030. this._jsPlumb.parameters = p;
  3031. },
  3032. getClass:function() {
  3033. return jsPlumb.getClass(this.canvas);
  3034. },
  3035. hasClass:function(clazz) {
  3036. return jsPlumb.hasClass(this.canvas, clazz);
  3037. },
  3038. addClass: function (clazz) {
  3039. jsPlumb.addClass(this.canvas, clazz);
  3040. },
  3041. removeClass: function (clazz) {
  3042. jsPlumb.removeClass(this.canvas, clazz);
  3043. },
  3044. updateClasses: function (classesToAdd, classesToRemove) {
  3045. jsPlumb.updateClasses(this.canvas, classesToAdd, classesToRemove);
  3046. },
  3047. setType: function (typeId, params, doNotRepaint) {
  3048. this.clearTypes();
  3049. this._jsPlumb.types = _splitType(typeId) || [];
  3050. _applyTypes(this, params, doNotRepaint);
  3051. },
  3052. getType: function () {
  3053. return this._jsPlumb.types;
  3054. },
  3055. reapplyTypes: function (params, doNotRepaint) {
  3056. _applyTypes(this, params, doNotRepaint);
  3057. },
  3058. hasType: function (typeId) {
  3059. return this._jsPlumb.types.indexOf(typeId) !== -1;
  3060. },
  3061. addType: function (typeId, params, doNotRepaint) {
  3062. var t = _splitType(typeId), _cont = false;
  3063. if (t != null) {
  3064. for (var i = 0, j = t.length; i < j; i++) {
  3065. if (!this.hasType(t[i])) {
  3066. this._jsPlumb.types.push(t[i]);
  3067. _cont = true;
  3068. }
  3069. }
  3070. if (_cont) {
  3071. _applyTypes(this, params, doNotRepaint);
  3072. }
  3073. }
  3074. },
  3075. removeType: function (typeId, params, doNotRepaint) {
  3076. var t = _splitType(typeId), _cont = false, _one = function (tt) {
  3077. var idx = this._jsPlumb.types.indexOf(tt);
  3078. if (idx !== -1) {
  3079. // remove css class if necessary
  3080. _removeTypeCssHelper(this, idx);
  3081. this._jsPlumb.types.splice(idx, 1);
  3082. return true;
  3083. }
  3084. return false;
  3085. }.bind(this);
  3086. if (t != null) {
  3087. for (var i = 0, j = t.length; i < j; i++) {
  3088. _cont = _one(t[i]) || _cont;
  3089. }
  3090. if (_cont) {
  3091. _applyTypes(this, params, doNotRepaint);
  3092. }
  3093. }
  3094. },
  3095. clearTypes: function (params, doNotRepaint) {
  3096. var i = this._jsPlumb.types.length;
  3097. for (var j = 0; j < i; j++) {
  3098. _removeTypeCssHelper(this, 0);
  3099. this._jsPlumb.types.splice(0, 1);
  3100. }
  3101. _applyTypes(this, params, doNotRepaint);
  3102. },
  3103. toggleType: function (typeId, params, doNotRepaint) {
  3104. var t = _splitType(typeId);
  3105. if (t != null) {
  3106. for (var i = 0, j = t.length; i < j; i++) {
  3107. var idx = this._jsPlumb.types.indexOf(t[i]);
  3108. if (idx !== -1) {
  3109. _removeTypeCssHelper(this, idx);
  3110. this._jsPlumb.types.splice(idx, 1);
  3111. }
  3112. else {
  3113. this._jsPlumb.types.push(t[i]);
  3114. }
  3115. }
  3116. _applyTypes(this, params, doNotRepaint);
  3117. }
  3118. },
  3119. applyType: function (t, doNotRepaint) {
  3120. this.setPaintStyle(t.paintStyle, doNotRepaint);
  3121. this.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint);
  3122. if (t.parameters) {
  3123. for (var i in t.parameters) {
  3124. this.setParameter(i, t.parameters[i]);
  3125. }
  3126. }
  3127. this._jsPlumb.paintStyleInUse = this.getPaintStyle();
  3128. },
  3129. setPaintStyle: function (style, doNotRepaint) {
  3130. // this._jsPlumb.paintStyle = jsPlumb.extend({}, style);
  3131. // TODO figure out if we want components to clone paintStyle so as not to share it.
  3132. this._jsPlumb.paintStyle = style;
  3133. this._jsPlumb.paintStyleInUse = this._jsPlumb.paintStyle;
  3134. _updateHoverStyle(this);
  3135. if (!doNotRepaint) {
  3136. this.repaint();
  3137. }
  3138. },
  3139. getPaintStyle: function () {
  3140. return this._jsPlumb.paintStyle;
  3141. },
  3142. setHoverPaintStyle: function (style, doNotRepaint) {
  3143. //this._jsPlumb.hoverPaintStyle = jsPlumb.extend({}, style);
  3144. // TODO figure out if we want components to clone paintStyle so as not to share it.
  3145. this._jsPlumb.hoverPaintStyle = style;
  3146. _updateHoverStyle(this);
  3147. if (!doNotRepaint) {
  3148. this.repaint();
  3149. }
  3150. },
  3151. getHoverPaintStyle: function () {
  3152. return this._jsPlumb.hoverPaintStyle;
  3153. },
  3154. destroy: function (force) {
  3155. if (force || this.typeId == null) {
  3156. this.cleanupListeners(); // this is on EventGenerator
  3157. this.clone = null;
  3158. this._jsPlumb = null;
  3159. }
  3160. },
  3161. isHover: function () {
  3162. return this._jsPlumb.hover;
  3163. },
  3164. setHover: function (hover, ignoreAttachedElements, timestamp) {
  3165. // while dragging, we ignore these events. this keeps the UI from flashing and
  3166. // swishing and whatevering.
  3167. if (this._jsPlumb && !this._jsPlumb.instance.currentlyDragging && !this._jsPlumb.instance.isHoverSuspended()) {
  3168. this._jsPlumb.hover = hover;
  3169. var method = hover ? "addClass" : "removeClass";
  3170. if (this.canvas != null) {
  3171. if (this._jsPlumb.instance.hoverClass != null) {
  3172. this._jsPlumb.instance[method](this.canvas, this._jsPlumb.instance.hoverClass);
  3173. }
  3174. if (this._jsPlumb.hoverClass != null) {
  3175. this._jsPlumb.instance[method](this.canvas, this._jsPlumb.hoverClass);
  3176. }
  3177. }
  3178. if (this._jsPlumb.hoverPaintStyle != null) {
  3179. this._jsPlumb.paintStyleInUse = hover ? this._jsPlumb.hoverPaintStyle : this._jsPlumb.paintStyle;
  3180. if (!this._jsPlumb.instance.isSuspendDrawing()) {
  3181. timestamp = timestamp || _timestamp();
  3182. this.repaint({timestamp: timestamp, recalc: false});
  3183. }
  3184. }
  3185. // get the list of other affected elements, if supported by this component.
  3186. // for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  3187. if (this.getAttachedElements && !ignoreAttachedElements) {
  3188. _updateAttachedElements(this, hover, _timestamp(), this);
  3189. }
  3190. }
  3191. }
  3192. });
  3193. // ------------------------------ END jsPlumbUIComponent --------------------------------------------
  3194. var _jsPlumbInstanceIndex = 0,
  3195. getInstanceIndex = function () {
  3196. var i = _jsPlumbInstanceIndex + 1;
  3197. _jsPlumbInstanceIndex++;
  3198. return i;
  3199. };
  3200. var jsPlumbInstance = root.jsPlumbInstance = function (_defaults) {
  3201. this.version = "2.6.7";
  3202. if (_defaults) {
  3203. jsPlumb.extend(this.Defaults, _defaults);
  3204. }
  3205. this.logEnabled = this.Defaults.LogEnabled;
  3206. this._connectionTypes = {};
  3207. this._endpointTypes = {};
  3208. _ju.EventGenerator.apply(this);
  3209. var _currentInstance = this,
  3210. _instanceIndex = getInstanceIndex(),
  3211. _bb = _currentInstance.bind,
  3212. _initialDefaults = {},
  3213. _zoom = 1,
  3214. _info = function (el) {
  3215. if (el == null) {
  3216. return null;
  3217. }
  3218. else if (el.nodeType === 3 || el.nodeType === 8) {
  3219. return { el:el, text:true };
  3220. }
  3221. else {
  3222. var _el = _currentInstance.getElement(el);
  3223. return { el: _el, id: (_ju.isString(el) && _el == null) ? el : _getId(_el) };
  3224. }
  3225. };
  3226. this.getInstanceIndex = function () {
  3227. return _instanceIndex;
  3228. };
  3229. // CONVERTED
  3230. this.setZoom = function (z, repaintEverything) {
  3231. _zoom = z;
  3232. _currentInstance.fire("zoom", _zoom);
  3233. if (repaintEverything) {
  3234. _currentInstance.repaintEverything();
  3235. }
  3236. return true;
  3237. };
  3238. // CONVERTED
  3239. this.getZoom = function () {
  3240. return _zoom;
  3241. };
  3242. for (var i in this.Defaults) {
  3243. _initialDefaults[i] = this.Defaults[i];
  3244. }
  3245. var _container, _containerDelegations = [];
  3246. this.unbindContainer = function() {
  3247. if (_container != null && _containerDelegations.length > 0) {
  3248. for (var i = 0; i < _containerDelegations.length; i++) {
  3249. _currentInstance.off(_container, _containerDelegations[i][0], _containerDelegations[i][1]);
  3250. }
  3251. }
  3252. };
  3253. this.setContainer = function (c) {
  3254. this.unbindContainer();
  3255. // get container as dom element.
  3256. c = this.getElement(c);
  3257. // move existing connections and endpoints, if any.
  3258. this.select().each(function (conn) {
  3259. conn.moveParent(c);
  3260. });
  3261. this.selectEndpoints().each(function (ep) {
  3262. ep.moveParent(c);
  3263. });
  3264. // set container.
  3265. var previousContainer = _container;
  3266. _container = c;
  3267. _containerDelegations.length = 0;
  3268. var eventAliases = {
  3269. "endpointclick":"endpointClick",
  3270. "endpointdblclick":"endpointDblClick"
  3271. };
  3272. var _oneDelegateHandler = function (id, e, componentType) {
  3273. var t = e.srcElement || e.target,
  3274. jp = (t && t.parentNode ? t.parentNode._jsPlumb : null) || (t ? t._jsPlumb : null) || (t && t.parentNode && t.parentNode.parentNode ? t.parentNode.parentNode._jsPlumb : null);
  3275. if (jp) {
  3276. jp.fire(id, jp, e);
  3277. var alias = componentType ? eventAliases[componentType + id] || id : id;
  3278. // jsplumb also fires every event coming from components/overlays. That's what the test for `jp.component` is for.
  3279. _currentInstance.fire(alias, jp.component || jp, e);
  3280. }
  3281. };
  3282. var _addOneDelegate = function(eventId, selector, fn) {
  3283. _containerDelegations.push([eventId, fn]);
  3284. _currentInstance.on(_container, eventId, selector, fn);
  3285. };
  3286. // delegate one event on the container to jsplumb elements. it might be possible to
  3287. // abstract this out: each of endpoint, connection and overlay could register themselves with
  3288. // jsplumb as "component types" or whatever, and provide a suitable selector. this would be
  3289. // done by the renderer (although admittedly from 2.0 onwards we're not supporting vml anymore)
  3290. var _oneDelegate = function (id) {
  3291. // connections.
  3292. _addOneDelegate(id, ".jtk-connector", function (e) {
  3293. _oneDelegateHandler(id, e);
  3294. });
  3295. // endpoints. note they can have an enclosing div, or not.
  3296. _addOneDelegate(id, ".jtk-endpoint", function (e) {
  3297. _oneDelegateHandler(id, e, "endpoint");
  3298. });
  3299. // overlays
  3300. _addOneDelegate(id, ".jtk-overlay", function (e) {
  3301. _oneDelegateHandler(id, e);
  3302. });
  3303. };
  3304. for (var i = 0; i < events.length; i++) {
  3305. _oneDelegate(events[i]);
  3306. }
  3307. // managed elements
  3308. for (var elId in managedElements) {
  3309. var el = managedElements[elId].el;
  3310. if (el.parentNode === previousContainer) {
  3311. previousContainer.removeChild(el);
  3312. _container.appendChild(el);
  3313. }
  3314. }
  3315. };
  3316. this.getContainer = function () {
  3317. return _container;
  3318. };
  3319. this.bind = function (event, fn) {
  3320. if ("ready" === event && initialized) {
  3321. fn();
  3322. }
  3323. else {
  3324. _bb.apply(_currentInstance, [event, fn]);
  3325. }
  3326. };
  3327. _currentInstance.importDefaults = function (d) {
  3328. for (var i in d) {
  3329. _currentInstance.Defaults[i] = d[i];
  3330. }
  3331. if (d.Container) {
  3332. _currentInstance.setContainer(d.Container);
  3333. }
  3334. return _currentInstance;
  3335. };
  3336. _currentInstance.restoreDefaults = function () {
  3337. _currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults);
  3338. return _currentInstance;
  3339. };
  3340. var log = null,
  3341. initialized = false,
  3342. // TODO remove from window scope
  3343. connections = [],
  3344. // map of element id -> endpoint lists. an element can have an arbitrary
  3345. // number of endpoints on it, and not all of them have to be connected
  3346. // to anything.
  3347. endpointsByElement = {},
  3348. endpointsByUUID = {},
  3349. managedElements = {},
  3350. offsets = {},
  3351. offsetTimestamps = {},
  3352. draggableStates = {},
  3353. connectionBeingDragged = false,
  3354. sizes = [],
  3355. _suspendDrawing = false,
  3356. _suspendedAt = null,
  3357. DEFAULT_SCOPE = this.Defaults.Scope,
  3358. _curIdStamp = 1,
  3359. _idstamp = function () {
  3360. return "" + _curIdStamp++;
  3361. },
  3362. //
  3363. // appends an element to some other element, which is calculated as follows:
  3364. //
  3365. // 1. if Container exists, use that element.
  3366. // 2. if the 'parent' parameter exists, use that.
  3367. // 3. otherwise just use the root element.
  3368. //
  3369. //
  3370. _appendElement = function (el, parent) {
  3371. if (_container) {
  3372. _container.appendChild(el);
  3373. }
  3374. else if (!parent) {
  3375. this.appendToRoot(el);
  3376. }
  3377. else {
  3378. this.getElement(parent).appendChild(el);
  3379. }
  3380. }.bind(this),
  3381. //
  3382. // Draws an endpoint and its connections. this is the main entry point into drawing connections as well
  3383. // as endpoints, since jsPlumb is endpoint-centric under the hood.
  3384. //
  3385. // @param element element to draw (of type library specific element object)
  3386. // @param ui UI object from current library's event system. optional.
  3387. // @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  3388. // @param clearEdits defaults to false; indicates that mouse edits for connectors should be cleared
  3389. ///
  3390. _draw = function (element, ui, timestamp, clearEdits) {
  3391. if (!_suspendDrawing) {
  3392. var id = _getId(element),
  3393. repaintEls,
  3394. dm = _currentInstance.getDragManager();
  3395. if (dm) {
  3396. repaintEls = dm.getElementsForDraggable(id);
  3397. }
  3398. if (timestamp == null) {
  3399. timestamp = _timestamp();
  3400. }
  3401. // update the offset of everything _before_ we try to draw anything.
  3402. var o = _updateOffset({ elId: id, offset: ui, recalc: false, timestamp: timestamp });
  3403. if (repaintEls && o && o.o) {
  3404. for (var i in repaintEls) {
  3405. _updateOffset({
  3406. elId: repaintEls[i].id,
  3407. offset: {
  3408. left: o.o.left + repaintEls[i].offset.left,
  3409. top: o.o.top + repaintEls[i].offset.top
  3410. },
  3411. recalc: false,
  3412. timestamp: timestamp
  3413. });
  3414. }
  3415. }
  3416. _currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits);
  3417. if (repaintEls) {
  3418. for (var j in repaintEls) {
  3419. _currentInstance.anchorManager.redraw(repaintEls[j].id, ui, timestamp, repaintEls[j].offset, clearEdits, true);
  3420. }
  3421. }
  3422. }
  3423. },
  3424. //
  3425. // gets an Endpoint by uuid.
  3426. //
  3427. _getEndpoint = function (uuid) {
  3428. return endpointsByUUID[uuid];
  3429. },
  3430. /**
  3431. * inits a draggable if it's not already initialised.
  3432. * TODO: somehow abstract this to the adapter, because the concept of "draggable" has no
  3433. * place on the server.
  3434. */
  3435. _initDraggableIfNecessary = function (element, isDraggable, dragOptions, id, fireEvent) {
  3436. // move to DragManager?
  3437. if (!jsPlumb.headless) {
  3438. var _draggable = isDraggable == null ? false : isDraggable;
  3439. if (_draggable) {
  3440. if (jsPlumb.isDragSupported(element, _currentInstance)) {
  3441. var options = dragOptions || _currentInstance.Defaults.DragOptions;
  3442. options = jsPlumb.extend({}, options); // make a copy.
  3443. if (!jsPlumb.isAlreadyDraggable(element, _currentInstance)) {
  3444. var dragEvent = jsPlumb.dragEvents.drag,
  3445. stopEvent = jsPlumb.dragEvents.stop,
  3446. startEvent = jsPlumb.dragEvents.start,
  3447. _started = false;
  3448. _manage(id, element);
  3449. options[startEvent] = _ju.wrap(options[startEvent], function () {
  3450. _currentInstance.setHoverSuspended(true);
  3451. _currentInstance.select({source: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
  3452. _currentInstance.select({target: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
  3453. _currentInstance.setConnectionBeingDragged(true);
  3454. if (options.canDrag) {
  3455. return dragOptions.canDrag();
  3456. }
  3457. }, false);
  3458. options[dragEvent] = _ju.wrap(options[dragEvent], function () {
  3459. // TODO: here we could actually use getDragObject, and then compute it ourselves,
  3460. // since every adapter does the same thing. but i'm not sure why YUI's getDragObject
  3461. // differs from getUIPosition so much
  3462. var ui = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom());
  3463. if (ui != null) {
  3464. _draw(element, ui, null, true);
  3465. if (_started) {
  3466. _currentInstance.addClass(element, "jtk-dragged");
  3467. }
  3468. _started = true;
  3469. }
  3470. });
  3471. options[stopEvent] = _ju.wrap(options[stopEvent], function () {
  3472. var elements = arguments[0].selection, uip;
  3473. var _one = function (_e) {
  3474. if (_e[1] != null) {
  3475. // run the reported offset through the code that takes parent containers
  3476. // into account, to adjust if necessary (issue 554)
  3477. uip = _currentInstance.getUIPosition([{
  3478. el:_e[2].el,
  3479. pos:[_e[1].left, _e[1].top]
  3480. }]);
  3481. _draw(_e[2].el, uip);
  3482. }
  3483. _currentInstance.removeClass(_e[0], "jtk-dragged");
  3484. _currentInstance.select({source: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
  3485. _currentInstance.select({target: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
  3486. _currentInstance.getDragManager().dragEnded(_e[2].el);
  3487. };
  3488. for (var i = 0; i < elements.length; i++) {
  3489. _one(elements[i]);
  3490. }
  3491. _started = false;
  3492. _currentInstance.setHoverSuspended(false);
  3493. _currentInstance.setConnectionBeingDragged(false);
  3494. });
  3495. var elId = _getId(element); // need ID
  3496. draggableStates[elId] = true;
  3497. var draggable = draggableStates[elId];
  3498. options.disabled = draggable == null ? false : !draggable;
  3499. _currentInstance.initDraggable(element, options);
  3500. _currentInstance.getDragManager().register(element);
  3501. if (fireEvent) {
  3502. _currentInstance.fire("elementDraggable", {el:element, options:options});
  3503. }
  3504. }
  3505. else {
  3506. // already draggable. attach any start, drag or stop listeners to the current Drag.
  3507. if (dragOptions.force) {
  3508. _currentInstance.initDraggable(element, options);
  3509. }
  3510. }
  3511. }
  3512. }
  3513. }
  3514. },
  3515. _scopeMatch = function (e1, e2) {
  3516. var s1 = e1.scope.split(/\s/), s2 = e2.scope.split(/\s/);
  3517. for (var i = 0; i < s1.length; i++) {
  3518. for (var j = 0; j < s2.length; j++) {
  3519. if (s2[j] === s1[i]) {
  3520. return true;
  3521. }
  3522. }
  3523. }
  3524. return false;
  3525. },
  3526. _mergeOverrides = function (def, values) {
  3527. var m = jsPlumb.extend({}, def);
  3528. for (var i in values) {
  3529. if (values[i]) {
  3530. m[i] = values[i];
  3531. }
  3532. }
  3533. return m;
  3534. },
  3535. /*
  3536. * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc.
  3537. */
  3538. _prepareConnectionParams = function (params, referenceParams) {
  3539. var _p = jsPlumb.extend({ }, params);
  3540. if (referenceParams) {
  3541. jsPlumb.extend(_p, referenceParams);
  3542. }
  3543. // hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively.
  3544. if (_p.source) {
  3545. if (_p.source.endpoint) {
  3546. _p.sourceEndpoint = _p.source;
  3547. }
  3548. else {
  3549. _p.source = _currentInstance.getElement(_p.source);
  3550. }
  3551. }
  3552. if (_p.target) {
  3553. if (_p.target.endpoint) {
  3554. _p.targetEndpoint = _p.target;
  3555. }
  3556. else {
  3557. _p.target = _currentInstance.getElement(_p.target);
  3558. }
  3559. }
  3560. // test for endpoint uuids to connect
  3561. if (params.uuids) {
  3562. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  3563. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  3564. }
  3565. // now ensure that if we do have Endpoints already, they're not full.
  3566. // source:
  3567. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  3568. _ju.log(_currentInstance, "could not add connection; source endpoint is full");
  3569. return;
  3570. }
  3571. // target:
  3572. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  3573. _ju.log(_currentInstance, "could not add connection; target endpoint is full");
  3574. return;
  3575. }
  3576. // if source endpoint mandates connection type and nothing specified in our params, use it.
  3577. if (!_p.type && _p.sourceEndpoint) {
  3578. _p.type = _p.sourceEndpoint.connectionType;
  3579. }
  3580. // copy in any connectorOverlays that were specified on the source endpoint.
  3581. // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not.
  3582. if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) {
  3583. _p.overlays = _p.overlays || [];
  3584. for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) {
  3585. _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]);
  3586. }
  3587. }
  3588. // scope
  3589. if (_p.sourceEndpoint && _p.sourceEndpoint.scope) {
  3590. _p.scope = _p.sourceEndpoint.scope;
  3591. }
  3592. // pointer events
  3593. if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents) {
  3594. _p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents;
  3595. }
  3596. var _addEndpoint = function (el, def, idx) {
  3597. return _currentInstance.addEndpoint(el, _mergeOverrides(def, {
  3598. anchor: _p.anchors ? _p.anchors[idx] : _p.anchor,
  3599. endpoint: _p.endpoints ? _p.endpoints[idx] : _p.endpoint,
  3600. paintStyle: _p.endpointStyles ? _p.endpointStyles[idx] : _p.endpointStyle,
  3601. hoverPaintStyle: _p.endpointHoverStyles ? _p.endpointHoverStyles[idx] : _p.endpointHoverStyle
  3602. }));
  3603. };
  3604. // check for makeSource/makeTarget specs.
  3605. var _oneElementDef = function (type, idx, defs, matchType) {
  3606. if (_p[type] && !_p[type].endpoint && !_p[type + "Endpoint"] && !_p.newConnection) {
  3607. var tid = _getId(_p[type]), tep = defs[tid];
  3608. tep = tep ? tep[matchType] : null;
  3609. if (tep) {
  3610. // if not enabled, return.
  3611. if (!tep.enabled) {
  3612. return false;
  3613. }
  3614. var newEndpoint = tep.endpoint != null && tep.endpoint._jsPlumb ? tep.endpoint : _addEndpoint(_p[type], tep.def, idx);
  3615. if (newEndpoint.isFull()) {
  3616. return false;
  3617. }
  3618. _p[type + "Endpoint"] = newEndpoint;
  3619. if (!_p.scope && tep.def.scope) {
  3620. _p.scope = tep.def.scope;
  3621. } // provide scope if not already provided and endpoint def has one.
  3622. if (tep.uniqueEndpoint) {
  3623. if (!tep.endpoint) {
  3624. tep.endpoint = newEndpoint;
  3625. newEndpoint.setDeleteOnEmpty(false);
  3626. }
  3627. else {
  3628. newEndpoint.finalEndpoint = tep.endpoint;
  3629. }
  3630. } else {
  3631. newEndpoint.setDeleteOnEmpty(true);
  3632. }
  3633. //
  3634. // copy in connector overlays if present on the source definition.
  3635. //
  3636. if (idx === 0 && tep.def.connectorOverlays) {
  3637. _p.overlays = _p.overlays || [];
  3638. Array.prototype.push.apply(_p.overlays, tep.def.connectorOverlays);
  3639. }
  3640. }
  3641. }
  3642. };
  3643. if (_oneElementDef("source", 0, this.sourceEndpointDefinitions, _p.type || "default") === false) {
  3644. return;
  3645. }
  3646. if (_oneElementDef("target", 1, this.targetEndpointDefinitions, _p.type || "default") === false) {
  3647. return;
  3648. }
  3649. // last, ensure scopes match
  3650. if (_p.sourceEndpoint && _p.targetEndpoint) {
  3651. if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) {
  3652. _p = null;
  3653. }
  3654. }
  3655. return _p;
  3656. }.bind(_currentInstance),
  3657. _newConnection = function (params) {
  3658. var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType();
  3659. params._jsPlumb = _currentInstance;
  3660. params.newConnection = _newConnection;
  3661. params.newEndpoint = _newEndpoint;
  3662. params.endpointsByUUID = endpointsByUUID;
  3663. params.endpointsByElement = endpointsByElement;
  3664. params.finaliseConnection = _finaliseConnection;
  3665. params.id = "con_" + _idstamp();
  3666. var con = new connectionFunc(params);
  3667. // if the connection is draggable, then maybe we need to tell the target endpoint to init the
  3668. // dragging code. it won't run again if it already configured to be draggable.
  3669. if (con.isDetachable()) {
  3670. con.endpoints[0].initDraggable("_jsPlumbSource");
  3671. con.endpoints[1].initDraggable("_jsPlumbTarget");
  3672. }
  3673. return con;
  3674. },
  3675. //
  3676. // adds the connection to the backing model, fires an event if necessary and then redraws
  3677. //
  3678. _finaliseConnection = _currentInstance.finaliseConnection = function (jpc, params, originalEvent, doInformAnchorManager) {
  3679. params = params || {};
  3680. // add to list of connections (by scope).
  3681. if (!jpc.suspendedEndpoint) {
  3682. connections.push(jpc);
  3683. }
  3684. jpc.pending = null;
  3685. // turn off isTemporarySource on the source endpoint (only viable on first draw)
  3686. jpc.endpoints[0].isTemporarySource = false;
  3687. // always inform the anchor manager
  3688. // except that if jpc has a suspended endpoint it's not true to say the
  3689. // connection is new; it has just (possibly) moved. the question is whether
  3690. // to make that call here or in the anchor manager. i think perhaps here.
  3691. if (doInformAnchorManager !== false) {
  3692. _currentInstance.anchorManager.newConnection(jpc);
  3693. }
  3694. // force a paint
  3695. _draw(jpc.source);
  3696. // fire an event
  3697. if (!params.doNotFireConnectionEvent && params.fireEvent !== false) {
  3698. var eventArgs = {
  3699. connection: jpc,
  3700. source: jpc.source, target: jpc.target,
  3701. sourceId: jpc.sourceId, targetId: jpc.targetId,
  3702. sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
  3703. };
  3704. _currentInstance.fire("connection", eventArgs, originalEvent);
  3705. }
  3706. },
  3707. /*
  3708. factory method to prepare a new endpoint. this should always be used instead of creating Endpoints
  3709. manually, since this method attaches event listeners and an id.
  3710. */
  3711. _newEndpoint = function (params, id) {
  3712. var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint;
  3713. var _p = jsPlumb.extend({}, params);
  3714. _p._jsPlumb = _currentInstance;
  3715. _p.newConnection = _newConnection;
  3716. _p.newEndpoint = _newEndpoint;
  3717. _p.endpointsByUUID = endpointsByUUID;
  3718. _p.endpointsByElement = endpointsByElement;
  3719. _p.fireDetachEvent = fireDetachEvent;
  3720. _p.elementId = id || _getId(_p.source);
  3721. var ep = new endpointFunc(_p);
  3722. ep.id = "ep_" + _idstamp();
  3723. _manage(_p.elementId, _p.source);
  3724. if (!jsPlumb.headless) {
  3725. _currentInstance.getDragManager().endpointAdded(_p.source, id);
  3726. }
  3727. return ep;
  3728. },
  3729. /*
  3730. * performs the given function operation on all the connections found
  3731. * for the given element id; this means we find all the endpoints for
  3732. * the given element, and then for each endpoint find the connectors
  3733. * connected to it. then we pass each connection in to the given
  3734. * function.
  3735. */
  3736. _operation = function (elId, func, endpointFunc) {
  3737. var endpoints = endpointsByElement[elId];
  3738. if (endpoints && endpoints.length) {
  3739. for (var i = 0, ii = endpoints.length; i < ii; i++) {
  3740. for (var j = 0, jj = endpoints[i].connections.length; j < jj; j++) {
  3741. var retVal = func(endpoints[i].connections[j]);
  3742. // if the function passed in returns true, we exit.
  3743. // most functions return false.
  3744. if (retVal) {
  3745. return;
  3746. }
  3747. }
  3748. if (endpointFunc) {
  3749. endpointFunc(endpoints[i]);
  3750. }
  3751. }
  3752. }
  3753. },
  3754. _setDraggable = function (element, draggable) {
  3755. return jsPlumb.each(element, function (el) {
  3756. if (_currentInstance.isDragSupported(el)) {
  3757. draggableStates[_currentInstance.getAttribute(el, "id")] = draggable;
  3758. _currentInstance.setElementDraggable(el, draggable);
  3759. }
  3760. });
  3761. },
  3762. /*
  3763. * private method to do the business of hiding/showing.
  3764. *
  3765. * @param el
  3766. * either Id of the element in question or a library specific
  3767. * object for the element.
  3768. * @param state
  3769. * String specifying a value for the css 'display' property
  3770. * ('block' or 'none').
  3771. */
  3772. _setVisible = function (el, state, alsoChangeEndpoints) {
  3773. state = state === "block";
  3774. var endpointFunc = null;
  3775. if (alsoChangeEndpoints) {
  3776. endpointFunc = function (ep) {
  3777. ep.setVisible(state, true, true);
  3778. };
  3779. }
  3780. var info = _info(el);
  3781. _operation(info.id, function (jpc) {
  3782. if (state && alsoChangeEndpoints) {
  3783. // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
  3784. // this block will only set a connection to be visible if the other endpoint in the connection is also visible.
  3785. var oidx = jpc.sourceId === info.id ? 1 : 0;
  3786. if (jpc.endpoints[oidx].isVisible()) {
  3787. jpc.setVisible(true);
  3788. }
  3789. }
  3790. else { // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
  3791. jpc.setVisible(state);
  3792. }
  3793. }, endpointFunc);
  3794. },
  3795. /*
  3796. * toggles the draggable state of the given element(s).
  3797. * el is either an id, or an element object, or a list of ids/element objects.
  3798. */
  3799. _toggleDraggable = function (el) {
  3800. var state;
  3801. jsPlumb.each(el, function (el) {
  3802. var elId = _currentInstance.getAttribute(el, "id");
  3803. state = draggableStates[elId] == null ? false : draggableStates[elId];
  3804. state = !state;
  3805. draggableStates[elId] = state;
  3806. _currentInstance.setDraggable(el, state);
  3807. return state;
  3808. }.bind(this));
  3809. return state;
  3810. },
  3811. /**
  3812. * private method to do the business of toggling hiding/showing.
  3813. */
  3814. _toggleVisible = function (elId, changeEndpoints) {
  3815. var endpointFunc = null;
  3816. if (changeEndpoints) {
  3817. endpointFunc = function (ep) {
  3818. var state = ep.isVisible();
  3819. ep.setVisible(!state);
  3820. };
  3821. }
  3822. _operation(elId, function (jpc) {
  3823. var state = jpc.isVisible();
  3824. jpc.setVisible(!state);
  3825. }, endpointFunc);
  3826. },
  3827. // TODO comparison performance
  3828. _getCachedData = function (elId) {
  3829. var o = offsets[elId];
  3830. if (!o) {
  3831. return _updateOffset({elId: elId});
  3832. }
  3833. else {
  3834. return {o: o, s: sizes[elId]};
  3835. }
  3836. },
  3837. /**
  3838. * gets an id for the given element, creating and setting one if
  3839. * necessary. the id is of the form
  3840. *
  3841. * jsPlumb_<instance index>_<index in instance>
  3842. *
  3843. * where "index in instance" is a monotonically increasing integer that starts at 0,
  3844. * for each instance. this method is used not only to assign ids to elements that do not
  3845. * have them but also to connections and endpoints.
  3846. */
  3847. _getId = function (element, uuid, doNotCreateIfNotFound) {
  3848. if (_ju.isString(element)) {
  3849. return element;
  3850. }
  3851. if (element == null) {
  3852. return null;
  3853. }
  3854. var id = _currentInstance.getAttribute(element, "id");
  3855. if (!id || id === "undefined") {
  3856. // check if fixed uuid parameter is given
  3857. if (arguments.length === 2 && arguments[1] !== undefined) {
  3858. id = uuid;
  3859. }
  3860. else if (arguments.length === 1 || (arguments.length === 3 && !arguments[2])) {
  3861. id = "jsPlumb_" + _instanceIndex + "_" + _idstamp();
  3862. }
  3863. if (!doNotCreateIfNotFound) {
  3864. _currentInstance.setAttribute(element, "id", id);
  3865. }
  3866. }
  3867. return id;
  3868. };
  3869. this.setConnectionBeingDragged = function (v) {
  3870. connectionBeingDragged = v;
  3871. };
  3872. this.isConnectionBeingDragged = function () {
  3873. return connectionBeingDragged;
  3874. };
  3875. /**
  3876. * Returns a map of all the elements this jsPlumbInstance is currently managing.
  3877. * @returns {Object} Map of [id-> {el, endpoint[], connection, position}] information.
  3878. */
  3879. this.getManagedElements = function() {
  3880. return managedElements;
  3881. };
  3882. this.connectorClass = "jtk-connector";
  3883. this.connectorOutlineClass = "jtk-connector-outline";
  3884. this.editableConnectorClass = "jtk-connector-editable";
  3885. this.connectedClass = "jtk-connected";
  3886. this.hoverClass = "jtk-hover";
  3887. this.endpointClass = "jtk-endpoint";
  3888. this.endpointConnectedClass = "jtk-endpoint-connected";
  3889. this.endpointFullClass = "jtk-endpoint-full";
  3890. this.endpointDropAllowedClass = "jtk-endpoint-drop-allowed";
  3891. this.endpointDropForbiddenClass = "jtk-endpoint-drop-forbidden";
  3892. this.overlayClass = "jtk-overlay";
  3893. this.draggingClass = "jtk-dragging";// CONVERTED
  3894. this.elementDraggingClass = "jtk-element-dragging";// CONVERTED
  3895. this.sourceElementDraggingClass = "jtk-source-element-dragging"; // CONVERTED
  3896. this.targetElementDraggingClass = "jtk-target-element-dragging";// CONVERTED
  3897. this.endpointAnchorClassPrefix = "jtk-endpoint-anchor";
  3898. this.hoverSourceClass = "jtk-source-hover";
  3899. this.hoverTargetClass = "jtk-target-hover";
  3900. this.dragSelectClass = "jtk-drag-select";
  3901. this.Anchors = {};
  3902. this.Connectors = { "svg": {} };
  3903. this.Endpoints = { "svg": {} };
  3904. this.Overlays = { "svg": {} } ;
  3905. this.ConnectorRenderers = {};
  3906. this.SVG = "svg";
  3907. // --------------------------- jsPlumbInstance public API ---------------------------------------------------------
  3908. this.addEndpoint = function (el, params, referenceParams) {
  3909. referenceParams = referenceParams || {};
  3910. var p = jsPlumb.extend({}, referenceParams);
  3911. jsPlumb.extend(p, params);
  3912. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint;
  3913. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle;
  3914. var results = [],
  3915. inputs = (_ju.isArray(el) || (el.length != null && !_ju.isString(el))) ? el : [ el ];
  3916. for (var i = 0, j = inputs.length; i < j; i++) {
  3917. p.source = _currentInstance.getElement(inputs[i]);
  3918. _ensureContainer(p.source);
  3919. var id = _getId(p.source), e = _newEndpoint(p, id);
  3920. // ensure element is managed.
  3921. var myOffset = _manage(id, p.source).info.o;
  3922. _ju.addToList(endpointsByElement, id, e);
  3923. if (!_suspendDrawing) {
  3924. e.paint({
  3925. anchorLoc: e.anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: sizes[id], element: e, timestamp: _suspendedAt }),
  3926. timestamp: _suspendedAt
  3927. });
  3928. }
  3929. results.push(e);
  3930. }
  3931. return results.length === 1 ? results[0] : results;
  3932. };
  3933. this.addEndpoints = function (el, endpoints, referenceParams) {
  3934. var results = [];
  3935. for (var i = 0, j = endpoints.length; i < j; i++) {
  3936. var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
  3937. if (_ju.isArray(e)) {
  3938. Array.prototype.push.apply(results, e);
  3939. }
  3940. else {
  3941. results.push(e);
  3942. }
  3943. }
  3944. return results;
  3945. };
  3946. this.animate = function (el, properties, options) {
  3947. if (!this.animationSupported) {
  3948. return false;
  3949. }
  3950. options = options || {};
  3951. var del = _currentInstance.getElement(el),
  3952. id = _getId(del),
  3953. stepFunction = jsPlumb.animEvents.step,
  3954. completeFunction = jsPlumb.animEvents.complete;
  3955. options[stepFunction] = _ju.wrap(options[stepFunction], function () {
  3956. _currentInstance.revalidate(id);
  3957. });
  3958. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  3959. options[completeFunction] = _ju.wrap(options[completeFunction], function () {
  3960. _currentInstance.revalidate(id);
  3961. });
  3962. _currentInstance.doAnimate(del, properties, options);
  3963. };
  3964. /**
  3965. * checks for a listener for the given condition, executing it if found, passing in the given value.
  3966. * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since
  3967. * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition"
  3968. * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these
  3969. * condition events anyway.
  3970. */
  3971. this.checkCondition = function (conditionName, args) {
  3972. var l = _currentInstance.getListener(conditionName),
  3973. r = true;
  3974. if (l && l.length > 0) {
  3975. var values = Array.prototype.slice.call(arguments, 1);
  3976. try {
  3977. for (var i = 0, j = l.length; i < j; i++) {
  3978. r = r && l[i].apply(l[i], values);
  3979. }
  3980. }
  3981. catch (e) {
  3982. _ju.log(_currentInstance, "cannot check condition [" + conditionName + "]" + e);
  3983. }
  3984. }
  3985. return r;
  3986. };
  3987. this.connect = function (params, referenceParams) {
  3988. // prepare a final set of parameters to create connection with
  3989. var _p = _prepareConnectionParams(params, referenceParams), jpc;
  3990. // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams
  3991. // will return null (and log something) if either endpoint was full. what would be nicer is to
  3992. // create a dedicated 'error' object.
  3993. if (_p) {
  3994. if (_p.source == null && _p.sourceEndpoint == null) {
  3995. _ju.log("Cannot establish connection - source does not exist");
  3996. return;
  3997. }
  3998. if (_p.target == null && _p.targetEndpoint == null) {
  3999. _ju.log("Cannot establish connection - target does not exist");
  4000. return;
  4001. }
  4002. _ensureContainer(_p.source);
  4003. // create the connection. it is not yet registered
  4004. jpc = _newConnection(_p);
  4005. // now add it the model, fire an event, and redraw
  4006. _finaliseConnection(jpc, _p);
  4007. }
  4008. return jpc;
  4009. };
  4010. var stTypes = [
  4011. { el: "source", elId: "sourceId", epDefs: "sourceEndpointDefinitions" },
  4012. { el: "target", elId: "targetId", epDefs: "targetEndpointDefinitions" }
  4013. ];
  4014. var _set = function (c, el, idx, doNotRepaint) {
  4015. var ep, _st = stTypes[idx], cId = c[_st.elId], cEl = c[_st.el], sid, sep,
  4016. oldEndpoint = c.endpoints[idx];
  4017. var evtParams = {
  4018. index: idx,
  4019. originalSourceId: idx === 0 ? cId : c.sourceId,
  4020. newSourceId: c.sourceId,
  4021. originalTargetId: idx === 1 ? cId : c.targetId,
  4022. newTargetId: c.targetId,
  4023. connection: c
  4024. };
  4025. if (el.constructor === jsPlumb.Endpoint) {
  4026. ep = el;
  4027. ep.addConnection(c);
  4028. el = ep.element;
  4029. }
  4030. else {
  4031. sid = _getId(el);
  4032. sep = this[_st.epDefs][sid];
  4033. if (sid === c[_st.elId]) {
  4034. ep = null; // dont change source/target if the element is already the one given.
  4035. }
  4036. else if (sep) {
  4037. for (var t in sep) {
  4038. if (!sep[t].enabled) {
  4039. return;
  4040. }
  4041. ep = sep[t].endpoint != null && sep[t].endpoint._jsPlumb ? sep[t].endpoint : this.addEndpoint(el, sep[t].def);
  4042. if (sep[t].uniqueEndpoint) {
  4043. sep[t].endpoint = ep;
  4044. }
  4045. ep.addConnection(c);
  4046. }
  4047. }
  4048. else {
  4049. ep = c.makeEndpoint(idx === 0, el, sid);
  4050. }
  4051. }
  4052. if (ep != null) {
  4053. oldEndpoint.detachFromConnection(c);
  4054. c.endpoints[idx] = ep;
  4055. c[_st.el] = ep.element;
  4056. c[_st.elId] = ep.elementId;
  4057. evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId;
  4058. fireMoveEvent(evtParams);
  4059. if (!doNotRepaint) {
  4060. c.repaint();
  4061. }
  4062. }
  4063. evtParams.element = el;
  4064. return evtParams;
  4065. }.bind(this);
  4066. this.setSource = function (connection, el, doNotRepaint) {
  4067. var p = _set(connection, el, 0, doNotRepaint);
  4068. this.anchorManager.sourceChanged(p.originalSourceId, p.newSourceId, connection, p.el);
  4069. };
  4070. this.setTarget = function (connection, el, doNotRepaint) {
  4071. var p = _set(connection, el, 1, doNotRepaint);
  4072. this.anchorManager.updateOtherEndpoint(p.originalSourceId, p.originalTargetId, p.newTargetId, connection);
  4073. };
  4074. this.deleteEndpoint = function (object, dontUpdateHover, deleteAttachedObjects) {
  4075. var endpoint = (typeof object === "string") ? endpointsByUUID[object] : object;
  4076. if (endpoint) {
  4077. _currentInstance.deleteObject({ endpoint: endpoint, dontUpdateHover: dontUpdateHover, deleteAttachedObjects:deleteAttachedObjects });
  4078. }
  4079. return _currentInstance;
  4080. };
  4081. this.deleteEveryEndpoint = function () {
  4082. var _is = _currentInstance.setSuspendDrawing(true);
  4083. for (var id in endpointsByElement) {
  4084. var endpoints = endpointsByElement[id];
  4085. if (endpoints && endpoints.length) {
  4086. for (var i = 0, j = endpoints.length; i < j; i++) {
  4087. _currentInstance.deleteEndpoint(endpoints[i], true);
  4088. }
  4089. }
  4090. }
  4091. endpointsByElement = {};
  4092. managedElements = {};
  4093. endpointsByUUID = {};
  4094. offsets = {};
  4095. offsetTimestamps = {};
  4096. _currentInstance.anchorManager.reset();
  4097. var dm = _currentInstance.getDragManager();
  4098. if (dm) {
  4099. dm.reset();
  4100. }
  4101. if (!_is) {
  4102. _currentInstance.setSuspendDrawing(false);
  4103. }
  4104. return _currentInstance;
  4105. };
  4106. var fireDetachEvent = function (jpc, doFireEvent, originalEvent) {
  4107. // may have been given a connection, or in special cases, an object
  4108. var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
  4109. argIsConnection = jpc.constructor === connType,
  4110. params = argIsConnection ? {
  4111. connection: jpc,
  4112. source: jpc.source, target: jpc.target,
  4113. sourceId: jpc.sourceId, targetId: jpc.targetId,
  4114. sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
  4115. } : jpc;
  4116. if (doFireEvent) {
  4117. _currentInstance.fire("connectionDetached", params, originalEvent);
  4118. }
  4119. // always fire this. used by internal jsplumb stuff.
  4120. _currentInstance.fire("internal.connectionDetached", params, originalEvent);
  4121. _currentInstance.anchorManager.connectionDetached(params);
  4122. };
  4123. var fireMoveEvent = _currentInstance.fireMoveEvent = function (params, evt) {
  4124. _currentInstance.fire("connectionMoved", params, evt);
  4125. };
  4126. this.unregisterEndpoint = function (endpoint) {
  4127. if (endpoint._jsPlumb.uuid) {
  4128. endpointsByUUID[endpoint._jsPlumb.uuid] = null;
  4129. }
  4130. _currentInstance.anchorManager.deleteEndpoint(endpoint);
  4131. // TODO at least replace this with a removeWithFunction call.
  4132. for (var e in endpointsByElement) {
  4133. var endpoints = endpointsByElement[e];
  4134. if (endpoints) {
  4135. var newEndpoints = [];
  4136. for (var i = 0, j = endpoints.length; i < j; i++) {
  4137. if (endpoints[i] !== endpoint) {
  4138. newEndpoints.push(endpoints[i]);
  4139. }
  4140. }
  4141. endpointsByElement[e] = newEndpoints;
  4142. }
  4143. if (endpointsByElement[e].length < 1) {
  4144. delete endpointsByElement[e];
  4145. }
  4146. }
  4147. };
  4148. var IS_DETACH_ALLOWED = "isDetachAllowed";
  4149. var BEFORE_DETACH = "beforeDetach";
  4150. var CHECK_CONDITION = "checkCondition";
  4151. /**
  4152. * Deletes a Connection.
  4153. * @method deleteConnection
  4154. * @param connection Connection to delete
  4155. * @param {Object} [params] Optional delete parameters
  4156. * @param {Boolean} [params.doNotFireEvent=false] If true, a connection detached event will not be fired. Otherwise one will.
  4157. * @param {Boolean} [params.force=false] If true, the connection will be deleted even if a beforeDetach interceptor tries to stop the deletion.
  4158. * @returns {Boolean} True if the connection was deleted, false otherwise.
  4159. */
  4160. this.deleteConnection = function(connection, params) {
  4161. if (connection != null) {
  4162. params = params || {};
  4163. if (params.force || _ju.functionChain(true, false, [
  4164. [ connection.endpoints[0], IS_DETACH_ALLOWED, [ connection ] ],
  4165. [ connection.endpoints[1], IS_DETACH_ALLOWED, [ connection ] ],
  4166. [ connection, IS_DETACH_ALLOWED, [ connection ] ],
  4167. [ _currentInstance, CHECK_CONDITION, [ BEFORE_DETACH, connection ] ]
  4168. ])) {
  4169. connection.setHover(false);
  4170. fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent);
  4171. connection.endpoints[0].detachFromConnection(connection);
  4172. connection.endpoints[1].detachFromConnection(connection);
  4173. _ju.removeWithFunction(connections, function (_c) {
  4174. return connection.id === _c.id;
  4175. });
  4176. connection.cleanup();
  4177. connection.destroy();
  4178. return true;
  4179. }
  4180. }
  4181. return false;
  4182. };
  4183. /**
  4184. * Remove all Connections from all elements, but leaves Endpoints in place ((unless a connection is set to auto delete its Endpoints).
  4185. * @method deleteEveryConnection
  4186. * @param {Object} [params] optional params object for the call
  4187. * @param {Boolean} [params.fireEvent=true] Whether or not to fire detach events
  4188. * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
  4189. * @returns {Number} The number of connections that were deleted.
  4190. */
  4191. this.deleteEveryConnection = function (params) {
  4192. params = params || {};
  4193. var count = connections.length, deletedCount = 0;
  4194. _currentInstance.batch(function () {
  4195. for (var i = 0; i < count; i++) {
  4196. deletedCount += _currentInstance.deleteConnection(connections[0], params) ? 1 : 0;
  4197. }
  4198. });
  4199. return deletedCount;
  4200. };
  4201. /**
  4202. * Removes all an element's Connections.
  4203. * @method deleteConnectionsForElement
  4204. * @param {Object} el Either the id of the element, or a selector for the element.
  4205. * @param {Object} [params] Optional parameters.
  4206. * @param {Boolean} [params.fireEvent=true] Whether or not to fire the detach event.
  4207. * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
  4208. * @return {jsPlumbInstance} The current jsPlumb instance.
  4209. */
  4210. this.deleteConnectionsForElement = function (el, params) {
  4211. params = params || {};
  4212. el = _currentInstance.getElement(el);
  4213. var id = _getId(el), endpoints = endpointsByElement[id];
  4214. if (endpoints && endpoints.length) {
  4215. for (var i = 0, j = endpoints.length; i < j; i++) {
  4216. endpoints[i].deleteEveryConnection(params);
  4217. }
  4218. }
  4219. return _currentInstance;
  4220. };
  4221. /// not public. but of course its exposed. how to change this.
  4222. this.deleteObject = function (params) {
  4223. var result = {
  4224. endpoints: {},
  4225. connections: {},
  4226. endpointCount: 0,
  4227. connectionCount: 0
  4228. },
  4229. deleteAttachedObjects = params.deleteAttachedObjects !== false;
  4230. var unravelConnection = function (connection) {
  4231. if (connection != null && result.connections[connection.id] == null) {
  4232. if (!params.dontUpdateHover && connection._jsPlumb != null) {
  4233. connection.setHover(false);
  4234. }
  4235. result.connections[connection.id] = connection;
  4236. result.connectionCount++;
  4237. }
  4238. };
  4239. var unravelEndpoint = function (endpoint) {
  4240. if (endpoint != null && result.endpoints[endpoint.id] == null) {
  4241. if (!params.dontUpdateHover && endpoint._jsPlumb != null) {
  4242. endpoint.setHover(false);
  4243. }
  4244. result.endpoints[endpoint.id] = endpoint;
  4245. result.endpointCount++;
  4246. if (deleteAttachedObjects) {
  4247. for (var i = 0; i < endpoint.connections.length; i++) {
  4248. var c = endpoint.connections[i];
  4249. unravelConnection(c);
  4250. }
  4251. }
  4252. }
  4253. };
  4254. if (params.connection) {
  4255. unravelConnection(params.connection);
  4256. }
  4257. else {
  4258. unravelEndpoint(params.endpoint);
  4259. }
  4260. // loop through connections
  4261. for (var i in result.connections) {
  4262. var c = result.connections[i];
  4263. if (c._jsPlumb) {
  4264. _ju.removeWithFunction(connections, function (_c) {
  4265. return c.id === _c.id;
  4266. });
  4267. fireDetachEvent(c, params.fireEvent === false ? false : !c.pending, params.originalEvent);
  4268. var doNotCleanup = params.deleteAttachedObjects == null ? null : !params.deleteAttachedObjects;
  4269. c.endpoints[0].detachFromConnection(c, null, doNotCleanup);
  4270. c.endpoints[1].detachFromConnection(c, null, doNotCleanup);
  4271. c.cleanup(true);
  4272. c.destroy(true);
  4273. }
  4274. }
  4275. // loop through endpoints
  4276. for (var j in result.endpoints) {
  4277. var e = result.endpoints[j];
  4278. if (e._jsPlumb) {
  4279. _currentInstance.unregisterEndpoint(e);
  4280. // FIRE some endpoint deleted event?
  4281. e.cleanup(true);
  4282. e.destroy(true);
  4283. }
  4284. }
  4285. return result;
  4286. };
  4287. this.draggable = function (el, options) {
  4288. var info;
  4289. _each(function(_el) {
  4290. info = _info(_el);
  4291. if (info.el) {
  4292. _initDraggableIfNecessary(info.el, true, options, info.id, true);
  4293. }
  4294. }, el);
  4295. return _currentInstance;
  4296. };
  4297. this.droppable = function(el, options) {
  4298. var info;
  4299. options = options || {};
  4300. options.allowLoopback = false;
  4301. _each(function(_el) {
  4302. info = _info(_el);
  4303. if (info.el) {
  4304. _currentInstance.initDroppable(info.el, options);
  4305. }
  4306. }, el);
  4307. return _currentInstance;
  4308. };
  4309. // helpers for select/selectEndpoints
  4310. var _setOperation = function (list, func, args, selector) {
  4311. for (var i = 0, j = list.length; i < j; i++) {
  4312. list[i][func].apply(list[i], args);
  4313. }
  4314. return selector(list);
  4315. },
  4316. _getOperation = function (list, func, args) {
  4317. var out = [];
  4318. for (var i = 0, j = list.length; i < j; i++) {
  4319. out.push([ list[i][func].apply(list[i], args), list[i] ]);
  4320. }
  4321. return out;
  4322. },
  4323. setter = function (list, func, selector) {
  4324. return function () {
  4325. return _setOperation(list, func, arguments, selector);
  4326. };
  4327. },
  4328. getter = function (list, func) {
  4329. return function () {
  4330. return _getOperation(list, func, arguments);
  4331. };
  4332. },
  4333. prepareList = function (input, doNotGetIds) {
  4334. var r = [];
  4335. if (input) {
  4336. if (typeof input === 'string') {
  4337. if (input === "*") {
  4338. return input;
  4339. }
  4340. r.push(input);
  4341. }
  4342. else {
  4343. if (doNotGetIds) {
  4344. r = input;
  4345. }
  4346. else {
  4347. if (input.length) {
  4348. for (var i = 0, j = input.length; i < j; i++) {
  4349. r.push(_info(input[i]).id);
  4350. }
  4351. }
  4352. else {
  4353. r.push(_info(input).id);
  4354. }
  4355. }
  4356. }
  4357. }
  4358. return r;
  4359. },
  4360. filterList = function (list, value, missingIsFalse) {
  4361. if (list === "*") {
  4362. return true;
  4363. }
  4364. return list.length > 0 ? list.indexOf(value) !== -1 : !missingIsFalse;
  4365. };
  4366. // get some connections, specifying source/target/scope
  4367. this.getConnections = function (options, flat) {
  4368. if (!options) {
  4369. options = {};
  4370. } else if (options.constructor === String) {
  4371. options = { "scope": options };
  4372. }
  4373. var scope = options.scope || _currentInstance.getDefaultScope(),
  4374. scopes = prepareList(scope, true),
  4375. sources = prepareList(options.source),
  4376. targets = prepareList(options.target),
  4377. results = (!flat && scopes.length > 1) ? {} : [],
  4378. _addOne = function (scope, obj) {
  4379. if (!flat && scopes.length > 1) {
  4380. var ss = results[scope];
  4381. if (ss == null) {
  4382. ss = results[scope] = [];
  4383. }
  4384. ss.push(obj);
  4385. } else {
  4386. results.push(obj);
  4387. }
  4388. };
  4389. for (var j = 0, jj = connections.length; j < jj; j++) {
  4390. var c = connections[j],
  4391. sourceId = c.proxies && c.proxies[0] ? c.proxies[0].originalEp.elementId : c.sourceId,
  4392. targetId = c.proxies && c.proxies[1] ? c.proxies[1].originalEp.elementId : c.targetId;
  4393. if (filterList(scopes, c.scope) && filterList(sources, sourceId) && filterList(targets, targetId)) {
  4394. _addOne(c.scope, c);
  4395. }
  4396. }
  4397. return results;
  4398. };
  4399. var _curryEach = function (list, executor) {
  4400. return function (f) {
  4401. for (var i = 0, ii = list.length; i < ii; i++) {
  4402. f(list[i]);
  4403. }
  4404. return executor(list);
  4405. };
  4406. },
  4407. _curryGet = function (list) {
  4408. return function (idx) {
  4409. return list[idx];
  4410. };
  4411. };
  4412. var _makeCommonSelectHandler = function (list, executor) {
  4413. var out = {
  4414. length: list.length,
  4415. each: _curryEach(list, executor),
  4416. get: _curryGet(list)
  4417. },
  4418. setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay",
  4419. "removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle",
  4420. "setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible",
  4421. "repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ],
  4422. getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle",
  4423. "getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ],
  4424. i, ii;
  4425. for (i = 0, ii = setters.length; i < ii; i++) {
  4426. out[setters[i]] = setter(list, setters[i], executor);
  4427. }
  4428. for (i = 0, ii = getters.length; i < ii; i++) {
  4429. out[getters[i]] = getter(list, getters[i]);
  4430. }
  4431. return out;
  4432. };
  4433. var _makeConnectionSelectHandler = function (list) {
  4434. var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler);
  4435. return jsPlumb.extend(common, {
  4436. // setters
  4437. setDetachable: setter(list, "setDetachable", _makeConnectionSelectHandler),
  4438. setReattach: setter(list, "setReattach", _makeConnectionSelectHandler),
  4439. setConnector: setter(list, "setConnector", _makeConnectionSelectHandler),
  4440. delete: function () {
  4441. for (var i = 0, ii = list.length; i < ii; i++) {
  4442. _currentInstance.deleteConnection(list[i]);
  4443. }
  4444. },
  4445. // getters
  4446. isDetachable: getter(list, "isDetachable"),
  4447. isReattach: getter(list, "isReattach")
  4448. });
  4449. };
  4450. var _makeEndpointSelectHandler = function (list) {
  4451. var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler);
  4452. return jsPlumb.extend(common, {
  4453. setEnabled: setter(list, "setEnabled", _makeEndpointSelectHandler),
  4454. setAnchor: setter(list, "setAnchor", _makeEndpointSelectHandler),
  4455. isEnabled: getter(list, "isEnabled"),
  4456. deleteEveryConnection: function () {
  4457. for (var i = 0, ii = list.length; i < ii; i++) {
  4458. list[i].deleteEveryConnection();
  4459. }
  4460. },
  4461. "delete": function () {
  4462. for (var i = 0, ii = list.length; i < ii; i++) {
  4463. _currentInstance.deleteEndpoint(list[i]);
  4464. }
  4465. }
  4466. });
  4467. };
  4468. this.select = function (params) {
  4469. params = params || {};
  4470. params.scope = params.scope || "*";
  4471. return _makeConnectionSelectHandler(params.connections || _currentInstance.getConnections(params, true));
  4472. };
  4473. this.selectEndpoints = function (params) {
  4474. params = params || {};
  4475. params.scope = params.scope || "*";
  4476. var noElementFilters = !params.element && !params.source && !params.target,
  4477. elements = noElementFilters ? "*" : prepareList(params.element),
  4478. sources = noElementFilters ? "*" : prepareList(params.source),
  4479. targets = noElementFilters ? "*" : prepareList(params.target),
  4480. scopes = prepareList(params.scope, true);
  4481. var ep = [];
  4482. for (var el in endpointsByElement) {
  4483. var either = filterList(elements, el, true),
  4484. source = filterList(sources, el, true),
  4485. sourceMatchExact = sources !== "*",
  4486. target = filterList(targets, el, true),
  4487. targetMatchExact = targets !== "*";
  4488. // if they requested 'either' then just match scope. otherwise if they requested 'source' (not as a wildcard) then we have to match only endpoints that have isSource set to to true, and the same thing with isTarget.
  4489. if (either || source || target) {
  4490. inner:
  4491. for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) {
  4492. var _ep = endpointsByElement[el][i];
  4493. if (filterList(scopes, _ep.scope, true)) {
  4494. var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource),
  4495. noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget);
  4496. if (noMatchSource || noMatchTarget) {
  4497. continue inner;
  4498. }
  4499. ep.push(_ep);
  4500. }
  4501. }
  4502. }
  4503. }
  4504. return _makeEndpointSelectHandler(ep);
  4505. };
  4506. // get all connections managed by the instance of jsplumb.
  4507. this.getAllConnections = function () {
  4508. return connections;
  4509. };
  4510. this.getDefaultScope = function () {
  4511. return DEFAULT_SCOPE;
  4512. };
  4513. // get an endpoint by uuid.
  4514. this.getEndpoint = _getEndpoint;
  4515. /**
  4516. * Gets the list of Endpoints for a given element.
  4517. * @method getEndpoints
  4518. * @param {String|Element|Selector} el The element to get endpoints for.
  4519. * @return {Endpoint[]} An array of Endpoints for the specified element.
  4520. */
  4521. this.getEndpoints = function (el) {
  4522. return endpointsByElement[_info(el).id] || [];
  4523. };
  4524. // gets the default endpoint type. used when subclassing. see wiki.
  4525. this.getDefaultEndpointType = function () {
  4526. return jsPlumb.Endpoint;
  4527. };
  4528. // gets the default connection type. used when subclassing. see wiki.
  4529. this.getDefaultConnectionType = function () {
  4530. return jsPlumb.Connection;
  4531. };
  4532. /*
  4533. * Gets an element's id, creating one if necessary. really only exposed
  4534. * for the lib-specific functionality to access; would be better to pass
  4535. * the current instance into the lib-specific code (even though this is
  4536. * a static call. i just don't want to expose it to the public API).
  4537. */
  4538. this.getId = _getId;
  4539. this.appendElement = _appendElement;
  4540. var _hoverSuspended = false;
  4541. this.isHoverSuspended = function () {
  4542. return _hoverSuspended;
  4543. };
  4544. this.setHoverSuspended = function (s) {
  4545. _hoverSuspended = s;
  4546. };
  4547. // set an element's connections to be hidden
  4548. this.hide = function (el, changeEndpoints) {
  4549. _setVisible(el, "none", changeEndpoints);
  4550. return _currentInstance;
  4551. };
  4552. // exposed for other objects to use to get a unique id.
  4553. this.idstamp = _idstamp;
  4554. // this.connectorsInitialized = false;
  4555. // this.registerConnectorType = function (connector, name) {
  4556. // connectorTypes.push([connector, name]);
  4557. // };
  4558. // ensure that, if the current container exists, it is a DOM element and not a selector.
  4559. // if it does not exist and `candidate` is supplied, the offset parent of that element will be set as the Container.
  4560. // this is used to do a better default behaviour for the case that the user has not set a container:
  4561. // addEndpoint, makeSource, makeTarget and connect all call this method with the offsetParent of the
  4562. // element in question (for connect it is the source element). So if no container is set, it is inferred
  4563. // to be the offsetParent of the first element the user tries to connect.
  4564. var _ensureContainer = function (candidate) {
  4565. if (!_container && candidate) {
  4566. var can = _currentInstance.getElement(candidate);
  4567. if (can.offsetParent) {
  4568. _currentInstance.setContainer(can.offsetParent);
  4569. }
  4570. }
  4571. };
  4572. var _getContainerFromDefaults = function () {
  4573. if (_currentInstance.Defaults.Container) {
  4574. _currentInstance.setContainer(_currentInstance.Defaults.Container);
  4575. }
  4576. };
  4577. // check if a given element is managed or not. if not, add to our map. if drawing is not suspended then
  4578. // we'll also stash its dimensions; otherwise we'll do this in a lazy way through updateOffset.
  4579. var _manage = _currentInstance.manage = function (id, element, _transient) {
  4580. if (!managedElements[id]) {
  4581. managedElements[id] = {
  4582. el: element,
  4583. endpoints: [],
  4584. connections: []
  4585. };
  4586. managedElements[id].info = _updateOffset({ elId: id, timestamp: _suspendedAt });
  4587. if (!_transient) {
  4588. _currentInstance.fire("manageElement", { id:id, info:managedElements[id].info, el:element });
  4589. }
  4590. }
  4591. return managedElements[id];
  4592. };
  4593. var _unmanage = function(id) {
  4594. if (managedElements[id]) {
  4595. delete managedElements[id];
  4596. _currentInstance.fire("unmanageElement", id);
  4597. }
  4598. };
  4599. /**
  4600. * updates the offset and size for a given element, and stores the
  4601. * values. if 'offset' is not null we use that (it would have been
  4602. * passed in from a drag call) because it's faster; but if it is null,
  4603. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  4604. */
  4605. var _updateOffset = this.updateOffset = function (params) {
  4606. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId, s;
  4607. if (_suspendDrawing && !timestamp) {
  4608. timestamp = _suspendedAt;
  4609. }
  4610. if (!recalc) {
  4611. if (timestamp && timestamp === offsetTimestamps[elId]) {
  4612. return {o: params.offset || offsets[elId], s: sizes[elId]};
  4613. }
  4614. }
  4615. if (recalc || (!offset && offsets[elId] == null)) { // if forced repaint or no offset available, we recalculate.
  4616. // get the current size and offset, and store them
  4617. s = managedElements[elId] ? managedElements[elId].el : null;
  4618. if (s != null) {
  4619. sizes[elId] = _currentInstance.getSize(s);
  4620. offsets[elId] = _currentInstance.getOffset(s);
  4621. offsetTimestamps[elId] = timestamp;
  4622. }
  4623. } else {
  4624. offsets[elId] = offset || offsets[elId];
  4625. if (sizes[elId] == null) {
  4626. s = managedElements[elId].el;
  4627. if (s != null) {
  4628. sizes[elId] = _currentInstance.getSize(s);
  4629. }
  4630. }
  4631. offsetTimestamps[elId] = timestamp;
  4632. }
  4633. if (offsets[elId] && !offsets[elId].right) {
  4634. offsets[elId].right = offsets[elId].left + sizes[elId][0];
  4635. offsets[elId].bottom = offsets[elId].top + sizes[elId][1];
  4636. offsets[elId].width = sizes[elId][0];
  4637. offsets[elId].height = sizes[elId][1];
  4638. offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2);
  4639. offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2);
  4640. }
  4641. return {o: offsets[elId], s: sizes[elId]};
  4642. };
  4643. /**
  4644. * callback from the current library to tell us to prepare ourselves (attach
  4645. * mouse listeners etc; can't do that until the library has provided a bind method)
  4646. */
  4647. this.init = function () {
  4648. if (!initialized) {
  4649. _getContainerFromDefaults();
  4650. _currentInstance.anchorManager = new root.jsPlumb.AnchorManager({jsPlumbInstance: _currentInstance});
  4651. initialized = true;
  4652. _currentInstance.fire("ready", _currentInstance);
  4653. }
  4654. }.bind(this);
  4655. this.log = log;
  4656. this.jsPlumbUIComponent = jsPlumbUIComponent;
  4657. /*
  4658. * Creates an anchor with the given params.
  4659. *
  4660. *
  4661. * Returns: The newly created Anchor.
  4662. * Throws: an error if a named anchor was not found.
  4663. */
  4664. this.makeAnchor = function () {
  4665. var pp, _a = function (t, p) {
  4666. if (root.jsPlumb.Anchors[t]) {
  4667. return new root.jsPlumb.Anchors[t](p);
  4668. }
  4669. if (!_currentInstance.Defaults.DoNotThrowErrors) {
  4670. throw { msg: "jsPlumb: unknown anchor type '" + t + "'" };
  4671. }
  4672. };
  4673. if (arguments.length === 0) {
  4674. return null;
  4675. }
  4676. var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null;
  4677. // if it appears to be an anchor already...
  4678. if (specimen.compute && specimen.getOrientation) {
  4679. return specimen;
  4680. } //TODO hazy here about whether it should be added or is already added somehow.
  4681. // is it the name of an anchor type?
  4682. else if (typeof specimen === "string") {
  4683. newAnchor = _a(arguments[0], {elementId: elementId, jsPlumbInstance: _currentInstance});
  4684. }
  4685. // is it an array? it will be one of:
  4686. // an array of [spec, params] - this defines a single anchor, which may be dynamic, but has parameters.
  4687. // an array of arrays - this defines some dynamic anchors
  4688. // an array of numbers - this defines a single anchor.
  4689. else if (_ju.isArray(specimen)) {
  4690. if (_ju.isArray(specimen[0]) || _ju.isString(specimen[0])) {
  4691. // if [spec, params] format
  4692. if (specimen.length === 2 && _ju.isObject(specimen[1])) {
  4693. // if first arg is a string, its a named anchor with params
  4694. if (_ju.isString(specimen[0])) {
  4695. pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance}, specimen[1]);
  4696. newAnchor = _a(specimen[0], pp);
  4697. }
  4698. // otherwise first arg is array, second is params. we treat as a dynamic anchor, which is fine
  4699. // even if the first arg has only one entry. you could argue all anchors should be implicitly dynamic in fact.
  4700. else {
  4701. pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance, anchors: specimen[0]}, specimen[1]);
  4702. newAnchor = new root.jsPlumb.DynamicAnchor(pp);
  4703. }
  4704. }
  4705. else {
  4706. newAnchor = new jsPlumb.DynamicAnchor({anchors: specimen, selector: null, elementId: elementId, jsPlumbInstance: _currentInstance});
  4707. }
  4708. }
  4709. else {
  4710. var anchorParams = {
  4711. x: specimen[0], y: specimen[1],
  4712. orientation: (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0, 0],
  4713. offsets: (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ],
  4714. elementId: elementId,
  4715. jsPlumbInstance: _currentInstance,
  4716. cssClass: specimen.length === 7 ? specimen[6] : null
  4717. };
  4718. newAnchor = new root.jsPlumb.Anchor(anchorParams);
  4719. newAnchor.clone = function () {
  4720. return new root.jsPlumb.Anchor(anchorParams);
  4721. };
  4722. }
  4723. }
  4724. if (!newAnchor.id) {
  4725. newAnchor.id = "anchor_" + _idstamp();
  4726. }
  4727. return newAnchor;
  4728. };
  4729. /**
  4730. * makes a list of anchors from the given list of types or coords, eg
  4731. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  4732. */
  4733. this.makeAnchors = function (types, elementId, jsPlumbInstance) {
  4734. var r = [];
  4735. for (var i = 0, ii = types.length; i < ii; i++) {
  4736. if (typeof types[i] === "string") {
  4737. r.push(root.jsPlumb.Anchors[types[i]]({elementId: elementId, jsPlumbInstance: jsPlumbInstance}));
  4738. }
  4739. else if (_ju.isArray(types[i])) {
  4740. r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance));
  4741. }
  4742. }
  4743. return r;
  4744. };
  4745. /**
  4746. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  4747. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  4748. * not need to provide this - i think).
  4749. */
  4750. this.makeDynamicAnchor = function (anchors, anchorSelector) {
  4751. return new root.jsPlumb.DynamicAnchor({anchors: anchors, selector: anchorSelector, elementId: null, jsPlumbInstance: _currentInstance});
  4752. };
  4753. // --------------------- makeSource/makeTarget ----------------------------------------------
  4754. this.targetEndpointDefinitions = {};
  4755. this.sourceEndpointDefinitions = {};
  4756. var selectorFilter = function (evt, _el, selector, _instance, negate) {
  4757. var t = evt.target || evt.srcElement, ok = false,
  4758. sel = _instance.getSelector(_el, selector);
  4759. for (var j = 0; j < sel.length; j++) {
  4760. if (sel[j] === t) {
  4761. ok = true;
  4762. break;
  4763. }
  4764. }
  4765. return negate ? !ok : ok;
  4766. };
  4767. var _makeElementDropHandler = function (elInfo, p, dropOptions, isSource, isTarget) {
  4768. var proxyComponent = new jsPlumbUIComponent(p);
  4769. var _drop = p._jsPlumb.EndpointDropHandler({
  4770. jsPlumb: _currentInstance,
  4771. enabled: function () {
  4772. return elInfo.def.enabled;
  4773. },
  4774. isFull: function () {
  4775. var targetCount = _currentInstance.select({target: elInfo.id}).length;
  4776. return elInfo.def.maxConnections > 0 && targetCount >= elInfo.def.maxConnections;
  4777. },
  4778. element: elInfo.el,
  4779. elementId: elInfo.id,
  4780. isSource: isSource,
  4781. isTarget: isTarget,
  4782. addClass: function (clazz) {
  4783. _currentInstance.addClass(elInfo.el, clazz);
  4784. },
  4785. removeClass: function (clazz) {
  4786. _currentInstance.removeClass(elInfo.el, clazz);
  4787. },
  4788. onDrop: function (jpc) {
  4789. var source = jpc.endpoints[0];
  4790. source.anchor.locked = false;
  4791. },
  4792. isDropAllowed: function () {
  4793. return proxyComponent.isDropAllowed.apply(proxyComponent, arguments);
  4794. },
  4795. isRedrop:function(jpc) {
  4796. return (jpc.suspendedElement != null && jpc.suspendedEndpoint != null && jpc.suspendedEndpoint.element === elInfo.el);
  4797. },
  4798. getEndpoint: function (jpc) {
  4799. // make a new Endpoint for the target, or get it from the cache if uniqueEndpoint
  4800. // is set. if its a redrop the new endpoint will be immediately cleaned up.
  4801. var newEndpoint = elInfo.def.endpoint;
  4802. // if no cached endpoint, or there was one but it has been cleaned up
  4803. // (ie. detached), create a new one
  4804. if (newEndpoint == null || newEndpoint._jsPlumb == null) {
  4805. var eps = _currentInstance.deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true);
  4806. var pp = eps.endpoints ? root.jsPlumb.extend(p, {
  4807. endpoint:elInfo.def.def.endpoint || eps.endpoints[1]
  4808. }) :p;
  4809. if (eps.anchors) {
  4810. pp = root.jsPlumb.extend(pp, {
  4811. anchor:elInfo.def.def.anchor || eps.anchors[1]
  4812. });
  4813. }
  4814. newEndpoint = _currentInstance.addEndpoint(elInfo.el, pp);
  4815. newEndpoint._mtNew = true;
  4816. }
  4817. if (p.uniqueEndpoint) {
  4818. elInfo.def.endpoint = newEndpoint;
  4819. }
  4820. newEndpoint.setDeleteOnEmpty(true);
  4821. // if connection is detachable, init the new endpoint to be draggable, to support that happening.
  4822. if (jpc.isDetachable()) {
  4823. newEndpoint.initDraggable();
  4824. }
  4825. // if the anchor has a 'positionFinder' set, then delegate to that function to find
  4826. // out where to locate the anchor.
  4827. if (newEndpoint.anchor.positionFinder != null) {
  4828. var dropPosition = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()),
  4829. elPosition = _currentInstance.getOffset(elInfo.el),
  4830. elSize = _currentInstance.getSize(elInfo.el),
  4831. ap = dropPosition == null ? [0,0] : newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams);
  4832. newEndpoint.anchor.x = ap[0];
  4833. newEndpoint.anchor.y = ap[1];
  4834. // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to
  4835. // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation
  4836. // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be
  4837. // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which
  4838. // the target is furthest away from the source.
  4839. }
  4840. return newEndpoint;
  4841. },
  4842. maybeCleanup: function (ep) {
  4843. if (ep._mtNew && ep.connections.length === 0) {
  4844. _currentInstance.deleteObject({endpoint: ep});
  4845. }
  4846. else {
  4847. delete ep._mtNew;
  4848. }
  4849. }
  4850. });
  4851. // wrap drop events as needed and initialise droppable
  4852. var dropEvent = root.jsPlumb.dragEvents.drop;
  4853. dropOptions.scope = dropOptions.scope || (p.scope || _currentInstance.Defaults.Scope);
  4854. dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], _drop, true);
  4855. // if target, return true from the over event. this will cause katavorio to stop setting drops to hover
  4856. // if multipleDrop is set to false.
  4857. if (isTarget) {
  4858. dropOptions[root.jsPlumb.dragEvents.over] = function () { return true; };
  4859. }
  4860. // vanilla jsplumb only
  4861. if (p.allowLoopback === false) {
  4862. dropOptions.canDrop = function (_drag) {
  4863. var de = _drag.getDragElement()._jsPlumbRelatedElement;
  4864. return de !== elInfo.el;
  4865. };
  4866. }
  4867. _currentInstance.initDroppable(elInfo.el, dropOptions, "internal");
  4868. return _drop;
  4869. };
  4870. // see API docs
  4871. this.makeTarget = function (el, params, referenceParams) {
  4872. // put jsplumb ref into params without altering the params passed in
  4873. var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
  4874. root.jsPlumb.extend(p, params);
  4875. var maxConnections = p.maxConnections || -1,
  4876. _doOne = function (el) {
  4877. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  4878. // and use the endpoint definition if found.
  4879. // decode the info for this element (id and element)
  4880. var elInfo = _info(el),
  4881. elid = elInfo.id,
  4882. dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}),
  4883. type = p.connectionType || "default";
  4884. this.targetEndpointDefinitions[elid] = this.targetEndpointDefinitions[elid] || {};
  4885. _ensureContainer(elid);
  4886. // if this is a group and the user has not mandated a rank, set to -1 so that Nodes takes
  4887. // precedence.
  4888. if (elInfo.el._isJsPlumbGroup && dropOptions.rank == null) {
  4889. dropOptions.rank = -1;
  4890. }
  4891. // store the definition
  4892. var _def = {
  4893. def: root.jsPlumb.extend({}, p),
  4894. uniqueEndpoint: p.uniqueEndpoint,
  4895. maxConnections: maxConnections,
  4896. enabled: true
  4897. };
  4898. if (p.createEndpoint) {
  4899. _def.uniqueEndpoint = true;
  4900. _def.endpoint = _currentInstance.addEndpoint(el, _def.def);
  4901. _def.endpoint.setDeleteOnEmpty(false);
  4902. }
  4903. elInfo.def = _def;
  4904. this.targetEndpointDefinitions[elid][type] = _def;
  4905. _makeElementDropHandler(elInfo, p, dropOptions, p.isSource === true, true);
  4906. // stash the definition on the drop
  4907. elInfo.el._katavorioDrop[elInfo.el._katavorioDrop.length - 1].targetDef = _def;
  4908. }.bind(this);
  4909. // make an array if only given one element
  4910. var inputs = el.length && el.constructor !== String ? el : [ el ];
  4911. // register each one in the list.
  4912. for (var i = 0, ii = inputs.length; i < ii; i++) {
  4913. _doOne(inputs[i]);
  4914. }
  4915. return this;
  4916. };
  4917. // see api docs
  4918. this.unmakeTarget = function (el, doNotClearArrays) {
  4919. var info = _info(el);
  4920. _currentInstance.destroyDroppable(info.el, "internal");
  4921. if (!doNotClearArrays) {
  4922. delete this.targetEndpointDefinitions[info.id];
  4923. }
  4924. return this;
  4925. };
  4926. // see api docs
  4927. this.makeSource = function (el, params, referenceParams) {
  4928. var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
  4929. root.jsPlumb.extend(p, params);
  4930. var type = p.connectionType || "default";
  4931. var aae = _currentInstance.deriveEndpointAndAnchorSpec(type);
  4932. p.endpoint = p.endpoint || aae.endpoints[0];
  4933. p.anchor = p.anchor || aae.anchors[0];
  4934. var maxConnections = p.maxConnections || -1,
  4935. onMaxConnections = p.onMaxConnections,
  4936. _doOne = function (elInfo) {
  4937. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  4938. // and use the endpoint definition if found.
  4939. var elid = elInfo.id,
  4940. _del = this.getElement(elInfo.el);
  4941. this.sourceEndpointDefinitions[elid] = this.sourceEndpointDefinitions[elid] || {};
  4942. _ensureContainer(elid);
  4943. var _def = {
  4944. def:root.jsPlumb.extend({}, p),
  4945. uniqueEndpoint: p.uniqueEndpoint,
  4946. maxConnections: maxConnections,
  4947. enabled: true
  4948. };
  4949. if (p.createEndpoint) {
  4950. _def.uniqueEndpoint = true;
  4951. _def.endpoint = _currentInstance.addEndpoint(el, _def.def);
  4952. _def.endpoint.setDeleteOnEmpty(false);
  4953. }
  4954. this.sourceEndpointDefinitions[elid][type] = _def;
  4955. elInfo.def = _def;
  4956. var stopEvent = root.jsPlumb.dragEvents.stop,
  4957. dragEvent = root.jsPlumb.dragEvents.drag,
  4958. dragOptions = root.jsPlumb.extend({ }, p.dragOptions || {}),
  4959. existingDrag = dragOptions.drag,
  4960. existingStop = dragOptions.stop,
  4961. ep = null,
  4962. endpointAddedButNoDragYet = false;
  4963. // set scope if its not set in dragOptions but was passed in in params
  4964. dragOptions.scope = dragOptions.scope || p.scope;
  4965. dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], function () {
  4966. if (existingDrag) {
  4967. existingDrag.apply(this, arguments);
  4968. }
  4969. endpointAddedButNoDragYet = false;
  4970. });
  4971. dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], function () {
  4972. if (existingStop) {
  4973. existingStop.apply(this, arguments);
  4974. }
  4975. this.currentlyDragging = false;
  4976. if (ep._jsPlumb != null) { // if not cleaned up...
  4977. // reset the anchor to the anchor that was initially provided. the one we were using to drag
  4978. // the connection was just a placeholder that was located at the place the user pressed the
  4979. // mouse button to initiate the drag.
  4980. var anchorDef = p.anchor || this.Defaults.Anchor,
  4981. oldAnchor = ep.anchor,
  4982. oldConnection = ep.connections[0];
  4983. var newAnchor = this.makeAnchor(anchorDef, elid, this),
  4984. _el = ep.element;
  4985. // if the anchor has a 'positionFinder' set, then delegate to that function to find
  4986. // out where to locate the anchor. issue 117.
  4987. if (newAnchor.positionFinder != null) {
  4988. var elPosition = _currentInstance.getOffset(_el),
  4989. elSize = this.getSize(_el),
  4990. dropPosition = { left: elPosition.left + (oldAnchor.x * elSize[0]), top: elPosition.top + (oldAnchor.y * elSize[1]) },
  4991. ap = newAnchor.positionFinder(dropPosition, elPosition, elSize, newAnchor.constructorParams);
  4992. newAnchor.x = ap[0];
  4993. newAnchor.y = ap[1];
  4994. }
  4995. ep.setAnchor(newAnchor, true);
  4996. ep.repaint();
  4997. this.repaint(ep.elementId);
  4998. if (oldConnection != null) {
  4999. this.repaint(oldConnection.targetId);
  5000. }
  5001. }
  5002. }.bind(this));
  5003. // when the user presses the mouse, add an Endpoint, if we are enabled.
  5004. var mouseDownListener = function (e) {
  5005. // on right mouse button, abort.
  5006. if (e.which === 3 || e.button === 2) {
  5007. return;
  5008. }
  5009. // TODO store def on element.
  5010. var def = this.sourceEndpointDefinitions[elid][type];
  5011. // if disabled, return.
  5012. if (!def.enabled) {
  5013. return;
  5014. }
  5015. elid = this.getId(this.getElement(elInfo.el)); // elid might have changed since this method was called to configure the element.
  5016. // if a filter was given, run it, and return if it says no.
  5017. if (p.filter) {
  5018. var r = _ju.isString(p.filter) ? selectorFilter(e, elInfo.el, p.filter, this, p.filterExclude) : p.filter(e, elInfo.el);
  5019. if (r === false) {
  5020. return;
  5021. }
  5022. }
  5023. // if maxConnections reached
  5024. var sourceCount = this.select({source: elid}).length;
  5025. if (def.maxConnections >= 0 && (sourceCount >= def.maxConnections)) {
  5026. if (onMaxConnections) {
  5027. onMaxConnections({
  5028. element: elInfo.el,
  5029. maxConnections: maxConnections
  5030. }, e);
  5031. }
  5032. return false;
  5033. }
  5034. // find the position on the element at which the mouse was pressed; this is where the endpoint
  5035. // will be located.
  5036. var elxy = root.jsPlumb.getPositionOnElement(e, _del, _zoom);
  5037. // we need to override the anchor in here, and force 'isSource', but we don't want to mess with
  5038. // the params passed in, because after a connection is established we're going to reset the endpoint
  5039. // to have the anchor we were given.
  5040. var tempEndpointParams = {};
  5041. root.jsPlumb.extend(tempEndpointParams, p);
  5042. tempEndpointParams.isTemporarySource = true;
  5043. tempEndpointParams.anchor = [ elxy[0], elxy[1] , 0, 0];
  5044. tempEndpointParams.dragOptions = dragOptions;
  5045. if (def.def.scope) {
  5046. tempEndpointParams.scope = def.def.scope;
  5047. }
  5048. ep = this.addEndpoint(elid, tempEndpointParams);
  5049. endpointAddedButNoDragYet = true;
  5050. ep.setDeleteOnEmpty(true);
  5051. // if unique endpoint and it's already been created, push it onto the endpoint we create. at the end
  5052. // of a successful connection we'll switch to that endpoint.
  5053. // TODO this is the same code as the programmatic endpoints create on line 1050 ish
  5054. if (def.uniqueEndpoint) {
  5055. if (!def.endpoint) {
  5056. def.endpoint = ep;
  5057. ep.setDeleteOnEmpty(false);
  5058. }
  5059. else {
  5060. ep.finalEndpoint = def.endpoint;
  5061. }
  5062. }
  5063. var _delTempEndpoint = function () {
  5064. // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools
  5065. // it is fired even if dragging has occurred, in which case we would blow away a perfectly
  5066. // legitimate endpoint, were it not for this check. the flag is set after adding an
  5067. // endpoint and cleared in a drag listener we set in the dragOptions above.
  5068. _currentInstance.off(ep.canvas, "mouseup", _delTempEndpoint);
  5069. _currentInstance.off(elInfo.el, "mouseup", _delTempEndpoint);
  5070. if (endpointAddedButNoDragYet) {
  5071. endpointAddedButNoDragYet = false;
  5072. _currentInstance.deleteEndpoint(ep);
  5073. }
  5074. };
  5075. _currentInstance.on(ep.canvas, "mouseup", _delTempEndpoint);
  5076. _currentInstance.on(elInfo.el, "mouseup", _delTempEndpoint);
  5077. // optionally check for attributes to extract from the source element
  5078. var payload = {};
  5079. if (def.def.extract) {
  5080. for (var att in def.def.extract) {
  5081. var v = (e.srcElement || e.target).getAttribute(att);
  5082. if (v) {
  5083. payload[def.def.extract[att]] = v;
  5084. }
  5085. }
  5086. }
  5087. // and then trigger its mousedown event, which will kick off a drag, which will start dragging
  5088. // a new connection from this endpoint.
  5089. _currentInstance.trigger(ep.canvas, "mousedown", e, payload);
  5090. _ju.consume(e);
  5091. }.bind(this);
  5092. this.on(elInfo.el, "mousedown", mouseDownListener);
  5093. _def.trigger = mouseDownListener;
  5094. // if a filter was provided, set it as a dragFilter on the element,
  5095. // to prevent the element drag function from kicking in when we want to
  5096. // drag a new connection
  5097. if (p.filter && (_ju.isString(p.filter) || _ju.isFunction(p.filter))) {
  5098. _currentInstance.setDragFilter(elInfo.el, p.filter);
  5099. }
  5100. var dropOptions = root.jsPlumb.extend({}, p.dropOptions || {});
  5101. _makeElementDropHandler(elInfo, p, dropOptions, true, p.isTarget === true);
  5102. }.bind(this);
  5103. var inputs = el.length && el.constructor !== String ? el : [ el ];
  5104. for (var i = 0, ii = inputs.length; i < ii; i++) {
  5105. _doOne(_info(inputs[i]));
  5106. }
  5107. return this;
  5108. };
  5109. // see api docs
  5110. this.unmakeSource = function (el, connectionType, doNotClearArrays) {
  5111. var info = _info(el);
  5112. _currentInstance.destroyDroppable(info.el, "internal");
  5113. var eldefs = this.sourceEndpointDefinitions[info.id];
  5114. if (eldefs) {
  5115. for (var def in eldefs) {
  5116. if (connectionType == null || connectionType === def) {
  5117. var mouseDownListener = eldefs[def].trigger;
  5118. if (mouseDownListener) {
  5119. _currentInstance.off(info.el, "mousedown", mouseDownListener);
  5120. }
  5121. if (!doNotClearArrays) {
  5122. delete this.sourceEndpointDefinitions[info.id][def];
  5123. }
  5124. }
  5125. }
  5126. }
  5127. return this;
  5128. };
  5129. // see api docs
  5130. this.unmakeEverySource = function () {
  5131. for (var i in this.sourceEndpointDefinitions) {
  5132. _currentInstance.unmakeSource(i, null, true);
  5133. }
  5134. this.sourceEndpointDefinitions = {};
  5135. return this;
  5136. };
  5137. var _getScope = function (el, types, connectionType) {
  5138. types = _ju.isArray(types) ? types : [ types ];
  5139. var id = _getId(el);
  5140. connectionType = connectionType || "default";
  5141. for (var i = 0; i < types.length; i++) {
  5142. var eldefs = this[types[i]][id];
  5143. if (eldefs && eldefs[connectionType]) {
  5144. return eldefs[connectionType].def.scope || this.Defaults.Scope;
  5145. }
  5146. }
  5147. }.bind(this);
  5148. var _setScope = function (el, scope, types, connectionType) {
  5149. types = _ju.isArray(types) ? types : [ types ];
  5150. var id = _getId(el);
  5151. connectionType = connectionType || "default";
  5152. for (var i = 0; i < types.length; i++) {
  5153. var eldefs = this[types[i]][id];
  5154. if (eldefs && eldefs[connectionType]) {
  5155. eldefs[connectionType].def.scope = scope;
  5156. }
  5157. }
  5158. }.bind(this);
  5159. this.getScope = function (el, scope) {
  5160. return _getScope(el, [ "sourceEndpointDefinitions", "targetEndpointDefinitions" ]);
  5161. };
  5162. this.getSourceScope = function (el) {
  5163. return _getScope(el, "sourceEndpointDefinitions");
  5164. };
  5165. this.getTargetScope = function (el) {
  5166. return _getScope(el, "targetEndpointDefinitions");
  5167. };
  5168. this.setScope = function (el, scope, connectionType) {
  5169. this.setSourceScope(el, scope, connectionType);
  5170. this.setTargetScope(el, scope, connectionType);
  5171. };
  5172. this.setSourceScope = function (el, scope, connectionType) {
  5173. _setScope(el, scope, "sourceEndpointDefinitions", connectionType);
  5174. // we get the source scope during the mousedown event, but we also want to set this.
  5175. this.setDragScope(el, scope);
  5176. };
  5177. this.setTargetScope = function (el, scope, connectionType) {
  5178. _setScope(el, scope, "targetEndpointDefinitions", connectionType);
  5179. this.setDropScope(el, scope);
  5180. };
  5181. // see api docs
  5182. this.unmakeEveryTarget = function () {
  5183. for (var i in this.targetEndpointDefinitions) {
  5184. _currentInstance.unmakeTarget(i, true);
  5185. }
  5186. this.targetEndpointDefinitions = {};
  5187. return this;
  5188. };
  5189. // does the work of setting a source enabled or disabled.
  5190. var _setEnabled = function (type, el, state, toggle, connectionType) {
  5191. var a = type === "source" ? this.sourceEndpointDefinitions : this.targetEndpointDefinitions,
  5192. originalState, info, newState;
  5193. connectionType = connectionType || "default";
  5194. // a selector or an array
  5195. if (el.length && !_ju.isString(el)) {
  5196. originalState = [];
  5197. for (var i = 0, ii = el.length; i < ii; i++) {
  5198. info = _info(el[i]);
  5199. if (a[info.id] && a[info.id][connectionType]) {
  5200. originalState[i] = a[info.id][connectionType].enabled;
  5201. newState = toggle ? !originalState[i] : state;
  5202. a[info.id][connectionType].enabled = newState;
  5203. _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
  5204. }
  5205. }
  5206. }
  5207. // otherwise a DOM element or a String ID.
  5208. else {
  5209. info = _info(el);
  5210. var id = info.id;
  5211. if (a[id] && a[id][connectionType]) {
  5212. originalState = a[id][connectionType].enabled;
  5213. newState = toggle ? !originalState : state;
  5214. a[id][connectionType].enabled = newState;
  5215. _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
  5216. }
  5217. }
  5218. return originalState;
  5219. }.bind(this);
  5220. var _first = function (el, fn) {
  5221. if (_ju.isString(el) || !el.length) {
  5222. return fn.apply(this, [ el ]);
  5223. }
  5224. else if (el.length) {
  5225. return fn.apply(this, [ el[0] ]);
  5226. }
  5227. }.bind(this);
  5228. this.toggleSourceEnabled = function (el, connectionType) {
  5229. _setEnabled("source", el, null, true, connectionType);
  5230. return this.isSourceEnabled(el, connectionType);
  5231. };
  5232. this.setSourceEnabled = function (el, state, connectionType) {
  5233. return _setEnabled("source", el, state, null, connectionType);
  5234. };
  5235. this.isSource = function (el, connectionType) {
  5236. connectionType = connectionType || "default";
  5237. return _first(el, function (_el) {
  5238. var eldefs = this.sourceEndpointDefinitions[_info(_el).id];
  5239. return eldefs != null && eldefs[connectionType] != null;
  5240. }.bind(this));
  5241. };
  5242. this.isSourceEnabled = function (el, connectionType) {
  5243. connectionType = connectionType || "default";
  5244. return _first(el, function (_el) {
  5245. var sep = this.sourceEndpointDefinitions[_info(_el).id];
  5246. return sep && sep[connectionType] && sep[connectionType].enabled === true;
  5247. }.bind(this));
  5248. };
  5249. this.toggleTargetEnabled = function (el, connectionType) {
  5250. _setEnabled("target", el, null, true, connectionType);
  5251. return this.isTargetEnabled(el, connectionType);
  5252. };
  5253. this.isTarget = function (el, connectionType) {
  5254. connectionType = connectionType || "default";
  5255. return _first(el, function (_el) {
  5256. var eldefs = this.targetEndpointDefinitions[_info(_el).id];
  5257. return eldefs != null && eldefs[connectionType] != null;
  5258. }.bind(this));
  5259. };
  5260. this.isTargetEnabled = function (el, connectionType) {
  5261. connectionType = connectionType || "default";
  5262. return _first(el, function (_el) {
  5263. var tep = this.targetEndpointDefinitions[_info(_el).id];
  5264. return tep && tep[connectionType] && tep[connectionType].enabled === true;
  5265. }.bind(this));
  5266. };
  5267. this.setTargetEnabled = function (el, state, connectionType) {
  5268. return _setEnabled("target", el, state, null, connectionType);
  5269. };
  5270. // --------------------- end makeSource/makeTarget ----------------------------------------------
  5271. this.ready = function (fn) {
  5272. _currentInstance.bind("ready", fn);
  5273. };
  5274. var _elEach = function(el, fn) {
  5275. // support both lists...
  5276. if (typeof el === 'object' && el.length) {
  5277. for (var i = 0, ii = el.length; i < ii; i++) {
  5278. fn(el[i]);
  5279. }
  5280. }
  5281. else {// ...and single strings or elements.
  5282. fn(el);
  5283. }
  5284. return _currentInstance;
  5285. };
  5286. // repaint some element's endpoints and connections
  5287. this.repaint = function (el, ui, timestamp) {
  5288. return _elEach(el, function(_el) {
  5289. _draw(_el, ui, timestamp);
  5290. });
  5291. };
  5292. this.revalidate = function (el, timestamp, isIdAlready) {
  5293. return _elEach(el, function(_el) {
  5294. var elId = isIdAlready ? _el : _currentInstance.getId(_el);
  5295. _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp:timestamp });
  5296. var dm = _currentInstance.getDragManager();
  5297. if (dm) {
  5298. dm.updateOffsets(elId);
  5299. }
  5300. _currentInstance.repaint(_el);
  5301. });
  5302. };
  5303. // repaint every endpoint and connection.
  5304. this.repaintEverything = function () {
  5305. // TODO this timestamp causes continuous anchors to not repaint properly.
  5306. // fix this. do not just take out the timestamp. it runs a lot faster with
  5307. // the timestamp included.
  5308. var timestamp = _timestamp(), elId;
  5309. for (elId in endpointsByElement) {
  5310. _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp: timestamp });
  5311. }
  5312. for (elId in endpointsByElement) {
  5313. _draw(elId, null, timestamp);
  5314. }
  5315. return this;
  5316. };
  5317. this.removeAllEndpoints = function (el, recurse, affectedElements) {
  5318. affectedElements = affectedElements || [];
  5319. var _one = function (_el) {
  5320. var info = _info(_el),
  5321. ebe = endpointsByElement[info.id],
  5322. i, ii;
  5323. if (ebe) {
  5324. affectedElements.push(info);
  5325. for (i = 0, ii = ebe.length; i < ii; i++) {
  5326. _currentInstance.deleteEndpoint(ebe[i], false);
  5327. }
  5328. }
  5329. delete endpointsByElement[info.id];
  5330. if (recurse) {
  5331. if (info.el && info.el.nodeType !== 3 && info.el.nodeType !== 8) {
  5332. for (i = 0, ii = info.el.childNodes.length; i < ii; i++) {
  5333. _one(info.el.childNodes[i]);
  5334. }
  5335. }
  5336. }
  5337. };
  5338. _one(el);
  5339. return this;
  5340. };
  5341. var _doRemove = function(info, affectedElements) {
  5342. _currentInstance.removeAllEndpoints(info.id, true, affectedElements);
  5343. var dm = _currentInstance.getDragManager();
  5344. var _one = function(_info) {
  5345. if (dm) {
  5346. dm.elementRemoved(_info.id);
  5347. }
  5348. _currentInstance.anchorManager.clearFor(_info.id);
  5349. _currentInstance.anchorManager.removeFloatingConnection(_info.id);
  5350. if (_currentInstance.isSource(_info.el)) {
  5351. _currentInstance.unmakeSource(_info.el);
  5352. }
  5353. if (_currentInstance.isTarget(_info.el)) {
  5354. _currentInstance.unmakeTarget(_info.el);
  5355. }
  5356. _currentInstance.destroyDraggable(_info.el);
  5357. _currentInstance.destroyDroppable(_info.el);
  5358. delete _currentInstance.floatingConnections[_info.id];
  5359. delete managedElements[_info.id];
  5360. delete offsets[_info.id];
  5361. if (_info.el) {
  5362. _currentInstance.removeElement(_info.el);
  5363. _info.el._jsPlumb = null;
  5364. }
  5365. };
  5366. // remove all affected child elements
  5367. for (var ae = 1; ae < affectedElements.length; ae++) {
  5368. _one(affectedElements[ae]);
  5369. }
  5370. // and always remove the requested one from the dom.
  5371. _one(info);
  5372. };
  5373. /**
  5374. * Remove the given element, including cleaning up all endpoints registered for it.
  5375. * This is exposed in the public API but also used internally by jsPlumb when removing the
  5376. * element associated with a connection drag.
  5377. */
  5378. this.remove = function (el, doNotRepaint) {
  5379. var info = _info(el), affectedElements = [];
  5380. if (info.text) {
  5381. info.el.parentNode.removeChild(info.el);
  5382. }
  5383. else if (info.id) {
  5384. _currentInstance.batch(function () {
  5385. _doRemove(info, affectedElements);
  5386. }, doNotRepaint === false);
  5387. }
  5388. return _currentInstance;
  5389. };
  5390. this.empty = function (el, doNotRepaint) {
  5391. var affectedElements = [];
  5392. var _one = function(el, dontRemoveFocus) {
  5393. var info = _info(el);
  5394. if (info.text) {
  5395. info.el.parentNode.removeChild(info.el);
  5396. }
  5397. else if (info.el) {
  5398. while(info.el.childNodes.length > 0) {
  5399. _one(info.el.childNodes[0]);
  5400. }
  5401. if (!dontRemoveFocus) {
  5402. _doRemove(info, affectedElements);
  5403. }
  5404. }
  5405. };
  5406. _currentInstance.batch(function() {
  5407. _one(el, true);
  5408. }, doNotRepaint === false);
  5409. return _currentInstance;
  5410. };
  5411. this.reset = function (doNotUnbindInstanceEventListeners) {
  5412. _currentInstance.silently(function() {
  5413. _hoverSuspended = false;
  5414. _currentInstance.removeAllGroups();
  5415. _currentInstance.removeGroupManager();
  5416. _currentInstance.deleteEveryEndpoint();
  5417. if (!doNotUnbindInstanceEventListeners) {
  5418. _currentInstance.unbind();
  5419. }
  5420. this.targetEndpointDefinitions = {};
  5421. this.sourceEndpointDefinitions = {};
  5422. connections.length = 0;
  5423. if (this.doReset) {
  5424. this.doReset();
  5425. }
  5426. }.bind(this));
  5427. };
  5428. var _clearObject = function (obj) {
  5429. if (obj.canvas && obj.canvas.parentNode) {
  5430. obj.canvas.parentNode.removeChild(obj.canvas);
  5431. }
  5432. obj.cleanup();
  5433. obj.destroy();
  5434. };
  5435. this.clear = function () {
  5436. _currentInstance.select().each(_clearObject);
  5437. _currentInstance.selectEndpoints().each(_clearObject);
  5438. endpointsByElement = {};
  5439. endpointsByUUID = {};
  5440. };
  5441. this.setDefaultScope = function (scope) {
  5442. DEFAULT_SCOPE = scope;
  5443. return _currentInstance;
  5444. };
  5445. // sets whether or not some element should be currently draggable.
  5446. this.setDraggable = _setDraggable;
  5447. this.deriveEndpointAndAnchorSpec = function(type, dontPrependDefault) {
  5448. var bits = ((dontPrependDefault ? "" : "default ") + type).split(/[\s]/), eps = null, ep = null, a = null, as = null;
  5449. for (var i = 0; i < bits.length; i++) {
  5450. var _t = _currentInstance.getType(bits[i], "connection");
  5451. if (_t) {
  5452. if (_t.endpoints) {
  5453. eps = _t.endpoints;
  5454. }
  5455. if (_t.endpoint) {
  5456. ep = _t.endpoint;
  5457. }
  5458. if (_t.anchors) {
  5459. as = _t.anchors;
  5460. }
  5461. if (_t.anchor) {
  5462. a = _t.anchor;
  5463. }
  5464. }
  5465. }
  5466. return { endpoints: eps ? eps : [ ep, ep ], anchors: as ? as : [a, a ]};
  5467. };
  5468. // sets the id of some element, changing whatever we need to to keep track.
  5469. this.setId = function (el, newId, doNotSetAttribute) {
  5470. //
  5471. var id;
  5472. if (_ju.isString(el)) {
  5473. id = el;
  5474. }
  5475. else {
  5476. el = this.getElement(el);
  5477. id = this.getId(el);
  5478. }
  5479. var sConns = this.getConnections({source: id, scope: '*'}, true),
  5480. tConns = this.getConnections({target: id, scope: '*'}, true);
  5481. newId = "" + newId;
  5482. if (!doNotSetAttribute) {
  5483. el = this.getElement(id);
  5484. this.setAttribute(el, "id", newId);
  5485. }
  5486. else {
  5487. el = this.getElement(newId);
  5488. }
  5489. endpointsByElement[newId] = endpointsByElement[id] || [];
  5490. for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) {
  5491. endpointsByElement[newId][i].setElementId(newId);
  5492. endpointsByElement[newId][i].setReferenceElement(el);
  5493. }
  5494. delete endpointsByElement[id];
  5495. this.sourceEndpointDefinitions[newId] = this.sourceEndpointDefinitions[id];
  5496. delete this.sourceEndpointDefinitions[id];
  5497. this.targetEndpointDefinitions[newId] = this.targetEndpointDefinitions[id];
  5498. delete this.targetEndpointDefinitions[id];
  5499. this.anchorManager.changeId(id, newId);
  5500. var dm = this.getDragManager();
  5501. if (dm) {
  5502. dm.changeId(id, newId);
  5503. }
  5504. managedElements[newId] = managedElements[id];
  5505. delete managedElements[id];
  5506. var _conns = function (list, epIdx, type) {
  5507. for (var i = 0, ii = list.length; i < ii; i++) {
  5508. list[i].endpoints[epIdx].setElementId(newId);
  5509. list[i].endpoints[epIdx].setReferenceElement(el);
  5510. list[i][type + "Id"] = newId;
  5511. list[i][type] = el;
  5512. }
  5513. };
  5514. _conns(sConns, 0, "source");
  5515. _conns(tConns, 1, "target");
  5516. this.repaint(newId);
  5517. };
  5518. this.setDebugLog = function (debugLog) {
  5519. log = debugLog;
  5520. };
  5521. this.setSuspendDrawing = function (val, repaintAfterwards) {
  5522. var curVal = _suspendDrawing;
  5523. _suspendDrawing = val;
  5524. if (val) {
  5525. _suspendedAt = new Date().getTime();
  5526. } else {
  5527. _suspendedAt = null;
  5528. }
  5529. if (repaintAfterwards) {
  5530. this.repaintEverything();
  5531. }
  5532. return curVal;
  5533. };
  5534. // returns whether or not drawing is currently suspended.
  5535. this.isSuspendDrawing = function () {
  5536. return _suspendDrawing;
  5537. };
  5538. // return timestamp for when drawing was suspended.
  5539. this.getSuspendedAt = function () {
  5540. return _suspendedAt;
  5541. };
  5542. this.batch = function (fn, doNotRepaintAfterwards) {
  5543. var _wasSuspended = this.isSuspendDrawing();
  5544. if (!_wasSuspended) {
  5545. this.setSuspendDrawing(true);
  5546. }
  5547. try {
  5548. fn();
  5549. }
  5550. catch (e) {
  5551. _ju.log("Function run while suspended failed", e);
  5552. }
  5553. if (!_wasSuspended) {
  5554. this.setSuspendDrawing(false, !doNotRepaintAfterwards);
  5555. }
  5556. };
  5557. this.doWhileSuspended = this.batch;
  5558. this.getCachedData = _getCachedData;
  5559. this.timestamp = _timestamp;
  5560. this.show = function (el, changeEndpoints) {
  5561. _setVisible(el, "block", changeEndpoints);
  5562. return _currentInstance;
  5563. };
  5564. // TODO: update this method to return the current state.
  5565. this.toggleVisible = _toggleVisible;
  5566. this.toggleDraggable = _toggleDraggable;
  5567. this.addListener = this.bind;
  5568. var floatingConnections = [];
  5569. this.registerFloatingConnection = function(info, conn, ep) {
  5570. floatingConnections[info.id] = conn;
  5571. // only register for the target endpoint; we will not be dragging the source at any time
  5572. // before this connection is either discarded or made into a permanent connection.
  5573. _ju.addToList(endpointsByElement, info.id, ep);
  5574. };
  5575. this.getFloatingConnectionFor = function(id) {
  5576. return floatingConnections[id];
  5577. };
  5578. };
  5579. _ju.extend(root.jsPlumbInstance, _ju.EventGenerator, {
  5580. setAttribute: function (el, a, v) {
  5581. this.setAttribute(el, a, v);
  5582. },
  5583. getAttribute: function (el, a) {
  5584. return this.getAttribute(root.jsPlumb.getElement(el), a);
  5585. },
  5586. convertToFullOverlaySpec: function(spec) {
  5587. if (_ju.isString(spec)) {
  5588. spec = [ spec, { } ];
  5589. }
  5590. spec[1].id = spec[1].id || _ju.uuid();
  5591. return spec;
  5592. },
  5593. registerConnectionType: function (id, type) {
  5594. this._connectionTypes[id] = root.jsPlumb.extend({}, type);
  5595. if (type.overlays) {
  5596. var to = {};
  5597. for (var i = 0; i < type.overlays.length; i++) {
  5598. // if a string, convert to object representation so that we can store the typeid on it.
  5599. // also assign an id.
  5600. var fo = this.convertToFullOverlaySpec(type.overlays[i]);
  5601. to[fo[1].id] = fo;
  5602. }
  5603. this._connectionTypes[id].overlays = to;
  5604. }
  5605. },
  5606. registerConnectionTypes: function (types) {
  5607. for (var i in types) {
  5608. this.registerConnectionType(i, types[i]);
  5609. }
  5610. },
  5611. registerEndpointType: function (id, type) {
  5612. this._endpointTypes[id] = root.jsPlumb.extend({}, type);
  5613. if (type.overlays) {
  5614. var to = {};
  5615. for (var i = 0; i < type.overlays.length; i++) {
  5616. // if a string, convert to object representation so that we can store the typeid on it.
  5617. // also assign an id.
  5618. var fo = this.convertToFullOverlaySpec(type.overlays[i]);
  5619. to[fo[1].id] = fo;
  5620. }
  5621. this._endpointTypes[id].overlays = to;
  5622. }
  5623. },
  5624. registerEndpointTypes: function (types) {
  5625. for (var i in types) {
  5626. this.registerEndpointType(i, types[i]);
  5627. }
  5628. },
  5629. getType: function (id, typeDescriptor) {
  5630. return typeDescriptor === "connection" ? this._connectionTypes[id] : this._endpointTypes[id];
  5631. },
  5632. setIdChanged: function (oldId, newId) {
  5633. this.setId(oldId, newId, true);
  5634. },
  5635. // set parent: change the parent for some node and update all the registrations we need to.
  5636. setParent: function (el, newParent) {
  5637. var _dom = this.getElement(el),
  5638. _id = this.getId(_dom),
  5639. _pdom = this.getElement(newParent),
  5640. _pid = this.getId(_pdom),
  5641. dm = this.getDragManager();
  5642. _dom.parentNode.removeChild(_dom);
  5643. _pdom.appendChild(_dom);
  5644. if (dm) {
  5645. dm.setParent(_dom, _id, _pdom, _pid);
  5646. }
  5647. },
  5648. extend: function (o1, o2, names) {
  5649. var i;
  5650. if (names) {
  5651. for (i = 0; i < names.length; i++) {
  5652. o1[names[i]] = o2[names[i]];
  5653. }
  5654. }
  5655. else {
  5656. for (i in o2) {
  5657. o1[i] = o2[i];
  5658. }
  5659. }
  5660. return o1;
  5661. },
  5662. floatingConnections: {},
  5663. getFloatingAnchorIndex: function (jpc) {
  5664. return jpc.endpoints[0].isFloating() ? 0 : jpc.endpoints[1].isFloating() ? 1 : -1;
  5665. }
  5666. });
  5667. jsPlumbInstance.prototype.Defaults = {
  5668. Anchor: "Bottom",
  5669. Anchors: [ null, null ],
  5670. ConnectionsDetachable: true,
  5671. ConnectionOverlays: [ ],
  5672. Connector: "Bezier",
  5673. Container: null,
  5674. DoNotThrowErrors: false,
  5675. DragOptions: { },
  5676. DropOptions: { },
  5677. Endpoint: "Dot",
  5678. EndpointOverlays: [ ],
  5679. Endpoints: [ null, null ],
  5680. EndpointStyle: { fill: "#456" },
  5681. EndpointStyles: [ null, null ],
  5682. EndpointHoverStyle: null,
  5683. EndpointHoverStyles: [ null, null ],
  5684. HoverPaintStyle: null,
  5685. LabelStyle: { color: "black" },
  5686. LogEnabled: false,
  5687. Overlays: [ ],
  5688. MaxConnections: 1,
  5689. PaintStyle: { "stroke-width": 4, stroke: "#456" },
  5690. ReattachConnections: false,
  5691. RenderMode: "svg",
  5692. Scope: "jsPlumb_DefaultScope"
  5693. };
  5694. // --------------------- static instance + module registration -------------------------------------------
  5695. // create static instance and assign to window if window exists.
  5696. var jsPlumb = new jsPlumbInstance();
  5697. // register on 'root' (lets us run on server or browser)
  5698. root.jsPlumb = jsPlumb;
  5699. // add 'getInstance' method to static instance
  5700. jsPlumb.getInstance = function (_defaults, overrideFns) {
  5701. var j = new jsPlumbInstance(_defaults);
  5702. if (overrideFns) {
  5703. for (var ovf in overrideFns) {
  5704. j[ovf] = overrideFns[ovf];
  5705. }
  5706. }
  5707. j.init();
  5708. return j;
  5709. };
  5710. jsPlumb.each = function (spec, fn) {
  5711. if (spec == null) {
  5712. return;
  5713. }
  5714. if (typeof spec === "string") {
  5715. fn(jsPlumb.getElement(spec));
  5716. }
  5717. else if (spec.length != null) {
  5718. for (var i = 0; i < spec.length; i++) {
  5719. fn(jsPlumb.getElement(spec[i]));
  5720. }
  5721. }
  5722. else {
  5723. fn(spec);
  5724. } // assume it's an element.
  5725. };
  5726. // CommonJS
  5727. if (typeof exports !== 'undefined') {
  5728. exports.jsPlumb = jsPlumb;
  5729. }
  5730. // --------------------- end static instance + AMD registration -------------------------------------------
  5731. }).call(typeof window !== 'undefined' ? window : this);
  5732. /*
  5733. * This file contains the base functionality for DOM type adapters.
  5734. *
  5735. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  5736. *
  5737. * https://jsplumbtoolkit.com
  5738. * https://github.com/jsplumb/jsplumb
  5739. *
  5740. * Dual licensed under the MIT and GPL2 licenses.
  5741. */
  5742. ;
  5743. (function () {
  5744. var root = this, _ju = root.jsPlumbUtil;
  5745. var _genLoc = function (prefix, e) {
  5746. if (e == null) {
  5747. return [ 0, 0 ];
  5748. }
  5749. var ts = _touches(e), t = _getTouch(ts, 0);
  5750. return [t[prefix + "X"], t[prefix + "Y"]];
  5751. },
  5752. _pageLocation = _genLoc.bind(this, "page"),
  5753. _screenLocation = _genLoc.bind(this, "screen"),
  5754. _clientLocation = _genLoc.bind(this, "client"),
  5755. _getTouch = function (touches, idx) {
  5756. return touches.item ? touches.item(idx) : touches[idx];
  5757. },
  5758. _touches = function (e) {
  5759. return e.touches && e.touches.length > 0 ? e.touches :
  5760. e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
  5761. e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
  5762. [ e ];
  5763. };
  5764. /**
  5765. Manages dragging for some instance of jsPlumb.
  5766. TODO instead of this being accessed directly, it should subscribe to events on the jsPlumb instance: every method
  5767. in here is called directly by jsPlumb. But what should happen is that we have unpublished events that this listens
  5768. to. The only trick is getting one of these instantiated with every jsPlumb instance: it needs to have a hook somehow.
  5769. Basically the general idea is to pull ALL the drag code out (prototype method registrations plus this) into a
  5770. dedicated drag script), that does not necessarily need to be included.
  5771. */
  5772. var DragManager = function (_currentInstance) {
  5773. var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {},
  5774. // elementids mapped to the draggable to which they belong.
  5775. _draggablesForElements = {};
  5776. /**
  5777. register some element as draggable. right now the drag init stuff is done elsewhere, and it is
  5778. possible that will continue to be the case.
  5779. */
  5780. this.register = function (el) {
  5781. var id = _currentInstance.getId(el),
  5782. parentOffset = _currentInstance.getOffset(el);
  5783. if (!_draggables[id]) {
  5784. _draggables[id] = el;
  5785. _dlist.push(el);
  5786. _delements[id] = {};
  5787. }
  5788. // look for child elements that have endpoints and register them against this draggable.
  5789. var _oneLevel = function (p) {
  5790. if (p) {
  5791. for (var i = 0; i < p.childNodes.length; i++) {
  5792. if (p.childNodes[i].nodeType !== 3 && p.childNodes[i].nodeType !== 8) {
  5793. var cEl = jsPlumb.getElement(p.childNodes[i]),
  5794. cid = _currentInstance.getId(p.childNodes[i], null, true);
  5795. if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) {
  5796. var cOff = _currentInstance.getOffset(cEl);
  5797. _delements[id][cid] = {
  5798. id: cid,
  5799. offset: {
  5800. left: cOff.left - parentOffset.left,
  5801. top: cOff.top - parentOffset.top
  5802. }
  5803. };
  5804. _draggablesForElements[cid] = id;
  5805. }
  5806. _oneLevel(p.childNodes[i]);
  5807. }
  5808. }
  5809. }
  5810. };
  5811. _oneLevel(el);
  5812. };
  5813. // refresh the offsets for child elements of this element.
  5814. this.updateOffsets = function (elId, childOffsetOverrides) {
  5815. if (elId != null) {
  5816. childOffsetOverrides = childOffsetOverrides || {};
  5817. var domEl = jsPlumb.getElement(elId),
  5818. id = _currentInstance.getId(domEl),
  5819. children = _delements[id],
  5820. parentOffset = _currentInstance.getOffset(domEl);
  5821. if (children) {
  5822. for (var i in children) {
  5823. if (children.hasOwnProperty(i)) {
  5824. var cel = jsPlumb.getElement(i),
  5825. cOff = childOffsetOverrides[i] || _currentInstance.getOffset(cel);
  5826. // do not update if we have a value already and we'd just be writing 0,0
  5827. if (cel.offsetParent == null && _delements[id][i] != null) {
  5828. continue;
  5829. }
  5830. _delements[id][i] = {
  5831. id: i,
  5832. offset: {
  5833. left: cOff.left - parentOffset.left,
  5834. top: cOff.top - parentOffset.top
  5835. }
  5836. };
  5837. _draggablesForElements[i] = id;
  5838. }
  5839. }
  5840. }
  5841. }
  5842. };
  5843. /**
  5844. notification that an endpoint was added to the given el. we go up from that el's parent
  5845. node, looking for a parent that has been registered as a draggable. if we find one, we add this
  5846. el to that parent's list of elements to update on drag (if it is not there already)
  5847. */
  5848. this.endpointAdded = function (el, id) {
  5849. id = id || _currentInstance.getId(el);
  5850. var b = document.body,
  5851. p = el.parentNode;
  5852. _elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1;
  5853. while (p != null && p !== b) {
  5854. var pid = _currentInstance.getId(p, null, true);
  5855. if (pid && _draggables[pid]) {
  5856. var pLoc = _currentInstance.getOffset(p);
  5857. if (_delements[pid][id] == null) {
  5858. var cLoc = _currentInstance.getOffset(el);
  5859. _delements[pid][id] = {
  5860. id: id,
  5861. offset: {
  5862. left: cLoc.left - pLoc.left,
  5863. top: cLoc.top - pLoc.top
  5864. }
  5865. };
  5866. _draggablesForElements[id] = pid;
  5867. }
  5868. break;
  5869. }
  5870. p = p.parentNode;
  5871. }
  5872. };
  5873. this.endpointDeleted = function (endpoint) {
  5874. if (_elementsWithEndpoints[endpoint.elementId]) {
  5875. _elementsWithEndpoints[endpoint.elementId]--;
  5876. if (_elementsWithEndpoints[endpoint.elementId] <= 0) {
  5877. for (var i in _delements) {
  5878. if (_delements.hasOwnProperty(i) && _delements[i]) {
  5879. delete _delements[i][endpoint.elementId];
  5880. delete _draggablesForElements[endpoint.elementId];
  5881. }
  5882. }
  5883. }
  5884. }
  5885. };
  5886. this.changeId = function (oldId, newId) {
  5887. _delements[newId] = _delements[oldId];
  5888. _delements[oldId] = {};
  5889. _draggablesForElements[newId] = _draggablesForElements[oldId];
  5890. _draggablesForElements[oldId] = null;
  5891. };
  5892. this.getElementsForDraggable = function (id) {
  5893. return _delements[id];
  5894. };
  5895. this.elementRemoved = function (elementId) {
  5896. var elId = _draggablesForElements[elementId];
  5897. if (elId) {
  5898. delete _delements[elId][elementId];
  5899. delete _draggablesForElements[elementId];
  5900. }
  5901. };
  5902. this.reset = function () {
  5903. _draggables = {};
  5904. _dlist = [];
  5905. _delements = {};
  5906. _elementsWithEndpoints = {};
  5907. };
  5908. //
  5909. // notification drag ended. We check automatically if need to update some
  5910. // ancestor's offsets.
  5911. //
  5912. this.dragEnded = function (el) {
  5913. if (el.offsetParent != null) {
  5914. var id = _currentInstance.getId(el),
  5915. ancestor = _draggablesForElements[id];
  5916. if (ancestor) {
  5917. this.updateOffsets(ancestor);
  5918. }
  5919. }
  5920. };
  5921. this.setParent = function (el, elId, p, pId, currentChildLocation) {
  5922. var current = _draggablesForElements[elId];
  5923. if (!_delements[pId]) {
  5924. _delements[pId] = {};
  5925. }
  5926. var pLoc = _currentInstance.getOffset(p),
  5927. cLoc = currentChildLocation || _currentInstance.getOffset(el);
  5928. if (current && _delements[current]) {
  5929. delete _delements[current][elId];
  5930. }
  5931. _delements[pId][elId] = {
  5932. id:elId,
  5933. offset : {
  5934. left: cLoc.left - pLoc.left,
  5935. top: cLoc.top - pLoc.top
  5936. }
  5937. };
  5938. _draggablesForElements[elId] = pId;
  5939. };
  5940. this.clearParent = function(el, elId) {
  5941. var current = _draggablesForElements[elId];
  5942. if (current) {
  5943. delete _delements[current][elId];
  5944. delete _draggablesForElements[elId];
  5945. }
  5946. };
  5947. this.revalidateParent = function(el, elId, childOffset) {
  5948. var current = _draggablesForElements[elId];
  5949. if (current) {
  5950. var co = {};
  5951. co[elId] = childOffset;
  5952. this.updateOffsets(current, co);
  5953. _currentInstance.revalidate(current);
  5954. }
  5955. };
  5956. this.getDragAncestor = function (el) {
  5957. var de = jsPlumb.getElement(el),
  5958. id = _currentInstance.getId(de),
  5959. aid = _draggablesForElements[id];
  5960. if (aid) {
  5961. return jsPlumb.getElement(aid);
  5962. }
  5963. else {
  5964. return null;
  5965. }
  5966. };
  5967. };
  5968. var trim = function (str) {
  5969. return str == null ? null : (str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
  5970. },
  5971. _setClassName = function (el, cn, classList) {
  5972. cn = trim(cn);
  5973. if (typeof el.className.baseVal !== "undefined") {
  5974. el.className.baseVal = cn;
  5975. }
  5976. else {
  5977. el.className = cn;
  5978. }
  5979. // recent (i currently have 61.0.3163.100) version of chrome do not update classList when you set the base val
  5980. // of an svg element's className. in the long run we'd like to move to just using classList anyway
  5981. try {
  5982. var cl = el.classList;
  5983. while (cl.length > 0) {
  5984. cl.remove(cl.item(0));
  5985. }
  5986. for (var i = 0; i < classList.length; i++) {
  5987. if (classList[i]) {
  5988. cl.add(classList[i]);
  5989. }
  5990. }
  5991. }
  5992. catch(e) {
  5993. // not fatal
  5994. console.log("JSPLUMB: cannot set class list", e);
  5995. }
  5996. },
  5997. _getClassName = function (el) {
  5998. return (typeof el.className.baseVal === "undefined") ? el.className : el.className.baseVal;
  5999. },
  6000. _classManip = function (el, classesToAdd, classesToRemove) {
  6001. classesToAdd = classesToAdd == null ? [] : _ju.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/);
  6002. classesToRemove = classesToRemove == null ? [] : _ju.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/);
  6003. var className = _getClassName(el),
  6004. curClasses = className.split(/\s+/);
  6005. var _oneSet = function (add, classes) {
  6006. for (var i = 0; i < classes.length; i++) {
  6007. if (add) {
  6008. if (curClasses.indexOf(classes[i]) === -1) {
  6009. curClasses.push(classes[i]);
  6010. }
  6011. }
  6012. else {
  6013. var idx = curClasses.indexOf(classes[i]);
  6014. if (idx !== -1) {
  6015. curClasses.splice(idx, 1);
  6016. }
  6017. }
  6018. }
  6019. };
  6020. _oneSet(true, classesToAdd);
  6021. _oneSet(false, classesToRemove);
  6022. _setClassName(el, curClasses.join(" "), curClasses);
  6023. };
  6024. root.jsPlumb.extend(root.jsPlumbInstance.prototype, {
  6025. headless: false,
  6026. pageLocation: _pageLocation,
  6027. screenLocation: _screenLocation,
  6028. clientLocation: _clientLocation,
  6029. getDragManager:function() {
  6030. if (this.dragManager == null) {
  6031. this.dragManager = new DragManager(this);
  6032. }
  6033. return this.dragManager;
  6034. },
  6035. // NEVER CALLED IN THE CURRENT JS
  6036. recalculateOffsets:function(elId) {
  6037. this.getDragManager().updateOffsets(elId);
  6038. },
  6039. // CONVERTED
  6040. createElement:function(tag, style, clazz, atts) {
  6041. return this.createElementNS(null, tag, style, clazz, atts);
  6042. },
  6043. // CONVERTED
  6044. createElementNS:function(ns, tag, style, clazz, atts) {
  6045. var e = ns == null ? document.createElement(tag) : document.createElementNS(ns, tag);
  6046. var i;
  6047. style = style || {};
  6048. for (i in style) {
  6049. e.style[i] = style[i];
  6050. }
  6051. if (clazz) {
  6052. e.className = clazz;
  6053. }
  6054. atts = atts || {};
  6055. for (i in atts) {
  6056. e.setAttribute(i, "" + atts[i]);
  6057. }
  6058. return e;
  6059. },
  6060. // CONVERTED
  6061. getAttribute: function (el, attName) {
  6062. return el.getAttribute != null ? el.getAttribute(attName) : null;
  6063. },
  6064. // CONVERTED
  6065. setAttribute: function (el, a, v) {
  6066. if (el.setAttribute != null) {
  6067. el.setAttribute(a, v);
  6068. }
  6069. },
  6070. // CONVERTED
  6071. setAttributes: function (el, atts) {
  6072. for (var i in atts) {
  6073. if (atts.hasOwnProperty(i)) {
  6074. el.setAttribute(i, atts[i]);
  6075. }
  6076. }
  6077. },
  6078. appendToRoot: function (node) {
  6079. document.body.appendChild(node);
  6080. },
  6081. // NOT CONVERTING
  6082. getRenderModes: function () {
  6083. return [ "svg" ];
  6084. },
  6085. // CONVERTED
  6086. getClass:_getClassName,
  6087. // CONVERTED
  6088. addClass: function (el, clazz) {
  6089. jsPlumb.each(el, function (e) {
  6090. _classManip(e, clazz);
  6091. });
  6092. },
  6093. // CONVERTED
  6094. hasClass: function (el, clazz) {
  6095. el = jsPlumb.getElement(el);
  6096. if (el.classList) {
  6097. return el.classList.contains(clazz);
  6098. }
  6099. else {
  6100. return _getClassName(el).indexOf(clazz) !== -1;
  6101. }
  6102. },
  6103. // CONVERTED
  6104. removeClass: function (el, clazz) {
  6105. jsPlumb.each(el, function (e) {
  6106. _classManip(e, null, clazz);
  6107. });
  6108. },
  6109. // CONVERTED
  6110. updateClasses: function (el, toAdd, toRemove) {
  6111. jsPlumb.each(el, function (e) {
  6112. _classManip(e, toAdd, toRemove);
  6113. });
  6114. },
  6115. // CONVERTED
  6116. setClass: function (el, clazz) {
  6117. if (clazz != null) {
  6118. jsPlumb.each(el, function (e) {
  6119. _setClassName(e, clazz, clazz.split(/\s+/));
  6120. });
  6121. }
  6122. },
  6123. // CONVERTED
  6124. setPosition: function (el, p) {
  6125. el.style.left = p.left + "px";
  6126. el.style.top = p.top + "px";
  6127. },
  6128. // CONVERTED
  6129. getPosition: function (el) {
  6130. var _one = function (prop) {
  6131. var v = el.style[prop];
  6132. return v ? v.substring(0, v.length - 2) : 0;
  6133. };
  6134. return {
  6135. left: _one("left"),
  6136. top: _one("top")
  6137. };
  6138. },
  6139. // CONVERTED
  6140. getStyle:function(el, prop) {
  6141. if (typeof window.getComputedStyle !== 'undefined') {
  6142. return getComputedStyle(el, null).getPropertyValue(prop);
  6143. } else {
  6144. return el.currentStyle[prop];
  6145. }
  6146. },
  6147. // CONVERTED
  6148. getSelector: function (ctx, spec) {
  6149. var sel = null;
  6150. if (arguments.length === 1) {
  6151. sel = ctx.nodeType != null ? ctx : document.querySelectorAll(ctx);
  6152. }
  6153. else {
  6154. sel = ctx.querySelectorAll(spec);
  6155. }
  6156. return sel;
  6157. },
  6158. // CONVERTED
  6159. getOffset:function(el, relativeToRoot, container) {
  6160. el = jsPlumb.getElement(el);
  6161. container = container || this.getContainer();
  6162. var out = {
  6163. left: el.offsetLeft,
  6164. top: el.offsetTop
  6165. },
  6166. op = (relativeToRoot || (container != null && (el !== container && el.offsetParent !== container))) ? el.offsetParent : null,
  6167. _maybeAdjustScroll = function(offsetParent) {
  6168. if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) {
  6169. out.left -= offsetParent.scrollLeft;
  6170. out.top -= offsetParent.scrollTop;
  6171. }
  6172. }.bind(this);
  6173. while (op != null) {
  6174. out.left += op.offsetLeft;
  6175. out.top += op.offsetTop;
  6176. _maybeAdjustScroll(op);
  6177. op = relativeToRoot ? op.offsetParent :
  6178. op.offsetParent === container ? null : op.offsetParent;
  6179. }
  6180. // if container is scrolled and the element (or its offset parent) is not absolute or fixed, adjust accordingly.
  6181. if (container != null && !relativeToRoot && (container.scrollTop > 0 || container.scrollLeft > 0)) {
  6182. var pp = el.offsetParent != null ? this.getStyle(el.offsetParent, "position") : "static",
  6183. p = this.getStyle(el, "position");
  6184. if (p !== "absolute" && p !== "fixed" && pp !== "absolute" && pp !== "fixed") {
  6185. out.left -= container.scrollLeft;
  6186. out.top -= container.scrollTop;
  6187. }
  6188. }
  6189. return out;
  6190. },
  6191. //
  6192. // return x+y proportion of the given element's size corresponding to the location of the given event.
  6193. //
  6194. getPositionOnElement: function (evt, el, zoom) {
  6195. var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 },
  6196. body = document.body,
  6197. docElem = document.documentElement,
  6198. scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
  6199. scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
  6200. clientTop = docElem.clientTop || body.clientTop || 0,
  6201. clientLeft = docElem.clientLeft || body.clientLeft || 0,
  6202. pst = 0,
  6203. psl = 0,
  6204. top = box.top + scrollTop - clientTop + (pst * zoom),
  6205. left = box.left + scrollLeft - clientLeft + (psl * zoom),
  6206. cl = jsPlumb.pageLocation(evt),
  6207. w = box.width || (el.offsetWidth * zoom),
  6208. h = box.height || (el.offsetHeight * zoom),
  6209. x = (cl[0] - left) / w,
  6210. y = (cl[1] - top) / h;
  6211. return [ x, y ];
  6212. },
  6213. /**
  6214. * Gets the absolute position of some element as read from the left/top properties in its style.
  6215. * @method getAbsolutePosition
  6216. * @param {Element} el The element to retrieve the absolute coordinates from. **Note** this is a DOM element, not a selector from the underlying library.
  6217. * @return {Number[]} [left, top] pixel values.
  6218. */
  6219. getAbsolutePosition: function (el) {
  6220. var _one = function (s) {
  6221. var ss = el.style[s];
  6222. if (ss) {
  6223. return parseFloat(ss.substring(0, ss.length - 2));
  6224. }
  6225. };
  6226. return [ _one("left"), _one("top") ];
  6227. },
  6228. /**
  6229. * Sets the absolute position of some element by setting the left/top properties in its style.
  6230. * @method setAbsolutePosition
  6231. * @param {Element} el The element to set the absolute coordinates on. **Note** this is a DOM element, not a selector from the underlying library.
  6232. * @param {Number[]} xy x and y coordinates
  6233. * @param {Number[]} [animateFrom] Optional previous xy to animate from.
  6234. * @param {Object} [animateOptions] Options for the animation.
  6235. */
  6236. setAbsolutePosition: function (el, xy, animateFrom, animateOptions) {
  6237. if (animateFrom) {
  6238. this.animate(el, {
  6239. left: "+=" + (xy[0] - animateFrom[0]),
  6240. top: "+=" + (xy[1] - animateFrom[1])
  6241. }, animateOptions);
  6242. }
  6243. else {
  6244. el.style.left = xy[0] + "px";
  6245. el.style.top = xy[1] + "px";
  6246. }
  6247. },
  6248. /**
  6249. * gets the size for the element, in an array : [ width, height ].
  6250. */
  6251. // CONVERTED
  6252. getSize: function (el) {
  6253. return [ el.offsetWidth, el.offsetHeight ];
  6254. },
  6255. // CONVERTED
  6256. getWidth: function (el) {
  6257. return el.offsetWidth;
  6258. },
  6259. // CONVERTED
  6260. getHeight: function (el) {
  6261. return el.offsetHeight;
  6262. },
  6263. getRenderMode : function() { return "svg"; }
  6264. });
  6265. }).call(typeof window !== 'undefined' ? window : this);
  6266. /*
  6267. * 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  6268. *
  6269. * https://jsplumbtoolkit.com
  6270. * https://github.com/jsplumb/jsplumb
  6271. *
  6272. * Dual licensed under the MIT and GPL2 licenses.
  6273. */
  6274. ;(function() {
  6275. "use strict";
  6276. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  6277. // ------------------------------ BEGIN OverlayCapablejsPlumbUIComponent --------------------------------------------
  6278. var _internalLabelOverlayId = "__label",
  6279. // this is a shortcut helper method to let people add a label as
  6280. // overlay.
  6281. _makeLabelOverlay = function (component, params) {
  6282. var _params = {
  6283. cssClass: params.cssClass,
  6284. labelStyle: component.labelStyle,
  6285. id: _internalLabelOverlayId,
  6286. component: component,
  6287. _jsPlumb: component._jsPlumb.instance // TODO not necessary, since the instance can be accessed through the component.
  6288. },
  6289. mergedParams = _jp.extend(_params, params);
  6290. return new _jp.Overlays[component._jsPlumb.instance.getRenderMode()].Label(mergedParams);
  6291. },
  6292. _processOverlay = function (component, o) {
  6293. var _newOverlay = null;
  6294. if (_ju.isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  6295. // there's also a three arg version:
  6296. // ["Arrow", { width:50 }, {location:0.7}]
  6297. // which merges the 3rd arg into the 2nd.
  6298. var type = o[0],
  6299. // make a copy of the object so as not to mess up anyone else's reference...
  6300. p = _jp.extend({component: component, _jsPlumb: component._jsPlumb.instance}, o[1]);
  6301. if (o.length === 3) {
  6302. _jp.extend(p, o[2]);
  6303. }
  6304. _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][type](p);
  6305. } else if (o.constructor === String) {
  6306. _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][o]({component: component, _jsPlumb: component._jsPlumb.instance});
  6307. } else {
  6308. _newOverlay = o;
  6309. }
  6310. _newOverlay.id = _newOverlay.id || _ju.uuid();
  6311. component.cacheTypeItem("overlay", _newOverlay, _newOverlay.id);
  6312. component._jsPlumb.overlays[_newOverlay.id] = _newOverlay;
  6313. return _newOverlay;
  6314. };
  6315. _jp.OverlayCapableJsPlumbUIComponent = function (params) {
  6316. root.jsPlumbUIComponent.apply(this, arguments);
  6317. this._jsPlumb.overlays = {};
  6318. this._jsPlumb.overlayPositions = {};
  6319. if (params.label) {
  6320. this.getDefaultType().overlays[_internalLabelOverlayId] = ["Label", {
  6321. label: params.label,
  6322. location: params.labelLocation || this.defaultLabelLocation || 0.5,
  6323. labelStyle: params.labelStyle || this._jsPlumb.instance.Defaults.LabelStyle,
  6324. id:_internalLabelOverlayId
  6325. }];
  6326. }
  6327. this.setListenerComponent = function (c) {
  6328. if (this._jsPlumb) {
  6329. for (var i in this._jsPlumb.overlays) {
  6330. this._jsPlumb.overlays[i].setListenerComponent(c);
  6331. }
  6332. }
  6333. };
  6334. };
  6335. _jp.OverlayCapableJsPlumbUIComponent.applyType = function (component, t) {
  6336. if (t.overlays) {
  6337. // loop through the ones in the type. if already present on the component,
  6338. // dont remove or re-add.
  6339. var keep = {}, i;
  6340. for (i in t.overlays) {
  6341. var existing = component._jsPlumb.overlays[t.overlays[i][1].id];
  6342. if (existing) {
  6343. // maybe update from data, if there were parameterised values for instance.
  6344. existing.updateFrom(t.overlays[i][1]);
  6345. keep[t.overlays[i][1].id] = true;
  6346. }
  6347. else {
  6348. var c = component.getCachedTypeItem("overlay", t.overlays[i][1].id);
  6349. if (c != null) {
  6350. c.reattach(component._jsPlumb.instance, component);
  6351. c.setVisible(true);
  6352. // maybe update from data, if there were parameterised values for instance.
  6353. c.updateFrom(t.overlays[i][1]);
  6354. component._jsPlumb.overlays[c.id] = c;
  6355. }
  6356. else {
  6357. c = component.addOverlay(t.overlays[i], true);
  6358. }
  6359. keep[c.id] = true;
  6360. }
  6361. }
  6362. // now loop through the full overlays and remove those that we dont want to keep
  6363. for (i in component._jsPlumb.overlays) {
  6364. if (keep[component._jsPlumb.overlays[i].id] == null) {
  6365. component.removeOverlay(component._jsPlumb.overlays[i].id, true); // remove overlay but dont clean it up.
  6366. // that would remove event listeners etc; overlays are never discarded by the types stuff, they are
  6367. // just detached/reattached.
  6368. }
  6369. }
  6370. }
  6371. };
  6372. _ju.extend(_jp.OverlayCapableJsPlumbUIComponent, root.jsPlumbUIComponent, {
  6373. setHover: function (hover, ignoreAttachedElements) {
  6374. if (this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
  6375. for (var i in this._jsPlumb.overlays) {
  6376. this._jsPlumb.overlays[i][hover ? "addClass" : "removeClass"](this._jsPlumb.instance.hoverClass);
  6377. }
  6378. }
  6379. },
  6380. addOverlay: function (overlay, doNotRepaint) {
  6381. var o = _processOverlay(this, overlay);
  6382. if (!doNotRepaint) {
  6383. this.repaint();
  6384. }
  6385. return o;
  6386. },
  6387. getOverlay: function (id) {
  6388. return this._jsPlumb.overlays[id];
  6389. },
  6390. getOverlays: function () {
  6391. return this._jsPlumb.overlays;
  6392. },
  6393. hideOverlay: function (id) {
  6394. var o = this.getOverlay(id);
  6395. if (o) {
  6396. o.hide();
  6397. }
  6398. },
  6399. hideOverlays: function () {
  6400. for (var i in this._jsPlumb.overlays) {
  6401. this._jsPlumb.overlays[i].hide();
  6402. }
  6403. },
  6404. showOverlay: function (id) {
  6405. var o = this.getOverlay(id);
  6406. if (o) {
  6407. o.show();
  6408. }
  6409. },
  6410. showOverlays: function () {
  6411. for (var i in this._jsPlumb.overlays) {
  6412. this._jsPlumb.overlays[i].show();
  6413. }
  6414. },
  6415. removeAllOverlays: function (doNotRepaint) {
  6416. for (var i in this._jsPlumb.overlays) {
  6417. if (this._jsPlumb.overlays[i].cleanup) {
  6418. this._jsPlumb.overlays[i].cleanup();
  6419. }
  6420. }
  6421. this._jsPlumb.overlays = {};
  6422. this._jsPlumb.overlayPositions = null;
  6423. if (!doNotRepaint) {
  6424. this.repaint();
  6425. }
  6426. },
  6427. removeOverlay: function (overlayId, dontCleanup) {
  6428. var o = this._jsPlumb.overlays[overlayId];
  6429. if (o) {
  6430. o.setVisible(false);
  6431. if (!dontCleanup && o.cleanup) {
  6432. o.cleanup();
  6433. }
  6434. delete this._jsPlumb.overlays[overlayId];
  6435. if (this._jsPlumb.overlayPositions) {
  6436. delete this._jsPlumb.overlayPositions[overlayId];
  6437. }
  6438. }
  6439. },
  6440. removeOverlays: function () {
  6441. for (var i = 0, j = arguments.length; i < j; i++) {
  6442. this.removeOverlay(arguments[i]);
  6443. }
  6444. },
  6445. moveParent: function (newParent) {
  6446. if (this.bgCanvas) {
  6447. this.bgCanvas.parentNode.removeChild(this.bgCanvas);
  6448. newParent.appendChild(this.bgCanvas);
  6449. }
  6450. if (this.canvas && this.canvas.parentNode) {
  6451. this.canvas.parentNode.removeChild(this.canvas);
  6452. newParent.appendChild(this.canvas);
  6453. for (var i in this._jsPlumb.overlays) {
  6454. if (this._jsPlumb.overlays[i].isAppendedAtTopLevel) {
  6455. var el = this._jsPlumb.overlays[i].getElement();
  6456. el.parentNode.removeChild(el);
  6457. newParent.appendChild(el);
  6458. }
  6459. }
  6460. }
  6461. },
  6462. getLabel: function () {
  6463. var lo = this.getOverlay(_internalLabelOverlayId);
  6464. return lo != null ? lo.getLabel() : null;
  6465. },
  6466. getLabelOverlay: function () {
  6467. return this.getOverlay(_internalLabelOverlayId);
  6468. },
  6469. setLabel: function (l) {
  6470. var lo = this.getOverlay(_internalLabelOverlayId);
  6471. if (!lo) {
  6472. var params = l.constructor === String || l.constructor === Function ? { label: l } : l;
  6473. lo = _makeLabelOverlay(this, params);
  6474. this._jsPlumb.overlays[_internalLabelOverlayId] = lo;
  6475. }
  6476. else {
  6477. if (l.constructor === String || l.constructor === Function) {
  6478. lo.setLabel(l);
  6479. }
  6480. else {
  6481. if (l.label) {
  6482. lo.setLabel(l.label);
  6483. }
  6484. if (l.location) {
  6485. lo.setLocation(l.location);
  6486. }
  6487. }
  6488. }
  6489. if (!this._jsPlumb.instance.isSuspendDrawing()) {
  6490. this.repaint();
  6491. }
  6492. },
  6493. cleanup: function (force) {
  6494. for (var i in this._jsPlumb.overlays) {
  6495. this._jsPlumb.overlays[i].cleanup(force);
  6496. this._jsPlumb.overlays[i].destroy(force);
  6497. }
  6498. if (force) {
  6499. this._jsPlumb.overlays = {};
  6500. this._jsPlumb.overlayPositions = null;
  6501. }
  6502. },
  6503. setVisible: function (v) {
  6504. this[v ? "showOverlays" : "hideOverlays"]();
  6505. },
  6506. setAbsoluteOverlayPosition: function (overlay, xy) {
  6507. this._jsPlumb.overlayPositions[overlay.id] = xy;
  6508. },
  6509. getAbsoluteOverlayPosition: function (overlay) {
  6510. return this._jsPlumb.overlayPositions ? this._jsPlumb.overlayPositions[overlay.id] : null;
  6511. },
  6512. _clazzManip:function(action, clazz, dontUpdateOverlays) {
  6513. if (!dontUpdateOverlays) {
  6514. for (var i in this._jsPlumb.overlays) {
  6515. this._jsPlumb.overlays[i][action + "Class"](clazz);
  6516. }
  6517. }
  6518. },
  6519. addClass:function(clazz, dontUpdateOverlays) {
  6520. this._clazzManip("add", clazz, dontUpdateOverlays);
  6521. },
  6522. removeClass:function(clazz, dontUpdateOverlays) {
  6523. this._clazzManip("remove", clazz, dontUpdateOverlays);
  6524. }
  6525. });
  6526. // ------------------------------ END OverlayCapablejsPlumbUIComponent --------------------------------------------
  6527. }).call(typeof window !== 'undefined' ? window : this);
  6528. /*
  6529. * This file contains the code for Endpoints.
  6530. *
  6531. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  6532. *
  6533. * https://jsplumbtoolkit.com
  6534. * https://github.com/jsplumb/jsplumb
  6535. *
  6536. * Dual licensed under the MIT and GPL2 licenses.
  6537. */
  6538. ;(function () {
  6539. "use strict";
  6540. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  6541. // create the drag handler for a connection
  6542. var _makeConnectionDragHandler = function (endpoint, placeholder, _jsPlumb) {
  6543. var stopped = false;
  6544. return {
  6545. drag: function () {
  6546. if (stopped) {
  6547. stopped = false;
  6548. return true;
  6549. }
  6550. if (placeholder.element) {
  6551. var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom());
  6552. if (_ui != null) {
  6553. _jsPlumb.setPosition(placeholder.element, _ui);
  6554. }
  6555. _jsPlumb.repaint(placeholder.element, _ui);
  6556. // always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint
  6557. // to be repainted, so static anchors need to be told (or the endpoint gets dragged around)
  6558. endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint})});
  6559. }
  6560. },
  6561. stopDrag: function () {
  6562. stopped = true;
  6563. }
  6564. };
  6565. };
  6566. // creates a placeholder div for dragging purposes, adds it, and pre-computes its offset.
  6567. var _makeDraggablePlaceholder = function (placeholder, _jsPlumb, ipco, ips) {
  6568. var n = _jsPlumb.createElement("div", { position : "absolute" });
  6569. _jsPlumb.appendElement(n);
  6570. var id = _jsPlumb.getId(n);
  6571. _jsPlumb.setPosition(n, ipco);
  6572. n.style.width = ips[0] + "px";
  6573. n.style.height = ips[1] + "px";
  6574. _jsPlumb.manage(id, n, true); // TRANSIENT MANAGE
  6575. // create and assign an id, and initialize the offset.
  6576. placeholder.id = id;
  6577. placeholder.element = n;
  6578. };
  6579. // create a floating endpoint (for drag connections)
  6580. var _makeFloatingEndpoint = function (paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint, scope) {
  6581. var floatingAnchor = new _jp.FloatingAnchor({ reference: referenceAnchor, referenceCanvas: referenceCanvas, jsPlumbInstance: _jsPlumb });
  6582. //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
  6583. // adding the floating endpoint as a droppable. that makes more sense anyway!
  6584. // TRANSIENT MANAGE
  6585. return _newEndpoint({
  6586. paintStyle: paintStyle,
  6587. endpoint: endpoint,
  6588. anchor: floatingAnchor,
  6589. source: sourceElement,
  6590. scope: scope
  6591. });
  6592. };
  6593. var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays",
  6594. "connector", "connectionType", "connectorClass", "connectorHoverClass" ];
  6595. // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
  6596. // or no connection to it is found, we return the first connection in our list.
  6597. var findConnectionToUseForDynamicAnchor = function (ep, elementWithPrecedence) {
  6598. var idx = 0;
  6599. if (elementWithPrecedence != null) {
  6600. for (var i = 0; i < ep.connections.length; i++) {
  6601. if (ep.connections[i].sourceId === elementWithPrecedence || ep.connections[i].targetId === elementWithPrecedence) {
  6602. idx = i;
  6603. break;
  6604. }
  6605. }
  6606. }
  6607. return ep.connections[idx];
  6608. };
  6609. _jp.Endpoint = function (params) {
  6610. var _jsPlumb = params._jsPlumb,
  6611. _newConnection = params.newConnection,
  6612. _newEndpoint = params.newEndpoint;
  6613. this.idPrefix = "_jsplumb_e_";
  6614. this.defaultLabelLocation = [ 0.5, 0.5 ];
  6615. this.defaultOverlayKeys = ["Overlays", "EndpointOverlays"];
  6616. _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
  6617. // TYPE
  6618. this.appendToDefaultType({
  6619. connectionType:params.connectionType,
  6620. maxConnections: params.maxConnections == null ? this._jsPlumb.instance.Defaults.MaxConnections : params.maxConnections, // maximum number of connections this endpoint can be the source of.,
  6621. paintStyle: params.endpointStyle || params.paintStyle || params.style || this._jsPlumb.instance.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle,
  6622. hoverPaintStyle: params.endpointHoverStyle || params.hoverPaintStyle || this._jsPlumb.instance.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle,
  6623. connectorStyle: params.connectorStyle,
  6624. connectorHoverStyle: params.connectorHoverStyle,
  6625. connectorClass: params.connectorClass,
  6626. connectorHoverClass: params.connectorHoverClass,
  6627. connectorOverlays: params.connectorOverlays,
  6628. connector: params.connector,
  6629. connectorTooltip: params.connectorTooltip
  6630. });
  6631. // END TYPE
  6632. this._jsPlumb.enabled = !(params.enabled === false);
  6633. this._jsPlumb.visible = true;
  6634. this.element = _jp.getElement(params.source);
  6635. this._jsPlumb.uuid = params.uuid;
  6636. this._jsPlumb.floatingEndpoint = null;
  6637. var inPlaceCopy = null;
  6638. if (this._jsPlumb.uuid) {
  6639. params.endpointsByUUID[this._jsPlumb.uuid] = this;
  6640. }
  6641. this.elementId = params.elementId;
  6642. this.dragProxy = params.dragProxy;
  6643. this._jsPlumb.connectionCost = params.connectionCost;
  6644. this._jsPlumb.connectionsDirected = params.connectionsDirected;
  6645. this._jsPlumb.currentAnchorClass = "";
  6646. this._jsPlumb.events = {};
  6647. var deleteOnEmpty = params.deleteOnEmpty === true;
  6648. this.setDeleteOnEmpty = function(d) {
  6649. deleteOnEmpty = d;
  6650. };
  6651. var _updateAnchorClass = function () {
  6652. // stash old, get new
  6653. var oldAnchorClass = _jsPlumb.endpointAnchorClassPrefix + "-" + this._jsPlumb.currentAnchorClass;
  6654. this._jsPlumb.currentAnchorClass = this.anchor.getCssClass();
  6655. var anchorClass = _jsPlumb.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
  6656. this.removeClass(oldAnchorClass);
  6657. this.addClass(anchorClass);
  6658. // add and remove at the same time to reduce the number of reflows.
  6659. _jp.updateClasses(this.element, anchorClass, oldAnchorClass);
  6660. }.bind(this);
  6661. this.prepareAnchor = function(anchorParams) {
  6662. var a = this._jsPlumb.instance.makeAnchor(anchorParams, this.elementId, _jsPlumb);
  6663. a.bind("anchorChanged", function (currentAnchor) {
  6664. this.fire("anchorChanged", {endpoint: this, anchor: currentAnchor});
  6665. _updateAnchorClass();
  6666. }.bind(this));
  6667. return a;
  6668. };
  6669. this.setPreparedAnchor = function(anchor, doNotRepaint) {
  6670. this._jsPlumb.instance.continuousAnchorFactory.clear(this.elementId);
  6671. this.anchor = anchor;
  6672. _updateAnchorClass();
  6673. if (!doNotRepaint) {
  6674. this._jsPlumb.instance.repaint(this.elementId);
  6675. }
  6676. return this;
  6677. };
  6678. this.setAnchor = function (anchorParams, doNotRepaint) {
  6679. var a = this.prepareAnchor(anchorParams);
  6680. this.setPreparedAnchor(a, doNotRepaint);
  6681. return this;
  6682. };
  6683. var internalHover = function (state) {
  6684. if (this.connections.length > 0) {
  6685. for (var i = 0; i < this.connections.length; i++) {
  6686. this.connections[i].setHover(state, false);
  6687. }
  6688. }
  6689. else {
  6690. this.setHover(state);
  6691. }
  6692. }.bind(this);
  6693. this.bind("mouseover", function () {
  6694. internalHover(true);
  6695. });
  6696. this.bind("mouseout", function () {
  6697. internalHover(false);
  6698. });
  6699. // ANCHOR MANAGER
  6700. 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.
  6701. this._jsPlumb.instance.anchorManager.add(this, this.elementId);
  6702. }
  6703. this.prepareEndpoint = function(ep, typeId) {
  6704. var _e = function (t, p) {
  6705. var rm = _jsPlumb.getRenderMode();
  6706. if (_jp.Endpoints[rm][t]) {
  6707. return new _jp.Endpoints[rm][t](p);
  6708. }
  6709. if (!_jsPlumb.Defaults.DoNotThrowErrors) {
  6710. throw { msg: "jsPlumb: unknown endpoint type '" + t + "'" };
  6711. }
  6712. };
  6713. var endpointArgs = {
  6714. _jsPlumb: this._jsPlumb.instance,
  6715. cssClass: params.cssClass,
  6716. container: params.container,
  6717. tooltip: params.tooltip,
  6718. connectorTooltip: params.connectorTooltip,
  6719. endpoint: this
  6720. };
  6721. var endpoint;
  6722. if (_ju.isString(ep)) {
  6723. endpoint = _e(ep, endpointArgs);
  6724. }
  6725. else if (_ju.isArray(ep)) {
  6726. endpointArgs = _ju.merge(ep[1], endpointArgs);
  6727. endpoint = _e(ep[0], endpointArgs);
  6728. }
  6729. else {
  6730. endpoint = ep.clone();
  6731. }
  6732. // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
  6733. // and the clone is left in its place while the original one goes off on a magical journey.
  6734. // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by
  6735. // the whole world.
  6736. //var argsForClone = jsPlumb.extend({}, endpointArgs);
  6737. endpoint.clone = function () {
  6738. // TODO this, and the code above, can be refactored to be more dry.
  6739. if (_ju.isString(ep)) {
  6740. return _e(ep, endpointArgs);
  6741. }
  6742. else if (_ju.isArray(ep)) {
  6743. endpointArgs = _ju.merge(ep[1], endpointArgs);
  6744. return _e(ep[0], endpointArgs);
  6745. }
  6746. }.bind(this);
  6747. endpoint.typeId = typeId;
  6748. return endpoint;
  6749. };
  6750. this.setEndpoint = function(ep, doNotRepaint) {
  6751. var _ep = this.prepareEndpoint(ep);
  6752. this.setPreparedEndpoint(_ep, true);
  6753. };
  6754. this.setPreparedEndpoint = function (ep, doNotRepaint) {
  6755. if (this.endpoint != null) {
  6756. this.endpoint.cleanup();
  6757. this.endpoint.destroy();
  6758. }
  6759. this.endpoint = ep;
  6760. this.type = this.endpoint.type;
  6761. this.canvas = this.endpoint.canvas;
  6762. };
  6763. _jp.extend(this, params, typeParameters);
  6764. this.isSource = params.isSource || false;
  6765. this.isTemporarySource = params.isTemporarySource || false;
  6766. this.isTarget = params.isTarget || false;
  6767. this.connections = params.connections || [];
  6768. this.connectorPointerEvents = params["connector-pointer-events"];
  6769. this.scope = params.scope || _jsPlumb.getDefaultScope();
  6770. this.timestamp = null;
  6771. this.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections;
  6772. this.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable;
  6773. if (params.connectionsDetachable === false || params.detachable === false) {
  6774. this.connectionsDetachable = false;
  6775. }
  6776. this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false;
  6777. if (params.onMaxConnections) {
  6778. this.bind("maxConnections", params.onMaxConnections);
  6779. }
  6780. //
  6781. // add a connection. not part of public API.
  6782. //
  6783. this.addConnection = function (connection) {
  6784. this.connections.push(connection);
  6785. this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
  6786. this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
  6787. };
  6788. this.detachFromConnection = function (connection, idx, doNotCleanup) {
  6789. idx = idx == null ? this.connections.indexOf(connection) : idx;
  6790. if (idx >= 0) {
  6791. this.connections.splice(idx, 1);
  6792. this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
  6793. this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
  6794. }
  6795. if (!doNotCleanup && deleteOnEmpty && this.connections.length === 0) {
  6796. _jsPlumb.deleteObject({
  6797. endpoint: this,
  6798. fireEvent: false,
  6799. deleteAttachedObjects: doNotCleanup !== true
  6800. });
  6801. }
  6802. };
  6803. this.deleteEveryConnection = function(params) {
  6804. var c = this.connections.length;
  6805. for (var i = 0; i < c; i++) {
  6806. _jsPlumb.deleteConnection(this.connections[0], params);
  6807. }
  6808. };
  6809. this.detachFrom = function (targetEndpoint, fireEvent, originalEvent) {
  6810. var c = [];
  6811. for (var i = 0; i < this.connections.length; i++) {
  6812. if (this.connections[i].endpoints[1] === targetEndpoint || this.connections[i].endpoints[0] === targetEndpoint) {
  6813. c.push(this.connections[i]);
  6814. }
  6815. }
  6816. for (var j = 0, count = c.length; j < count; j++) {
  6817. _jsPlumb.deleteConnection(c[0]);
  6818. }
  6819. return this;
  6820. };
  6821. this.getElement = function () {
  6822. return this.element;
  6823. };
  6824. this.setElement = function (el) {
  6825. var parentId = this._jsPlumb.instance.getId(el),
  6826. curId = this.elementId;
  6827. // remove the endpoint from the list for the current endpoint's element
  6828. _ju.removeWithFunction(params.endpointsByElement[this.elementId], function (e) {
  6829. return e.id === this.id;
  6830. }.bind(this));
  6831. this.element = _jp.getElement(el);
  6832. this.elementId = _jsPlumb.getId(this.element);
  6833. _jsPlumb.anchorManager.rehomeEndpoint(this, curId, this.element);
  6834. _jsPlumb.dragManager.endpointAdded(this.element);
  6835. _ju.addToList(params.endpointsByElement, parentId, this);
  6836. return this;
  6837. };
  6838. /**
  6839. * private but must be exposed.
  6840. */
  6841. this.makeInPlaceCopy = function () {
  6842. var loc = this.anchor.getCurrentLocation({element: this}),
  6843. o = this.anchor.getOrientation(this),
  6844. acc = this.anchor.getCssClass(),
  6845. inPlaceAnchor = {
  6846. bind: function () {
  6847. },
  6848. compute: function () {
  6849. return [ loc[0], loc[1] ];
  6850. },
  6851. getCurrentLocation: function () {
  6852. return [ loc[0], loc[1] ];
  6853. },
  6854. getOrientation: function () {
  6855. return o;
  6856. },
  6857. getCssClass: function () {
  6858. return acc;
  6859. }
  6860. };
  6861. return _newEndpoint({
  6862. dropOptions: params.dropOptions,
  6863. anchor: inPlaceAnchor,
  6864. source: this.element,
  6865. paintStyle: this.getPaintStyle(),
  6866. endpoint: params.hideOnDrag ? "Blank" : this.endpoint,
  6867. _transient: true,
  6868. scope: this.scope,
  6869. reference:this
  6870. });
  6871. };
  6872. /**
  6873. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  6874. */
  6875. this.connectorSelector = function () {
  6876. return this.connections[0];
  6877. };
  6878. this.setStyle = this.setPaintStyle;
  6879. this.paint = function (params) {
  6880. params = params || {};
  6881. var timestamp = params.timestamp, recalc = !(params.recalc === false);
  6882. if (!timestamp || this.timestamp !== timestamp) {
  6883. var info = _jsPlumb.updateOffset({ elId: this.elementId, timestamp: timestamp });
  6884. var xy = params.offset ? params.offset.o : info.o;
  6885. if (xy != null) {
  6886. var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle;
  6887. if (ap == null) {
  6888. var wh = params.dimensions || info.s,
  6889. anchorParams = { xy: [ xy.left, xy.top ], wh: wh, element: this, timestamp: timestamp };
  6890. if (recalc && this.anchor.isDynamic && this.connections.length > 0) {
  6891. var c = findConnectionToUseForDynamicAnchor(this, params.elementWithPrecedence),
  6892. oIdx = c.endpoints[0] === this ? 1 : 0,
  6893. oId = oIdx === 0 ? c.sourceId : c.targetId,
  6894. oInfo = _jsPlumb.getCachedData(oId),
  6895. oOffset = oInfo.o, oWH = oInfo.s;
  6896. anchorParams.index = oIdx === 0 ? 1 : 0;
  6897. anchorParams.connection = c;
  6898. anchorParams.txy = [ oOffset.left, oOffset.top ];
  6899. anchorParams.twh = oWH;
  6900. anchorParams.tElement = c.endpoints[oIdx];
  6901. } else if (this.connections.length > 0) {
  6902. anchorParams.connection = this.connections[0];
  6903. }
  6904. ap = this.anchor.compute(anchorParams);
  6905. }
  6906. this.endpoint.compute(ap, this.anchor.getOrientation(this), this._jsPlumb.paintStyleInUse, connectorPaintStyle || this.paintStyleInUse);
  6907. this.endpoint.paint(this._jsPlumb.paintStyleInUse, this.anchor);
  6908. this.timestamp = timestamp;
  6909. // paint overlays
  6910. for (var i in this._jsPlumb.overlays) {
  6911. if (this._jsPlumb.overlays.hasOwnProperty(i)) {
  6912. var o = this._jsPlumb.overlays[i];
  6913. if (o.isVisible()) {
  6914. this._jsPlumb.overlayPlacements[i] = o.draw(this.endpoint, this._jsPlumb.paintStyleInUse);
  6915. o.paint(this._jsPlumb.overlayPlacements[i]);
  6916. }
  6917. }
  6918. }
  6919. }
  6920. }
  6921. };
  6922. this.getTypeDescriptor = function () {
  6923. return "endpoint";
  6924. };
  6925. this.isVisible = function () {
  6926. return this._jsPlumb.visible;
  6927. };
  6928. this.repaint = this.paint;
  6929. var draggingInitialised = false;
  6930. this.initDraggable = function () {
  6931. // is this a connection source? we make it draggable and have the
  6932. // drag listener maintain a connection with a floating endpoint.
  6933. if (!draggingInitialised && _jp.isDragSupported(this.element)) {
  6934. var placeholderInfo = { id: null, element: null },
  6935. jpc = null,
  6936. existingJpc = false,
  6937. existingJpcParams = null,
  6938. _dragHandler = _makeConnectionDragHandler(this, placeholderInfo, _jsPlumb),
  6939. dragOptions = params.dragOptions || {},
  6940. defaultOpts = {},
  6941. startEvent = _jp.dragEvents.start,
  6942. stopEvent = _jp.dragEvents.stop,
  6943. dragEvent = _jp.dragEvents.drag,
  6944. beforeStartEvent = _jp.dragEvents.beforeStart,
  6945. payload;
  6946. // respond to beforeStart from katavorio; this will have, optionally, a payload of attribute values
  6947. // that were placed there by the makeSource mousedown listener.
  6948. var beforeStart = function(beforeStartParams) {
  6949. payload = beforeStartParams.e.payload || {};
  6950. };
  6951. var start = function (startParams) {
  6952. // ------------- first, get a connection to drag. this may be null, in which case we are dragging a new one.
  6953. jpc = this.connectorSelector();
  6954. // -------------------------------- now a bunch of tests about whether or not to proceed -------------------------
  6955. var _continue = true;
  6956. // if not enabled, return
  6957. if (!this.isEnabled()) {
  6958. _continue = false;
  6959. }
  6960. // if no connection and we're not a source - or temporarily a source, as is the case with makeSource - return.
  6961. if (jpc == null && !this.isSource && !this.isTemporarySource) {
  6962. _continue = false;
  6963. }
  6964. // otherwise if we're full and not allowed to drag, also return false.
  6965. if (this.isSource && this.isFull() && !(jpc != null && this.dragAllowedWhenFull)) {
  6966. _continue = false;
  6967. }
  6968. // if the connection was setup as not detachable or one of its endpoints
  6969. // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
  6970. // is set to false...
  6971. if (jpc != null && !jpc.isDetachable(this)) {
  6972. _continue = false;
  6973. }
  6974. var beforeDrag = _jsPlumb.checkCondition(jpc == null ? "beforeDrag" : "beforeStartDetach", {
  6975. endpoint:this,
  6976. source:this.element,
  6977. sourceId:this.elementId,
  6978. connection:jpc
  6979. });
  6980. if (beforeDrag === false) {
  6981. _continue = false;
  6982. }
  6983. // else we might have been given some data. we'll pass it in to a new connection as 'data'.
  6984. // here we also merge in the optional payload we were given on mousedown.
  6985. else if (typeof beforeDrag === "object") {
  6986. _jp.extend(beforeDrag, payload || {});
  6987. }
  6988. else {
  6989. // or if no beforeDrag data, maybe use the payload on its own.
  6990. beforeDrag = payload || {};
  6991. }
  6992. if (_continue === false) {
  6993. // this is for mootools and yui. returning false from this causes jquery to stop drag.
  6994. // the events are wrapped in both mootools and yui anyway, but i don't think returning
  6995. // false from the start callback would stop a drag.
  6996. if (_jsPlumb.stopDrag) {
  6997. _jsPlumb.stopDrag(this.canvas);
  6998. }
  6999. _dragHandler.stopDrag();
  7000. return false;
  7001. }
  7002. // ---------------------------------------------------------------------------------------------------------------------
  7003. // ok to proceed.
  7004. // clear hover for all connections for this endpoint before continuing.
  7005. for (var i = 0; i < this.connections.length; i++) {
  7006. this.connections[i].setHover(false);
  7007. }
  7008. this.addClass("endpointDrag");
  7009. _jsPlumb.setConnectionBeingDragged(true);
  7010. // if we're not full but there was a connection, make it null. we'll create a new one.
  7011. if (jpc && !this.isFull() && this.isSource) {
  7012. jpc = null;
  7013. }
  7014. _jsPlumb.updateOffset({ elId: this.elementId });
  7015. // ---------------- make the element we will drag around, and position it -----------------------------
  7016. var ipco = this._jsPlumb.instance.getOffset(this.canvas),
  7017. canvasElement = this.canvas,
  7018. ips = this._jsPlumb.instance.getSize(this.canvas);
  7019. _makeDraggablePlaceholder(placeholderInfo, _jsPlumb, ipco, ips);
  7020. // store the id of the dragging div and the source element. the drop function will pick these up.
  7021. _jsPlumb.setAttributes(this.canvas, {
  7022. "dragId": placeholderInfo.id,
  7023. "elId": this.elementId
  7024. });
  7025. // ------------------- create an endpoint that will be our floating endpoint ------------------------------------
  7026. var endpointToFloat = this.dragProxy || this.endpoint;
  7027. if (this.dragProxy == null && this.connectionType != null) {
  7028. var aae = this._jsPlumb.instance.deriveEndpointAndAnchorSpec(this.connectionType);
  7029. if (aae.endpoints[1]) {
  7030. endpointToFloat = aae.endpoints[1];
  7031. }
  7032. }
  7033. var centerAnchor = this._jsPlumb.instance.makeAnchor("Center");
  7034. centerAnchor.isFloating = true;
  7035. this._jsPlumb.floatingEndpoint = _makeFloatingEndpoint(this.getPaintStyle(), centerAnchor, endpointToFloat, this.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint, this.scope);
  7036. var _savedAnchor = this._jsPlumb.floatingEndpoint.anchor;
  7037. if (jpc == null) {
  7038. this.setHover(false, false);
  7039. // create a connection. one end is this endpoint, the other is a floating endpoint.
  7040. jpc = _newConnection({
  7041. sourceEndpoint: this,
  7042. targetEndpoint: this._jsPlumb.floatingEndpoint,
  7043. source: this.element, // for makeSource with parent option. ensure source element is represented correctly.
  7044. target: placeholderInfo.element,
  7045. anchors: [ this.anchor, this._jsPlumb.floatingEndpoint.anchor ],
  7046. paintStyle: params.connectorStyle, // this can be null. Connection will use the default.
  7047. hoverPaintStyle: params.connectorHoverStyle,
  7048. connector: params.connector, // this can also be null. Connection will use the default.
  7049. overlays: params.connectorOverlays,
  7050. type: this.connectionType,
  7051. cssClass: this.connectorClass,
  7052. hoverClass: this.connectorHoverClass,
  7053. scope:params.scope,
  7054. data:beforeDrag
  7055. });
  7056. jpc.pending = true;
  7057. jpc.addClass(_jsPlumb.draggingClass);
  7058. this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
  7059. this._jsPlumb.floatingEndpoint.anchor = _savedAnchor;
  7060. // fire an event that informs that a connection is being dragged
  7061. _jsPlumb.fire("connectionDrag", jpc);
  7062. // register the new connection on the drag manager. This connection, at this point, is 'pending',
  7063. // and has as its target a temporary element (the 'placeholder'). If the connection subsequently
  7064. // becomes established, the anchor manager is informed that the target of the connection has
  7065. // changed.
  7066. _jsPlumb.anchorManager.newConnection(jpc);
  7067. } else {
  7068. existingJpc = true;
  7069. jpc.setHover(false);
  7070. // new anchor idx
  7071. var anchorIdx = jpc.endpoints[0].id === this.id ? 0 : 1;
  7072. this.detachFromConnection(jpc, null, true); // detach from the connection while dragging is occurring. but dont cleanup automatically.
  7073. // store the original scope (issue 57)
  7074. var dragScope = _jsPlumb.getDragScope(canvasElement);
  7075. _jsPlumb.setAttribute(this.canvas, "originalScope", dragScope);
  7076. // fire an event that informs that a connection is being dragged. we do this before
  7077. // replacing the original target with the floating element info.
  7078. _jsPlumb.fire("connectionDrag", jpc);
  7079. // now we replace ourselves with the temporary div we created above:
  7080. if (anchorIdx === 0) {
  7081. existingJpcParams = [ jpc.source, jpc.sourceId, canvasElement, dragScope ];
  7082. _jsPlumb.anchorManager.sourceChanged(jpc.endpoints[anchorIdx].elementId, placeholderInfo.id, jpc, placeholderInfo.element);
  7083. } else {
  7084. existingJpcParams = [ jpc.target, jpc.targetId, canvasElement, dragScope ];
  7085. jpc.target = placeholderInfo.element;
  7086. jpc.targetId = placeholderInfo.id;
  7087. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.endpoints[anchorIdx].elementId, jpc.targetId, jpc);
  7088. }
  7089. // store the original endpoint and assign the new floating endpoint for the drag.
  7090. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  7091. // PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39)
  7092. jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement();
  7093. jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId;
  7094. jpc.suspendedElementType = anchorIdx === 0 ? "source" : "target";
  7095. jpc.suspendedEndpoint.setHover(false);
  7096. this._jsPlumb.floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint;
  7097. jpc.endpoints[anchorIdx] = this._jsPlumb.floatingEndpoint;
  7098. jpc.addClass(_jsPlumb.draggingClass);
  7099. this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
  7100. }
  7101. _jsPlumb.registerFloatingConnection(placeholderInfo, jpc, this._jsPlumb.floatingEndpoint);
  7102. // // register it and register connection on it.
  7103. // _jsPlumb.floatingConnections[placeholderInfo.id] = jpc;
  7104. //
  7105. // // only register for the target endpoint; we will not be dragging the source at any time
  7106. // // before this connection is either discarded or made into a permanent connection.
  7107. // _ju.addToList(params.endpointsByElement, placeholderInfo.id, this._jsPlumb.floatingEndpoint);
  7108. // tell jsplumb about it
  7109. _jsPlumb.currentlyDragging = true;
  7110. }.bind(this);
  7111. var stop = function () {
  7112. _jsPlumb.setConnectionBeingDragged(false);
  7113. if (jpc && jpc.endpoints != null) {
  7114. // get the actual drop event (decode from library args to stop function)
  7115. var originalEvent = _jsPlumb.getDropEvent(arguments);
  7116. // unlock the other endpoint (if it is dynamic, it would have been locked at drag start)
  7117. var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
  7118. jpc.endpoints[idx === 0 ? 1 : 0].anchor.locked = false;
  7119. // TODO: Dont want to know about css classes inside jsplumb, ideally.
  7120. jpc.removeClass(_jsPlumb.draggingClass);
  7121. // if we have the floating endpoint then the connection has not been dropped
  7122. // on another endpoint. If it is a new connection we throw it away. If it is an
  7123. // existing connection we check to see if we should reattach it, throwing it away
  7124. // if not.
  7125. if (this._jsPlumb && (jpc.deleteConnectionNow || jpc.endpoints[idx] === this._jsPlumb.floatingEndpoint)) {
  7126. // 6a. if the connection was an existing one...
  7127. if (existingJpc && jpc.suspendedEndpoint) {
  7128. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  7129. // floating endpoint has been replaced.
  7130. if (idx === 0) {
  7131. jpc.floatingElement = jpc.source;
  7132. jpc.floatingId = jpc.sourceId;
  7133. jpc.floatingEndpoint = jpc.endpoints[0];
  7134. jpc.floatingIndex = 0;
  7135. jpc.source = existingJpcParams[0];
  7136. jpc.sourceId = existingJpcParams[1];
  7137. } else {
  7138. // keep a copy of the floating element; the anchor manager will want to clean up.
  7139. jpc.floatingElement = jpc.target;
  7140. jpc.floatingId = jpc.targetId;
  7141. jpc.floatingEndpoint = jpc.endpoints[1];
  7142. jpc.floatingIndex = 1;
  7143. jpc.target = existingJpcParams[0];
  7144. jpc.targetId = existingJpcParams[1];
  7145. }
  7146. var fe = this._jsPlumb.floatingEndpoint; // store for later removal.
  7147. // restore the original scope (issue 57)
  7148. _jsPlumb.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  7149. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  7150. // if the connection should be reattached, or the other endpoint refuses detach, then
  7151. // reset the connection to its original state
  7152. if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !_jsPlumb.deleteConnection(jpc, {originalEvent: originalEvent})) {
  7153. jpc.setHover(false);
  7154. jpc._forceDetach = null;
  7155. jpc._forceReattach = null;
  7156. this._jsPlumb.floatingEndpoint.detachFromConnection(jpc);
  7157. jpc.suspendedEndpoint.addConnection(jpc);
  7158. // TODO this code is duplicated in lots of places...and there is nothing external
  7159. // in the code; it all refers to the connection itself. we could add a
  7160. // `checkSanity(connection)` method to anchorManager that did this.
  7161. if (idx === 1) {
  7162. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
  7163. }
  7164. else {
  7165. _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
  7166. }
  7167. _jsPlumb.repaint(existingJpcParams[1]);
  7168. }
  7169. else {
  7170. _jsPlumb.deleteObject({endpoint: fe});
  7171. }
  7172. }
  7173. }
  7174. // makeTargets sets this flag, to tell us we have been replaced and should delete this object.
  7175. if (this.deleteAfterDragStop) {
  7176. _jsPlumb.deleteObject({endpoint: this});
  7177. }
  7178. else {
  7179. if (this._jsPlumb) {
  7180. this.paint({recalc: false});
  7181. }
  7182. }
  7183. // although the connection is no longer valid, there are use cases where this is useful.
  7184. _jsPlumb.fire("connectionDragStop", jpc, originalEvent);
  7185. // fire this event to give people more fine-grained control (connectionDragStop fires a lot)
  7186. if (jpc.pending) {
  7187. _jsPlumb.fire("connectionAborted", jpc, originalEvent);
  7188. }
  7189. // tell jsplumb that dragging is finished.
  7190. _jsPlumb.currentlyDragging = false;
  7191. jpc.suspendedElement = null;
  7192. jpc.suspendedEndpoint = null;
  7193. jpc = null;
  7194. }
  7195. // if no endpoints, jpc already cleaned up. but still we want to ensure we're reset properly.
  7196. // remove the element associated with the floating endpoint
  7197. // (and its associated floating endpoint and visual artefacts)
  7198. if (placeholderInfo && placeholderInfo.element) {
  7199. _jsPlumb.remove(placeholderInfo.element, false, false);
  7200. }
  7201. // remove the inplace copy
  7202. if (inPlaceCopy) {
  7203. _jsPlumb.deleteObject({endpoint: inPlaceCopy});
  7204. }
  7205. if (this._jsPlumb) {
  7206. // make our canvas visible (TODO: hand off to library; we should not know about DOM)
  7207. this.canvas.style.visibility = "visible";
  7208. // unlock our anchor
  7209. this.anchor.locked = false;
  7210. // clear floating anchor.
  7211. this._jsPlumb.floatingEndpoint = null;
  7212. }
  7213. }.bind(this);
  7214. dragOptions = _jp.extend(defaultOpts, dragOptions);
  7215. dragOptions.scope = this.scope || dragOptions.scope;
  7216. dragOptions[beforeStartEvent] = _ju.wrap(dragOptions[beforeStartEvent], beforeStart, false);
  7217. dragOptions[startEvent] = _ju.wrap(dragOptions[startEvent], start, false);
  7218. // extracted drag handler function so can be used by makeSource
  7219. dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], _dragHandler.drag);
  7220. dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], stop);
  7221. dragOptions.multipleDrop = false;
  7222. dragOptions.canDrag = function () {
  7223. return this.isSource || this.isTemporarySource || /*(this.isTarget && */this.connections.length > 0/*)*/;
  7224. }.bind(this);
  7225. _jsPlumb.initDraggable(this.canvas, dragOptions, "internal");
  7226. this.canvas._jsPlumbRelatedElement = this.element;
  7227. draggingInitialised = true;
  7228. }
  7229. };
  7230. var ep = params.endpoint || this._jsPlumb.instance.Defaults.Endpoint || _jp.Defaults.Endpoint;
  7231. this.setEndpoint(ep, true);
  7232. var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top");
  7233. this.setAnchor(anchorParamsToUse, true);
  7234. // finally, set type if it was provided
  7235. var type = [ "default", (params.type || "")].join(" ");
  7236. this.addType(type, params.data, true);
  7237. this.canvas = this.endpoint.canvas;
  7238. this.canvas._jsPlumb = this;
  7239. this.initDraggable();
  7240. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  7241. // back onto the endpoint you detached it from.
  7242. var _initDropTarget = function (canvas, isTransient, endpoint, referenceEndpoint) {
  7243. if (_jp.isDropSupported(this.element)) {
  7244. var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || _jp.Defaults.DropOptions;
  7245. dropOptions = _jp.extend({}, dropOptions);
  7246. dropOptions.scope = dropOptions.scope || this.scope;
  7247. var dropEvent = _jp.dragEvents.drop,
  7248. overEvent = _jp.dragEvents.over,
  7249. outEvent = _jp.dragEvents.out,
  7250. _ep = this,
  7251. drop = _jsPlumb.EndpointDropHandler({
  7252. getEndpoint: function () {
  7253. return _ep;
  7254. },
  7255. jsPlumb: _jsPlumb,
  7256. enabled: function () {
  7257. return endpoint != null ? endpoint.isEnabled() : true;
  7258. },
  7259. isFull: function () {
  7260. return endpoint.isFull();
  7261. },
  7262. element: this.element,
  7263. elementId: this.elementId,
  7264. isSource: this.isSource,
  7265. isTarget: this.isTarget,
  7266. addClass: function (clazz) {
  7267. _ep.addClass(clazz);
  7268. },
  7269. removeClass: function (clazz) {
  7270. _ep.removeClass(clazz);
  7271. },
  7272. isDropAllowed: function () {
  7273. return _ep.isDropAllowed.apply(_ep, arguments);
  7274. },
  7275. reference:referenceEndpoint,
  7276. isRedrop:function(jpc, dhParams) {
  7277. return jpc.suspendedEndpoint && dhParams.reference && (jpc.suspendedEndpoint.id === dhParams.reference.id);
  7278. }
  7279. });
  7280. dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], drop, true);
  7281. dropOptions[overEvent] = _ju.wrap(dropOptions[overEvent], function () {
  7282. var draggable = _jp.getDragObject(arguments),
  7283. id = _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
  7284. _jpc = _jsPlumb.getFloatingConnectionFor(id);//_jsPlumb.floatingConnections[id];
  7285. if (_jpc != null) {
  7286. var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
  7287. // here we should fire the 'over' event if we are a target and this is a new connection,
  7288. // or we are the same as the floating endpoint.
  7289. var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id);
  7290. if (_cont) {
  7291. var bb = _jsPlumb.checkCondition("checkDropAllowed", {
  7292. sourceEndpoint: _jpc.endpoints[idx],
  7293. targetEndpoint: this,
  7294. connection: _jpc
  7295. });
  7296. this[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass);
  7297. this[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass);
  7298. _jpc.endpoints[idx].anchor.over(this.anchor, this);
  7299. }
  7300. }
  7301. }.bind(this));
  7302. dropOptions[outEvent] = _ju.wrap(dropOptions[outEvent], function () {
  7303. var draggable = _jp.getDragObject(arguments),
  7304. id = draggable == null ? null : _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
  7305. _jpc = id ? _jsPlumb.getFloatingConnectionFor(id) : null;
  7306. if (_jpc != null) {
  7307. var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
  7308. var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id);
  7309. if (_cont) {
  7310. this.removeClass(_jsPlumb.endpointDropAllowedClass);
  7311. this.removeClass(_jsPlumb.endpointDropForbiddenClass);
  7312. _jpc.endpoints[idx].anchor.out();
  7313. }
  7314. }
  7315. }.bind(this));
  7316. _jsPlumb.initDroppable(canvas, dropOptions, "internal", isTransient);
  7317. }
  7318. }.bind(this);
  7319. // Initialise the endpoint's canvas as a drop target. The drop handler will take care of the logic of whether
  7320. // something can actually be dropped.
  7321. if (!this.anchor.isFloating) {
  7322. _initDropTarget(this.canvas, !(params._transient || this.anchor.isFloating), this, params.reference);
  7323. }
  7324. return this;
  7325. };
  7326. _ju.extend(_jp.Endpoint, _jp.OverlayCapableJsPlumbUIComponent, {
  7327. setVisible: function (v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  7328. this._jsPlumb.visible = v;
  7329. if (this.canvas) {
  7330. this.canvas.style.display = v ? "block" : "none";
  7331. }
  7332. this[v ? "showOverlays" : "hideOverlays"]();
  7333. if (!doNotChangeConnections) {
  7334. for (var i = 0; i < this.connections.length; i++) {
  7335. this.connections[i].setVisible(v);
  7336. if (!doNotNotifyOtherEndpoint) {
  7337. var oIdx = this === this.connections[i].endpoints[0] ? 1 : 0;
  7338. // only change the other endpoint if this is its only connection.
  7339. if (this.connections[i].endpoints[oIdx].connections.length === 1) {
  7340. this.connections[i].endpoints[oIdx].setVisible(v, true, true);
  7341. }
  7342. }
  7343. }
  7344. }
  7345. },
  7346. getAttachedElements: function () {
  7347. return this.connections;
  7348. },
  7349. applyType: function (t, doNotRepaint) {
  7350. this.setPaintStyle(t.endpointStyle || t.paintStyle, doNotRepaint);
  7351. this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle, doNotRepaint);
  7352. if (t.maxConnections != null) {
  7353. this._jsPlumb.maxConnections = t.maxConnections;
  7354. }
  7355. if (t.scope) {
  7356. this.scope = t.scope;
  7357. }
  7358. _jp.extend(this, t, typeParameters);
  7359. if (t.cssClass != null && this.canvas) {
  7360. this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
  7361. }
  7362. _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
  7363. },
  7364. isEnabled: function () {
  7365. return this._jsPlumb.enabled;
  7366. },
  7367. setEnabled: function (e) {
  7368. this._jsPlumb.enabled = e;
  7369. },
  7370. cleanup: function () {
  7371. var anchorClass = this._jsPlumb.instance.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
  7372. _jp.removeClass(this.element, anchorClass);
  7373. this.anchor = null;
  7374. this.endpoint.cleanup(true);
  7375. this.endpoint.destroy();
  7376. this.endpoint = null;
  7377. // drag/drop
  7378. this._jsPlumb.instance.destroyDraggable(this.canvas, "internal");
  7379. this._jsPlumb.instance.destroyDroppable(this.canvas, "internal");
  7380. },
  7381. setHover: function (h) {
  7382. if (this.endpoint && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
  7383. this.endpoint.setHover(h);
  7384. }
  7385. },
  7386. isFull: function () {
  7387. return this._jsPlumb.maxConnections === 0 ? true : !(this.isFloating() || this._jsPlumb.maxConnections < 0 || this.connections.length < this._jsPlumb.maxConnections);
  7388. },
  7389. /**
  7390. * private but needs to be exposed.
  7391. */
  7392. isFloating: function () {
  7393. return this.anchor != null && this.anchor.isFloating;
  7394. },
  7395. isConnectedTo: function (endpoint) {
  7396. var found = false;
  7397. if (endpoint) {
  7398. for (var i = 0; i < this.connections.length; i++) {
  7399. if (this.connections[i].endpoints[1] === endpoint || this.connections[i].endpoints[0] === endpoint) {
  7400. found = true;
  7401. break;
  7402. }
  7403. }
  7404. }
  7405. return found;
  7406. },
  7407. getConnectionCost: function () {
  7408. return this._jsPlumb.connectionCost;
  7409. },
  7410. setConnectionCost: function (c) {
  7411. this._jsPlumb.connectionCost = c;
  7412. },
  7413. areConnectionsDirected: function () {
  7414. return this._jsPlumb.connectionsDirected;
  7415. },
  7416. setConnectionsDirected: function (b) {
  7417. this._jsPlumb.connectionsDirected = b;
  7418. },
  7419. setElementId: function (_elId) {
  7420. this.elementId = _elId;
  7421. this.anchor.elementId = _elId;
  7422. },
  7423. setReferenceElement: function (_el) {
  7424. this.element = _jp.getElement(_el);
  7425. },
  7426. setDragAllowedWhenFull: function (allowed) {
  7427. this.dragAllowedWhenFull = allowed;
  7428. },
  7429. equals: function (endpoint) {
  7430. return this.anchor.equals(endpoint.anchor);
  7431. },
  7432. getUuid: function () {
  7433. return this._jsPlumb.uuid;
  7434. },
  7435. computeAnchor: function (params) {
  7436. return this.anchor.compute(params);
  7437. }
  7438. });
  7439. root.jsPlumbInstance.prototype.EndpointDropHandler = function (dhParams) {
  7440. return function (e) {
  7441. var _jsPlumb = dhParams.jsPlumb;
  7442. // remove the classes that are added dynamically. drop is neither forbidden nor allowed now that
  7443. // the drop is finishing.
  7444. dhParams.removeClass(_jsPlumb.endpointDropAllowedClass);
  7445. dhParams.removeClass(_jsPlumb.endpointDropForbiddenClass);
  7446. var originalEvent = _jsPlumb.getDropEvent(arguments),
  7447. draggable = _jsPlumb.getDragObject(arguments),
  7448. id = _jsPlumb.getAttribute(draggable, "dragId"),
  7449. elId = _jsPlumb.getAttribute(draggable, "elId"),
  7450. scope = _jsPlumb.getAttribute(draggable, "originalScope"),
  7451. jpc = _jsPlumb.getFloatingConnectionFor(id);
  7452. // if no active connection, bail.
  7453. if (jpc == null) {
  7454. return;
  7455. }
  7456. // calculate if this is an existing connection.
  7457. var existingConnection = jpc.suspendedEndpoint != null;
  7458. // if suspended endpoint exists but has been cleaned up, bail. This means it's an existing connection
  7459. // that has been detached and will shortly be discarded.
  7460. if (existingConnection && jpc.suspendedEndpoint._jsPlumb == null) {
  7461. return;
  7462. }
  7463. // get the drop endpoint. for a normal connection this is just the one that would replace the currently
  7464. // floating endpoint. for a makeTarget this is a new endpoint that is created on drop. But we leave that to
  7465. // the handler to figure out.
  7466. var _ep = dhParams.getEndpoint(jpc);
  7467. // If we're not given an endpoint to use, bail.
  7468. if (_ep == null) {
  7469. return;
  7470. }
  7471. // if this is a drop back where the connection came from, mark it force reattach and
  7472. // return; the stop handler will reattach. without firing an event.
  7473. if (dhParams.isRedrop(jpc, dhParams)) {
  7474. jpc._forceReattach = true;
  7475. jpc.setHover(false);
  7476. if (dhParams.maybeCleanup) {
  7477. dhParams.maybeCleanup(_ep);
  7478. }
  7479. return;
  7480. }
  7481. // ensure we dont bother trying to drop sources on non-source eps, and same for target.
  7482. var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
  7483. if ((idx === 0 && !dhParams.isSource)|| (idx === 1 && !dhParams.isTarget)){
  7484. if (dhParams.maybeCleanup) {
  7485. dhParams.maybeCleanup(_ep);
  7486. }
  7487. return;
  7488. }
  7489. if (dhParams.onDrop) {
  7490. dhParams.onDrop(jpc);
  7491. }
  7492. // restore the original scope if necessary (issue 57)
  7493. if (scope) {
  7494. _jsPlumb.setDragScope(draggable, scope);
  7495. }
  7496. // if the target of the drop is full, fire an event (we abort below)
  7497. // makeTarget: keep.
  7498. var isFull = dhParams.isFull(e);
  7499. if (isFull) {
  7500. _ep.fire("maxConnections", {
  7501. endpoint: this,
  7502. connection: jpc,
  7503. maxConnections: _ep._jsPlumb.maxConnections
  7504. }, originalEvent);
  7505. }
  7506. //
  7507. // if endpoint enabled, not full, and matches the index of the floating endpoint...
  7508. if (!isFull && dhParams.enabled()) {
  7509. var _doContinue = true;
  7510. // before testing for beforeDrop, reset the connection's source/target to be the actual DOM elements
  7511. // involved (that is, stash any temporary stuff used for dragging. but we need to keep it around in
  7512. // order that the anchor manager can clean things up properly).
  7513. if (idx === 0) {
  7514. jpc.floatingElement = jpc.source;
  7515. jpc.floatingId = jpc.sourceId;
  7516. jpc.floatingEndpoint = jpc.endpoints[0];
  7517. jpc.floatingIndex = 0;
  7518. jpc.source = dhParams.element;
  7519. jpc.sourceId = dhParams.elementId;
  7520. } else {
  7521. jpc.floatingElement = jpc.target;
  7522. jpc.floatingId = jpc.targetId;
  7523. jpc.floatingEndpoint = jpc.endpoints[1];
  7524. jpc.floatingIndex = 1;
  7525. jpc.target = dhParams.element;
  7526. jpc.targetId = dhParams.elementId;
  7527. }
  7528. // if this is an existing connection and detach is not allowed we won't continue. The connection's
  7529. // endpoints have been reinstated; everything is back to how it was.
  7530. if (existingConnection && jpc.suspendedEndpoint.id !== _ep.id) {
  7531. if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc)) {
  7532. _doContinue = false;
  7533. }
  7534. }
  7535. // ------------ wrap the execution path in a function so we can support asynchronous beforeDrop
  7536. var continueFunction = function (optionalData) {
  7537. // remove this jpc from the current endpoint, which is a floating endpoint that we will
  7538. // subsequently discard.
  7539. jpc.endpoints[idx].detachFromConnection(jpc);
  7540. // if there's a suspended endpoint, detach it from the connection.
  7541. if (jpc.suspendedEndpoint) {
  7542. jpc.suspendedEndpoint.detachFromConnection(jpc);
  7543. }
  7544. jpc.endpoints[idx] = _ep;
  7545. _ep.addConnection(jpc);
  7546. // copy our parameters in to the connection:
  7547. var params = _ep.getParameters();
  7548. for (var aParam in params) {
  7549. jpc.setParameter(aParam, params[aParam]);
  7550. }
  7551. if (!existingConnection) {
  7552. // if not an existing connection and
  7553. if (params.draggable) {
  7554. _jsPlumb.initDraggable(this.element, dhParams.dragOptions, "internal", _jsPlumb);
  7555. }
  7556. }
  7557. else {
  7558. var suspendedElementId = jpc.suspendedEndpoint.elementId;
  7559. _jsPlumb.fireMoveEvent({
  7560. index: idx,
  7561. originalSourceId: idx === 0 ? suspendedElementId : jpc.sourceId,
  7562. newSourceId: idx === 0 ? _ep.elementId : jpc.sourceId,
  7563. originalTargetId: idx === 1 ? suspendedElementId : jpc.targetId,
  7564. newTargetId: idx === 1 ? _ep.elementId : jpc.targetId,
  7565. originalSourceEndpoint: idx === 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  7566. newSourceEndpoint: idx === 0 ? _ep : jpc.endpoints[0],
  7567. originalTargetEndpoint: idx === 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  7568. newTargetEndpoint: idx === 1 ? _ep : jpc.endpoints[1],
  7569. connection: jpc
  7570. }, originalEvent);
  7571. }
  7572. if (idx === 1) {
  7573. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
  7574. }
  7575. else {
  7576. _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
  7577. }
  7578. // when makeSource has uniqueEndpoint:true, we want to create connections with new endpoints
  7579. // that are subsequently deleted. So makeSource sets `finalEndpoint`, which is the Endpoint to
  7580. // which the connection should be attached. The `detachFromConnection` call below results in the
  7581. // temporary endpoint being cleaned up.
  7582. if (jpc.endpoints[0].finalEndpoint) {
  7583. var _toDelete = jpc.endpoints[0];
  7584. _toDelete.detachFromConnection(jpc);
  7585. jpc.endpoints[0] = jpc.endpoints[0].finalEndpoint;
  7586. jpc.endpoints[0].addConnection(jpc);
  7587. }
  7588. // if optionalData was given, merge it onto the connection's data.
  7589. if (_ju.isObject(optionalData)) {
  7590. jpc.mergeData(optionalData);
  7591. }
  7592. // finalise will inform the anchor manager and also add to
  7593. // connectionsByScope if necessary.
  7594. _jsPlumb.finaliseConnection(jpc, null, originalEvent, false);
  7595. jpc.setHover(false);
  7596. }.bind(this);
  7597. var dontContinueFunction = function () {
  7598. // otherwise just put it back on the endpoint it was on before the drag.
  7599. if (jpc.suspendedEndpoint) {
  7600. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  7601. jpc.setHover(false);
  7602. jpc._forceDetach = true;
  7603. if (idx === 0) {
  7604. jpc.source = jpc.suspendedEndpoint.element;
  7605. jpc.sourceId = jpc.suspendedEndpoint.elementId;
  7606. } else {
  7607. jpc.target = jpc.suspendedEndpoint.element;
  7608. jpc.targetId = jpc.suspendedEndpoint.elementId;
  7609. }
  7610. jpc.suspendedEndpoint.addConnection(jpc);
  7611. // TODO checkSanity
  7612. if (idx === 1) {
  7613. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
  7614. }
  7615. else {
  7616. _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
  7617. }
  7618. _jsPlumb.repaint(jpc.sourceId);
  7619. jpc._forceDetach = false;
  7620. }
  7621. };
  7622. // --------------------------------------
  7623. // now check beforeDrop. this will be available only on Endpoints that are setup to
  7624. // have a beforeDrop condition (although, secretly, under the hood all Endpoints and
  7625. // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
  7626. // it only makes sense to have it on a target endpoint.
  7627. _doContinue = _doContinue && dhParams.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, _ep);// && jpc.pending;
  7628. if (_doContinue) {
  7629. continueFunction(_doContinue);
  7630. return true;
  7631. }
  7632. else {
  7633. dontContinueFunction();
  7634. }
  7635. }
  7636. if (dhParams.maybeCleanup) {
  7637. dhParams.maybeCleanup(_ep);
  7638. }
  7639. _jsPlumb.currentlyDragging = false;
  7640. };
  7641. };
  7642. }).call(typeof window !== 'undefined' ? window : this);
  7643. /*
  7644. * This file contains the code for Connections.
  7645. *
  7646. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  7647. *
  7648. * https://jsplumbtoolkit.com
  7649. * https://github.com/jsplumb/jsplumb
  7650. *
  7651. * Dual licensed under the MIT and GPL2 licenses.
  7652. */
  7653. ;
  7654. (function () {
  7655. "use strict";
  7656. var root = this,
  7657. _jp = root.jsPlumb,
  7658. _ju = root.jsPlumbUtil;
  7659. var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) {
  7660. if (!_jsPlumb.Defaults.DoNotThrowErrors && _jp.Connectors[renderMode][connectorName] == null) {
  7661. throw { msg: "jsPlumb: unknown connector type '" + connectorName + "'" };
  7662. }
  7663. return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent);
  7664. },
  7665. _makeAnchor = function (anchorParams, elementId, _jsPlumb) {
  7666. return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null;
  7667. },
  7668. _updateConnectedClass = function (conn, element, _jsPlumb, remove) {
  7669. if (element != null) {
  7670. element._jsPlumbConnections = element._jsPlumbConnections || {};
  7671. if (remove) {
  7672. delete element._jsPlumbConnections[conn.id];
  7673. }
  7674. else {
  7675. element._jsPlumbConnections[conn.id] = true;
  7676. }
  7677. if (_ju.isEmpty(element._jsPlumbConnections)) {
  7678. _jsPlumb.removeClass(element, _jsPlumb.connectedClass);
  7679. }
  7680. else {
  7681. _jsPlumb.addClass(element, _jsPlumb.connectedClass);
  7682. }
  7683. }
  7684. };
  7685. _jp.Connection = function (params) {
  7686. var _newEndpoint = params.newEndpoint;
  7687. this.id = params.id;
  7688. this.connector = null;
  7689. this.idPrefix = "_jsplumb_c_";
  7690. this.defaultLabelLocation = 0.5;
  7691. this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
  7692. // if a new connection is the result of moving some existing connection, params.previousConnection
  7693. // will have that Connection in it. listeners for the jsPlumbConnection event can look for that
  7694. // member and take action if they need to.
  7695. this.previousConnection = params.previousConnection;
  7696. this.source = _jp.getElement(params.source);
  7697. this.target = _jp.getElement(params.target);
  7698. // sourceEndpoint and targetEndpoint override source/target, if they are present. but
  7699. // source is not overridden if the Endpoint has declared it is not the final target of a connection;
  7700. // instead we use the source that the Endpoint declares will be the final source element.
  7701. if (params.sourceEndpoint) {
  7702. this.source = params.sourceEndpoint.getElement();
  7703. }
  7704. if (params.targetEndpoint) {
  7705. this.target = params.targetEndpoint.getElement();
  7706. }
  7707. _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
  7708. this.sourceId = this._jsPlumb.instance.getId(this.source);
  7709. this.targetId = this._jsPlumb.instance.getId(this.target);
  7710. 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.
  7711. this.endpoints = [];
  7712. this.endpointStyles = [];
  7713. var _jsPlumb = this._jsPlumb.instance;
  7714. _jsPlumb.manage(this.sourceId, this.source);
  7715. _jsPlumb.manage(this.targetId, this.target);
  7716. this._jsPlumb.visible = true;
  7717. this._jsPlumb.editable = params.editable === true;
  7718. this._jsPlumb.params = {
  7719. cssClass: params.cssClass,
  7720. container: params.container,
  7721. "pointer-events": params["pointer-events"],
  7722. editorParams: params.editorParams,
  7723. overlays: params.overlays
  7724. };
  7725. this._jsPlumb.lastPaintedAt = null;
  7726. // listen to mouseover and mouseout events passed from the container delegate.
  7727. this.bind("mouseover", function () {
  7728. this.setHover(true);
  7729. }.bind(this));
  7730. this.bind("mouseout", function () {
  7731. this.setHover(false);
  7732. }.bind(this));
  7733. this.editableRequested = params.editable !== false;
  7734. this.setEditable = function(e) {
  7735. return this.connector ? this.connector.setEditable(e) : false;
  7736. };
  7737. this.isEditable = function() { return this.connector ? this.connector.isEditable() : false; };
  7738. this.isEditing = function() { return this.connector ? this.connector.isEditing() : false; };
  7739. // INITIALISATION CODE
  7740. this.makeEndpoint = function (isSource, el, elId, ep) {
  7741. elId = elId || this._jsPlumb.instance.getId(el);
  7742. return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId);
  7743. };
  7744. // if type given, get the endpoint definitions mapping to that type from the jsplumb instance, and use those.
  7745. // we apply types at the end of this constructor but endpoints are only honoured in a type definition at
  7746. // create time.
  7747. if (params.type) {
  7748. params.endpoints = params.endpoints || this._jsPlumb.instance.deriveEndpointAndAnchorSpec(params.type).endpoints;
  7749. }
  7750. var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint),
  7751. eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint);
  7752. if (eS) {
  7753. _ju.addToList(params.endpointsByElement, this.sourceId, eS);
  7754. }
  7755. if (eT) {
  7756. _ju.addToList(params.endpointsByElement, this.targetId, eT);
  7757. }
  7758. // if scope not set, set it to be the scope for the source endpoint.
  7759. if (!this.scope) {
  7760. this.scope = this.endpoints[0].scope;
  7761. }
  7762. // if explicitly told to (or not to) delete endpoints when empty, override endpoint's preferences
  7763. if (params.deleteEndpointsOnEmpty != null) {
  7764. this.endpoints[0].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
  7765. this.endpoints[1].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
  7766. }
  7767. // -------------------------- DEFAULT TYPE ---------------------------------------------
  7768. // DETACHABLE
  7769. var _detachable = _jsPlumb.Defaults.ConnectionsDetachable;
  7770. if (params.detachable === false) {
  7771. _detachable = false;
  7772. }
  7773. if (this.endpoints[0].connectionsDetachable === false) {
  7774. _detachable = false;
  7775. }
  7776. if (this.endpoints[1].connectionsDetachable === false) {
  7777. _detachable = false;
  7778. }
  7779. // REATTACH
  7780. var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections;
  7781. this.appendToDefaultType({
  7782. detachable: _detachable,
  7783. reattach: _reattach,
  7784. paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || _jp.Defaults.PaintStyle,
  7785. hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || _jp.Defaults.HoverPaintStyle
  7786. });
  7787. var _suspendedAt = _jsPlumb.getSuspendedAt();
  7788. if (!_jsPlumb.isSuspendDrawing()) {
  7789. // paint the endpoints
  7790. var myInfo = _jsPlumb.getCachedData(this.sourceId),
  7791. myOffset = myInfo.o, myWH = myInfo.s,
  7792. otherInfo = _jsPlumb.getCachedData(this.targetId),
  7793. otherOffset = otherInfo.o,
  7794. otherWH = otherInfo.s,
  7795. initialTimestamp = _suspendedAt || _jsPlumb.timestamp(),
  7796. anchorLoc = this.endpoints[0].anchor.compute({
  7797. xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0],
  7798. elementId: this.endpoints[0].elementId,
  7799. txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1],
  7800. timestamp: initialTimestamp
  7801. });
  7802. this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
  7803. anchorLoc = this.endpoints[1].anchor.compute({
  7804. xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1],
  7805. elementId: this.endpoints[1].elementId,
  7806. txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0],
  7807. timestamp: initialTimestamp
  7808. });
  7809. this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
  7810. }
  7811. this.getTypeDescriptor = function () {
  7812. return "connection";
  7813. };
  7814. this.getAttachedElements = function () {
  7815. return this.endpoints;
  7816. };
  7817. this.isDetachable = function () {
  7818. return this._jsPlumb.detachable === true;
  7819. };
  7820. this.setDetachable = function (detachable) {
  7821. this._jsPlumb.detachable = detachable === true;
  7822. };
  7823. this.isReattach = function () {
  7824. return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true;
  7825. };
  7826. this.setReattach = function (reattach) {
  7827. this._jsPlumb.reattach = reattach === true;
  7828. };
  7829. // END INITIALISATION CODE
  7830. // COST + DIRECTIONALITY
  7831. // if cost not supplied, try to inherit from source endpoint
  7832. this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost();
  7833. this._jsPlumb.directed = params.directed;
  7834. // inherit directed flag if set no source endpoint
  7835. if (params.directed == null) {
  7836. this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected();
  7837. }
  7838. // END COST + DIRECTIONALITY
  7839. // PARAMETERS
  7840. // merge all the parameters objects into the connection. parameters set
  7841. // on the connection take precedence; then source endpoint params, then
  7842. // finally target endpoint params.
  7843. var _p = _jp.extend({}, this.endpoints[1].getParameters());
  7844. _jp.extend(_p, this.endpoints[0].getParameters());
  7845. _jp.extend(_p, this.getParameters());
  7846. this.setParameters(_p);
  7847. // END PARAMETERS
  7848. // PAINTING
  7849. this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true);
  7850. if (params.geometry) {
  7851. this.connector.setGeometry(params.geometry);
  7852. }
  7853. var data = params.data == null || !_ju.isObject(params.data) ? {} : params.data;
  7854. this.getData = function() { return data; };
  7855. this.setData = function(d) { data = d || {}; };
  7856. this.mergeData = function(d) { data = _jp.extend(data, d); };
  7857. // the very last thing we do is apply types, if there are any.
  7858. var _types = [ "default", this.endpoints[0].connectionType, this.endpoints[1].connectionType, params.type ].join(" ");
  7859. if (/[^\s]/.test(_types)) {
  7860. this.addType(_types, params.data, true);
  7861. }
  7862. this.updateConnectedClass();
  7863. // END PAINTING
  7864. };
  7865. _ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, {
  7866. applyType: function (t, doNotRepaint, typeMap) {
  7867. var _connector = null;
  7868. if (t.connector != null) {
  7869. _connector = this.getCachedTypeItem("connector", typeMap.connector);
  7870. if (_connector == null) {
  7871. _connector = this.prepareConnector(t.connector, typeMap.connector);
  7872. this.cacheTypeItem("connector", _connector, typeMap.connector);
  7873. }
  7874. this.setPreparedConnector(_connector);
  7875. }
  7876. // none of these things result in the creation of objects so can be ignored.
  7877. if (t.detachable != null) {
  7878. this.setDetachable(t.detachable);
  7879. }
  7880. if (t.reattach != null) {
  7881. this.setReattach(t.reattach);
  7882. }
  7883. if (t.scope) {
  7884. this.scope = t.scope;
  7885. }
  7886. if (t.cssClass != null && this.canvas) {
  7887. this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
  7888. }
  7889. var _anchors = null;
  7890. // this also results in the creation of objects.
  7891. if (t.anchor) {
  7892. // note that even if the param was anchor, we store `anchors`.
  7893. _anchors = this.getCachedTypeItem("anchors", typeMap.anchor);
  7894. if (_anchors == null) {
  7895. _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ];
  7896. this.cacheTypeItem("anchors", _anchors, typeMap.anchor);
  7897. }
  7898. }
  7899. else if (t.anchors) {
  7900. _anchors = this.getCachedTypeItem("anchors", typeMap.anchors);
  7901. if (_anchors == null) {
  7902. _anchors = [
  7903. this._jsPlumb.instance.makeAnchor(t.anchors[0]),
  7904. this._jsPlumb.instance.makeAnchor(t.anchors[1])
  7905. ];
  7906. this.cacheTypeItem("anchors", _anchors, typeMap.anchors);
  7907. }
  7908. }
  7909. if (_anchors != null) {
  7910. this.endpoints[0].anchor = _anchors[0];
  7911. this.endpoints[1].anchor = _anchors[1];
  7912. if (this.endpoints[1].anchor.isDynamic) {
  7913. this._jsPlumb.instance.repaint(this.endpoints[1].elementId);
  7914. }
  7915. }
  7916. _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
  7917. },
  7918. addClass: function (c, informEndpoints) {
  7919. if (informEndpoints) {
  7920. this.endpoints[0].addClass(c);
  7921. this.endpoints[1].addClass(c);
  7922. if (this.suspendedEndpoint) {
  7923. this.suspendedEndpoint.addClass(c);
  7924. }
  7925. }
  7926. if (this.connector) {
  7927. this.connector.addClass(c);
  7928. }
  7929. },
  7930. removeClass: function (c, informEndpoints) {
  7931. if (informEndpoints) {
  7932. this.endpoints[0].removeClass(c);
  7933. this.endpoints[1].removeClass(c);
  7934. if (this.suspendedEndpoint) {
  7935. this.suspendedEndpoint.removeClass(c);
  7936. }
  7937. }
  7938. if (this.connector) {
  7939. this.connector.removeClass(c);
  7940. }
  7941. },
  7942. isVisible: function () {
  7943. return this._jsPlumb.visible;
  7944. },
  7945. setVisible: function (v) {
  7946. this._jsPlumb.visible = v;
  7947. if (this.connector) {
  7948. this.connector.setVisible(v);
  7949. }
  7950. this.repaint();
  7951. },
  7952. cleanup: function () {
  7953. this.updateConnectedClass(true);
  7954. this.endpoints = null;
  7955. this.source = null;
  7956. this.target = null;
  7957. if (this.connector != null) {
  7958. this.connector.cleanup(true);
  7959. this.connector.destroy(true);
  7960. }
  7961. this.connector = null;
  7962. },
  7963. updateConnectedClass:function(remove) {
  7964. if (this._jsPlumb) {
  7965. _updateConnectedClass(this, this.source, this._jsPlumb.instance, remove);
  7966. _updateConnectedClass(this, this.target, this._jsPlumb.instance, remove);
  7967. }
  7968. },
  7969. setHover: function (state) {
  7970. if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
  7971. this.connector.setHover(state);
  7972. root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass);
  7973. root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass);
  7974. }
  7975. },
  7976. getUuids:function() {
  7977. return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ];
  7978. },
  7979. getCost: function () {
  7980. return this._jsPlumb ? this._jsPlumb.cost : -Infinity;
  7981. },
  7982. setCost: function (c) {
  7983. this._jsPlumb.cost = c;
  7984. },
  7985. isDirected: function () {
  7986. return this._jsPlumb.directed;
  7987. },
  7988. getConnector: function () {
  7989. return this.connector;
  7990. },
  7991. getGeometry : function() {
  7992. return this.connector ? this.connector.getGeometry() : null;
  7993. },
  7994. setGeometry : function(g) {
  7995. if (this.connector) {
  7996. this.connector.setGeometry(g);
  7997. }
  7998. },
  7999. prepareConnector:function(connectorSpec, typeId) {
  8000. var connectorArgs = {
  8001. _jsPlumb: this._jsPlumb.instance,
  8002. cssClass: (this._jsPlumb.params.cssClass || "") + (this.isEditable() ? this._jsPlumb.instance.editableConnectorClass : ""),
  8003. container: this._jsPlumb.params.container,
  8004. "pointer-events": this._jsPlumb.params["pointer-events"],
  8005. editable:this.editableRequested
  8006. },
  8007. renderMode = this._jsPlumb.instance.getRenderMode(),
  8008. connector;
  8009. if (_ju.isString(connectorSpec)) {
  8010. connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this);
  8011. } // lets you use a string as shorthand.
  8012. else if (_ju.isArray(connectorSpec)) {
  8013. if (connectorSpec.length === 1) {
  8014. connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this);
  8015. }
  8016. else {
  8017. connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this);
  8018. }
  8019. }
  8020. if (typeId != null) {
  8021. connector.typeId = typeId;
  8022. }
  8023. return connector;
  8024. },
  8025. setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) {
  8026. if (this.connector !== connector) {
  8027. var previous, previousClasses = "";
  8028. // the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it
  8029. // and we havent passed in `true` for "force" here.
  8030. if (this.connector != null) {
  8031. previous = this.connector;
  8032. previousClasses = previous.getClass();
  8033. this.connector.cleanup();
  8034. this.connector.destroy();
  8035. }
  8036. this.connector = connector;
  8037. if (typeId) {
  8038. this.cacheTypeItem("connector", connector, typeId);
  8039. }
  8040. this.canvas = this.connector.canvas;
  8041. this.bgCanvas = this.connector.bgCanvas;
  8042. // put classes from prior connector onto the canvas
  8043. this.addClass(previousClasses);
  8044. // new: instead of binding listeners per connector, we now just have one delegate on the container.
  8045. // so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and
  8046. // bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards.
  8047. if (this.canvas) {
  8048. this.canvas._jsPlumb = this;
  8049. }
  8050. if (this.bgCanvas) {
  8051. this.bgCanvas._jsPlumb = this;
  8052. }
  8053. if (previous != null) {
  8054. var o = this.getOverlays();
  8055. for (var i = 0; i < o.length; i++) {
  8056. if (o[i].transfer) {
  8057. o[i].transfer(this.connector);
  8058. }
  8059. }
  8060. }
  8061. if (!doNotChangeListenerComponent) {
  8062. this.setListenerComponent(this.connector);
  8063. }
  8064. if (!doNotRepaint) {
  8065. this.repaint();
  8066. }
  8067. }
  8068. },
  8069. setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) {
  8070. var connector = this.prepareConnector(connectorSpec, typeId);
  8071. this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId);
  8072. },
  8073. paint: function (params) {
  8074. if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) {
  8075. params = params || {};
  8076. var timestamp = params.timestamp,
  8077. // if the moving object is not the source we must transpose the two references.
  8078. swap = false,
  8079. tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
  8080. tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  8081. if (timestamp == null || timestamp !== this._jsPlumb.lastPaintedAt) {
  8082. var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o,
  8083. targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o,
  8084. sE = this.endpoints[sIdx], tE = this.endpoints[tIdx];
  8085. var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}),
  8086. tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp});
  8087. this.connector.resetBounds();
  8088. this.connector.compute({
  8089. sourcePos: sAnchorP,
  8090. targetPos: tAnchorP,
  8091. sourceEndpoint: this.endpoints[sIdx],
  8092. targetEndpoint: this.endpoints[tIdx],
  8093. "stroke-width": this._jsPlumb.paintStyleInUse.strokeWidth,
  8094. sourceInfo: sourceInfo,
  8095. targetInfo: targetInfo
  8096. });
  8097. var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
  8098. // compute overlays. we do this first so we can get their placements, and adjust the
  8099. // container if needs be (if an overlay would be clipped)
  8100. for (var i in this._jsPlumb.overlays) {
  8101. if (this._jsPlumb.overlays.hasOwnProperty(i)) {
  8102. var o = this._jsPlumb.overlays[i];
  8103. if (o.isVisible()) {
  8104. this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o));
  8105. overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX);
  8106. overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX);
  8107. overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY);
  8108. overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY);
  8109. }
  8110. }
  8111. }
  8112. var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 1) / 2,
  8113. outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 0),
  8114. extents = {
  8115. xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX),
  8116. ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY),
  8117. xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX),
  8118. ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY)
  8119. };
  8120. // paint the connector.
  8121. this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents);
  8122. // and then the overlays
  8123. for (var j in this._jsPlumb.overlays) {
  8124. if (this._jsPlumb.overlays.hasOwnProperty(j)) {
  8125. var p = this._jsPlumb.overlays[j];
  8126. if (p.isVisible()) {
  8127. p.paint(this._jsPlumb.overlayPlacements[j], extents);
  8128. }
  8129. }
  8130. }
  8131. }
  8132. this._jsPlumb.lastPaintedAt = timestamp;
  8133. }
  8134. },
  8135. repaint: function (params) {
  8136. params = params || {};
  8137. this.paint({ elId: this.sourceId, recalc: !(params.recalc === false), timestamp: params.timestamp});
  8138. },
  8139. prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) {
  8140. var e;
  8141. if (existing) {
  8142. conn.endpoints[index] = existing;
  8143. existing.addConnection(conn);
  8144. } else {
  8145. if (!params.endpoints) {
  8146. params.endpoints = [ null, null ];
  8147. }
  8148. var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || _jp.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || _jp.Defaults.Endpoint;
  8149. if (!params.endpointStyles) {
  8150. params.endpointStyles = [ null, null ];
  8151. }
  8152. if (!params.endpointHoverStyles) {
  8153. params.endpointHoverStyles = [ null, null ];
  8154. }
  8155. var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || _jp.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle;
  8156. // Endpoints derive their fill from the connector's stroke, if no fill was specified.
  8157. if (es.fill == null && params.paintStyle != null) {
  8158. es.fill = params.paintStyle.stroke;
  8159. }
  8160. if (es.outlineStroke == null && params.paintStyle != null) {
  8161. es.outlineStroke = params.paintStyle.outlineStroke;
  8162. }
  8163. if (es.outlineWidth == null && params.paintStyle != null) {
  8164. es.outlineWidth = params.paintStyle.outlineWidth;
  8165. }
  8166. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || _jp.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle;
  8167. // endpoint hover fill style is derived from connector's hover stroke style
  8168. if (params.hoverPaintStyle != null) {
  8169. if (ehs == null) {
  8170. ehs = {};
  8171. }
  8172. if (ehs.fill == null) {
  8173. ehs.fill = params.hoverPaintStyle.stroke;
  8174. }
  8175. }
  8176. var a = params.anchors ? params.anchors[index] :
  8177. params.anchor ? params.anchor :
  8178. _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) ||
  8179. _makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) ||
  8180. _makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) ||
  8181. _makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb),
  8182. u = params.uuids ? params.uuids[index] : null;
  8183. e = _newEndpoint({
  8184. paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ],
  8185. uuid: u, anchor: a, source: element, scope: params.scope,
  8186. reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections,
  8187. detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable
  8188. });
  8189. if (existing == null) {
  8190. e.setDeleteOnEmpty(true);
  8191. }
  8192. conn.endpoints[index] = e;
  8193. if (params.drawEndpoints === false) {
  8194. e.setVisible(false, true, true);
  8195. }
  8196. }
  8197. return e;
  8198. }
  8199. }); // END Connection class
  8200. }).call(typeof window !== 'undefined' ? window : this);
  8201. /*
  8202. * This file contains the code for creating and manipulating anchors.
  8203. *
  8204. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  8205. *
  8206. * https://jsplumbtoolkit.com
  8207. * https://github.com/jsplumb/jsplumb
  8208. *
  8209. * Dual licensed under the MIT and GPL2 licenses.
  8210. */
  8211. ;
  8212. (function () {
  8213. "use strict";
  8214. var root = this,
  8215. _ju = root.jsPlumbUtil,
  8216. _jp = root.jsPlumb;
  8217. //
  8218. // manages anchors for all elements.
  8219. //
  8220. _jp.AnchorManager = function (params) {
  8221. var _amEndpoints = {},
  8222. continuousAnchorLocations = {},
  8223. userDefinedContinuousAnchorLocations = {},
  8224. continuousAnchorOrientations = {},
  8225. Orientation = { HORIZONTAL: "horizontal", VERTICAL: "vertical", DIAGONAL: "diagonal", IDENTITY: "identity" },
  8226. axes = ["left", "top", "right", "bottom"],
  8227. connectionsByElementId = {},
  8228. self = this,
  8229. anchorLists = {},
  8230. jsPlumbInstance = params.jsPlumbInstance,
  8231. floatingConnections = {},
  8232. calculateOrientation = function (sourceId, targetId, sd, td, sourceAnchor, targetAnchor) {
  8233. if (sourceId === targetId) {
  8234. return {
  8235. orientation: Orientation.IDENTITY,
  8236. a: ["top", "top"]
  8237. };
  8238. }
  8239. var theta = Math.atan2((td.centery - sd.centery), (td.centerx - sd.centerx)),
  8240. theta2 = Math.atan2((sd.centery - td.centery), (sd.centerx - td.centerx));
  8241. // --------------------------------------------------------------------------------------
  8242. // improved face calculation. get midpoints of each face for source and target, then put in an array with all combinations of
  8243. // source/target faces. sort this array by distance between midpoints. the entry at index 0 is our preferred option. we can
  8244. // go through the array one by one until we find an entry in which each requested face is supported.
  8245. var candidates = [], midpoints = { };
  8246. (function (types, dim) {
  8247. for (var i = 0; i < types.length; i++) {
  8248. midpoints[types[i]] = {
  8249. "left": [ dim[i].left, dim[i].centery ],
  8250. "right": [ dim[i].right, dim[i].centery ],
  8251. "top": [ dim[i].centerx, dim[i].top ],
  8252. "bottom": [ dim[i].centerx , dim[i].bottom]
  8253. };
  8254. }
  8255. })([ "source", "target" ], [ sd, td ]);
  8256. for (var sf = 0; sf < axes.length; sf++) {
  8257. for (var tf = 0; tf < axes.length; tf++) {
  8258. candidates.push({
  8259. source: axes[sf],
  8260. target: axes[tf],
  8261. dist: Biltong.lineLength(midpoints.source[axes[sf]], midpoints.target[axes[tf]])
  8262. });
  8263. }
  8264. }
  8265. candidates.sort(function (a, b) {
  8266. return a.dist < b.dist ? -1 : a.dist > b.dist ? 1 : 0;
  8267. });
  8268. // now go through this list and try to get an entry that satisfies both (there will be one, unless one of the anchors
  8269. // declares no available faces)
  8270. var sourceEdge = candidates[0].source, targetEdge = candidates[0].target;
  8271. for (var i = 0; i < candidates.length; i++) {
  8272. if (!sourceAnchor.isContinuous || sourceAnchor.isEdgeSupported(candidates[i].source)) {
  8273. sourceEdge = candidates[i].source;
  8274. }
  8275. else {
  8276. sourceEdge = null;
  8277. }
  8278. if (!targetAnchor.isContinuous || targetAnchor.isEdgeSupported(candidates[i].target)) {
  8279. targetEdge = candidates[i].target;
  8280. }
  8281. else {
  8282. targetEdge = null;
  8283. }
  8284. if (sourceEdge != null && targetEdge != null) {
  8285. break;
  8286. }
  8287. }
  8288. if (sourceAnchor.isContinuous) {
  8289. sourceAnchor.setCurrentFace(sourceEdge);
  8290. }
  8291. if (targetAnchor.isContinuous) {
  8292. targetAnchor.setCurrentFace(targetEdge);
  8293. }
  8294. // --------------------------------------------------------------------------------------
  8295. return {
  8296. a: [ sourceEdge, targetEdge ],
  8297. theta: theta,
  8298. theta2: theta2
  8299. };
  8300. },
  8301. // used by placeAnchors function
  8302. placeAnchorsOnLine = function (desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) {
  8303. var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
  8304. for (var i = 0; i < connections.length; i++) {
  8305. var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
  8306. if (reverse) {
  8307. val = elementDimensions[horizontal ? 0 : 1] - val;
  8308. }
  8309. var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
  8310. dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
  8311. a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
  8312. }
  8313. return a;
  8314. },
  8315. // used by edgeSortFunctions
  8316. currySort = function (reverseAngles) {
  8317. return function (a, b) {
  8318. var r = true;
  8319. if (reverseAngles) {
  8320. r = a[0][0] < b[0][0];
  8321. }
  8322. else {
  8323. r = a[0][0] > b[0][0];
  8324. }
  8325. return r === false ? -1 : 1;
  8326. };
  8327. },
  8328. // used by edgeSortFunctions
  8329. leftSort = function (a, b) {
  8330. // first get adjusted values
  8331. var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
  8332. p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
  8333. if (p1 > p2) {
  8334. return 1;
  8335. }
  8336. else {
  8337. return -1;
  8338. }
  8339. },
  8340. // used by placeAnchors
  8341. edgeSortFunctions = {
  8342. "top": function (a, b) {
  8343. return a[0] > b[0] ? 1 : -1;
  8344. },
  8345. "right": currySort(true),
  8346. "bottom": currySort(true),
  8347. "left": leftSort
  8348. },
  8349. // used by placeAnchors
  8350. _sortHelper = function (_array, _fn) {
  8351. return _array.sort(_fn);
  8352. },
  8353. // used by AnchorManager.redraw
  8354. placeAnchors = function (elementId, _anchorLists) {
  8355. var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o,
  8356. placeSomeAnchors = function (desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) {
  8357. if (unsortedConnections.length > 0) {
  8358. var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
  8359. reverse = desc === "right" || desc === "top",
  8360. anchors = placeAnchorsOnLine(desc, elementDimensions,
  8361. elementPosition, sc,
  8362. isHorizontal, otherMultiplier, reverse);
  8363. // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
  8364. var _setAnchorLocation = function (endpoint, anchorPos) {
  8365. continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ];
  8366. continuousAnchorOrientations[endpoint.id] = orientation;
  8367. };
  8368. for (var i = 0; i < anchors.length; i++) {
  8369. var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
  8370. if (weAreSource) {
  8371. _setAnchorLocation(c.endpoints[0], anchors[i]);
  8372. }
  8373. if (weAreTarget) {
  8374. _setAnchorLocation(c.endpoints[1], anchors[i]);
  8375. }
  8376. }
  8377. }
  8378. };
  8379. placeSomeAnchors("bottom", sS, [sO.left, sO.top], _anchorLists.bottom, true, 1, [0, 1]);
  8380. placeSomeAnchors("top", sS, [sO.left, sO.top], _anchorLists.top, true, 0, [0, -1]);
  8381. placeSomeAnchors("left", sS, [sO.left, sO.top], _anchorLists.left, false, 0, [-1, 0]);
  8382. placeSomeAnchors("right", sS, [sO.left, sO.top], _anchorLists.right, false, 1, [1, 0]);
  8383. };
  8384. this.reset = function () {
  8385. _amEndpoints = {};
  8386. connectionsByElementId = {};
  8387. anchorLists = {};
  8388. };
  8389. this.addFloatingConnection = function (key, conn) {
  8390. floatingConnections[key] = conn;
  8391. };
  8392. this.removeFloatingConnection = function (key) {
  8393. delete floatingConnections[key];
  8394. };
  8395. this.newConnection = function (conn) {
  8396. var sourceId = conn.sourceId, targetId = conn.targetId,
  8397. ep = conn.endpoints,
  8398. doRegisterTarget = true,
  8399. registerConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
  8400. if ((sourceId === targetId) && otherAnchor.isContinuous) {
  8401. // remove the target endpoint's canvas. we dont need it.
  8402. conn._jsPlumb.instance.removeElement(ep[1].canvas);
  8403. doRegisterTarget = false;
  8404. }
  8405. _ju.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor === _jp.DynamicAnchor]);
  8406. };
  8407. registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
  8408. if (doRegisterTarget) {
  8409. registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
  8410. }
  8411. };
  8412. var removeEndpointFromAnchorLists = function (endpoint) {
  8413. (function (list, eId) {
  8414. if (list) { // transient anchors dont get entries in this list.
  8415. var f = function (e) {
  8416. return e[4] === eId;
  8417. };
  8418. _ju.removeWithFunction(list.top, f);
  8419. _ju.removeWithFunction(list.left, f);
  8420. _ju.removeWithFunction(list.bottom, f);
  8421. _ju.removeWithFunction(list.right, f);
  8422. }
  8423. })(anchorLists[endpoint.elementId], endpoint.id);
  8424. };
  8425. this.connectionDetached = function (connInfo, doNotRedraw) {
  8426. var connection = connInfo.connection || connInfo,
  8427. sourceId = connInfo.sourceId,
  8428. targetId = connInfo.targetId,
  8429. ep = connection.endpoints,
  8430. removeConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
  8431. _ju.removeWithFunction(connectionsByElementId[elId], function (_c) {
  8432. return _c[0].id === c.id;
  8433. });
  8434. };
  8435. removeConnection(1, ep[1], ep[1].anchor, sourceId, connection);
  8436. removeConnection(0, ep[0], ep[0].anchor, targetId, connection);
  8437. if (connection.floatingId) {
  8438. removeConnection(connection.floatingIndex, connection.floatingEndpoint, connection.floatingEndpoint.anchor, connection.floatingId, connection);
  8439. removeEndpointFromAnchorLists(connection.floatingEndpoint);
  8440. }
  8441. // remove from anchorLists
  8442. removeEndpointFromAnchorLists(connection.endpoints[0]);
  8443. removeEndpointFromAnchorLists(connection.endpoints[1]);
  8444. if (!doNotRedraw) {
  8445. self.redraw(connection.sourceId);
  8446. if (connection.targetId !== connection.sourceId) {
  8447. self.redraw(connection.targetId);
  8448. }
  8449. }
  8450. };
  8451. this.add = function (endpoint, elementId) {
  8452. _ju.addToList(_amEndpoints, elementId, endpoint);
  8453. };
  8454. this.changeId = function (oldId, newId) {
  8455. connectionsByElementId[newId] = connectionsByElementId[oldId];
  8456. _amEndpoints[newId] = _amEndpoints[oldId];
  8457. delete connectionsByElementId[oldId];
  8458. delete _amEndpoints[oldId];
  8459. };
  8460. this.getConnectionsFor = function (elementId) {
  8461. return connectionsByElementId[elementId] || [];
  8462. };
  8463. this.getEndpointsFor = function (elementId) {
  8464. return _amEndpoints[elementId] || [];
  8465. };
  8466. this.deleteEndpoint = function (endpoint) {
  8467. _ju.removeWithFunction(_amEndpoints[endpoint.elementId], function (e) {
  8468. return e.id === endpoint.id;
  8469. });
  8470. removeEndpointFromAnchorLists(endpoint);
  8471. };
  8472. this.clearFor = function (elementId) {
  8473. delete _amEndpoints[elementId];
  8474. _amEndpoints[elementId] = [];
  8475. };
  8476. // updates the given anchor list by either updating an existing anchor's info, or adding it. this function
  8477. // also removes the anchor from its previous list, if the edge it is on has changed.
  8478. // all connections found along the way (those that are connected to one of the faces this function
  8479. // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
  8480. // them wthout having to calculate anything else about them.
  8481. var _updateAnchorList = function (lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
  8482. // first try to find the exact match, but keep track of the first index of a matching element id along the way.s
  8483. var exactIdx = -1,
  8484. firstMatchingElIdx = -1,
  8485. endpoint = conn.endpoints[idx],
  8486. endpointId = endpoint.id,
  8487. oIdx = [1, 0][idx],
  8488. values = [
  8489. [ theta, order ],
  8490. conn,
  8491. aBoolean,
  8492. otherElId,
  8493. endpointId
  8494. ],
  8495. listToAddTo = lists[edgeId],
  8496. listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null,
  8497. i,
  8498. candidate;
  8499. if (listToRemoveFrom) {
  8500. var rIdx = _ju.findWithFunction(listToRemoveFrom, function (e) {
  8501. return e[4] === endpointId;
  8502. });
  8503. if (rIdx !== -1) {
  8504. listToRemoveFrom.splice(rIdx, 1);
  8505. // get all connections from this list
  8506. for (i = 0; i < listToRemoveFrom.length; i++) {
  8507. candidate = listToRemoveFrom[i][1];
  8508. _ju.addWithFunction(connsToPaint, candidate, function (c) {
  8509. return c.id === candidate.id;
  8510. });
  8511. _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function (e) {
  8512. return e.id === candidate.endpoints[idx].id;
  8513. });
  8514. _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function (e) {
  8515. return e.id === candidate.endpoints[oIdx].id;
  8516. });
  8517. }
  8518. }
  8519. }
  8520. for (i = 0; i < listToAddTo.length; i++) {
  8521. candidate = listToAddTo[i][1];
  8522. if (params.idx === 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx === -1) {
  8523. firstMatchingElIdx = i;
  8524. }
  8525. _ju.addWithFunction(connsToPaint, candidate, function (c) {
  8526. return c.id === candidate.id;
  8527. });
  8528. _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function (e) {
  8529. return e.id === candidate.endpoints[idx].id;
  8530. });
  8531. _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function (e) {
  8532. return e.id === candidate.endpoints[oIdx].id;
  8533. });
  8534. }
  8535. if (exactIdx !== -1) {
  8536. listToAddTo[exactIdx] = values;
  8537. }
  8538. else {
  8539. var insertIdx = reverse ? firstMatchingElIdx !== -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
  8540. listToAddTo.splice(insertIdx, 0, values);
  8541. }
  8542. // store this for next time.
  8543. endpoint._continuousAnchorEdge = edgeId;
  8544. };
  8545. //
  8546. // find the entry in an endpoint's list for this connection and update its target endpoint
  8547. // with the current target in the connection.
  8548. // This method and sourceChanged need to be folder into one.
  8549. //
  8550. this.updateOtherEndpoint = function (sourceElId, oldTargetId, newTargetId, connection) {
  8551. var sIndex = _ju.findWithFunction(connectionsByElementId[sourceElId], function (i) {
  8552. return i[0].id === connection.id;
  8553. }),
  8554. tIndex = _ju.findWithFunction(connectionsByElementId[oldTargetId], function (i) {
  8555. return i[0].id === connection.id;
  8556. });
  8557. // update or add data for source
  8558. if (sIndex !== -1) {
  8559. connectionsByElementId[sourceElId][sIndex][0] = connection;
  8560. connectionsByElementId[sourceElId][sIndex][1] = connection.endpoints[1];
  8561. connectionsByElementId[sourceElId][sIndex][2] = connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor;
  8562. }
  8563. // remove entry for previous target (if there)
  8564. if (tIndex > -1) {
  8565. connectionsByElementId[oldTargetId].splice(tIndex, 1);
  8566. // add entry for new target
  8567. _ju.addToList(connectionsByElementId, newTargetId, [connection, connection.endpoints[0], connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor]);
  8568. }
  8569. connection.updateConnectedClass();
  8570. };
  8571. //
  8572. // notification that the connection given has changed source from the originalId to the newId.
  8573. // This involves:
  8574. // 1. removing the connection from the list of connections stored for the originalId
  8575. // 2. updating the source information for the target of the connection
  8576. // 3. re-registering the connection in connectionsByElementId with the newId
  8577. //
  8578. this.sourceChanged = function (originalId, newId, connection, newElement) {
  8579. if (originalId !== newId) {
  8580. connection.sourceId = newId;
  8581. connection.source = newElement;
  8582. // remove the entry that points from the old source to the target
  8583. _ju.removeWithFunction(connectionsByElementId[originalId], function (info) {
  8584. return info[0].id === connection.id;
  8585. });
  8586. // find entry for target and update it
  8587. var tIdx = _ju.findWithFunction(connectionsByElementId[connection.targetId], function (i) {
  8588. return i[0].id === connection.id;
  8589. });
  8590. if (tIdx > -1) {
  8591. connectionsByElementId[connection.targetId][tIdx][0] = connection;
  8592. connectionsByElementId[connection.targetId][tIdx][1] = connection.endpoints[0];
  8593. connectionsByElementId[connection.targetId][tIdx][2] = connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor;
  8594. }
  8595. // add entry for new source
  8596. _ju.addToList(connectionsByElementId, newId, [connection, connection.endpoints[1], connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor]);
  8597. // TODO SP not final on this yet. when a user drags an existing connection and it turns into a self
  8598. // loop, then this code hides the target endpoint (by removing it from the DOM) But I think this should
  8599. // occur only if the anchor is Continuous
  8600. if (connection.endpoints[1].anchor.isContinuous) {
  8601. if (connection.source === connection.target) {
  8602. connection._jsPlumb.instance.removeElement(connection.endpoints[1].canvas);
  8603. }
  8604. else {
  8605. if (connection.endpoints[1].canvas.parentNode == null) {
  8606. connection._jsPlumb.instance.appendElement(connection.endpoints[1].canvas);
  8607. }
  8608. }
  8609. }
  8610. connection.updateConnectedClass();
  8611. }
  8612. };
  8613. //
  8614. // moves the given endpoint from `currentId` to `element`.
  8615. // This involves:
  8616. //
  8617. // 1. changing the key in _amEndpoints under which the endpoint is stored
  8618. // 2. changing the source or target values in all of the endpoint's connections
  8619. // 3. changing the array in connectionsByElementId in which the endpoint's connections
  8620. // are stored (done by either sourceChanged or updateOtherEndpoint)
  8621. //
  8622. this.rehomeEndpoint = function (ep, currentId, element) {
  8623. var eps = _amEndpoints[currentId] || [],
  8624. elementId = jsPlumbInstance.getId(element);
  8625. if (elementId !== currentId) {
  8626. var idx = eps.indexOf(ep);
  8627. if (idx > -1) {
  8628. var _ep = eps.splice(idx, 1)[0];
  8629. self.add(_ep, elementId);
  8630. }
  8631. }
  8632. for (var i = 0; i < ep.connections.length; i++) {
  8633. if (ep.connections[i].sourceId === currentId) {
  8634. self.sourceChanged(currentId, ep.elementId, ep.connections[i], ep.element);
  8635. }
  8636. else if (ep.connections[i].targetId === currentId) {
  8637. ep.connections[i].targetId = ep.elementId;
  8638. ep.connections[i].target = ep.element;
  8639. self.updateOtherEndpoint(ep.connections[i].sourceId, currentId, ep.elementId, ep.connections[i]);
  8640. }
  8641. }
  8642. };
  8643. this.redraw = function (elementId, ui, timestamp, offsetToUI, clearEdits, doNotRecalcEndpoint) {
  8644. if (!jsPlumbInstance.isSuspendDrawing()) {
  8645. // get all the endpoints for this element
  8646. var ep = _amEndpoints[elementId] || [],
  8647. endpointConnections = connectionsByElementId[elementId] || [],
  8648. connectionsToPaint = [],
  8649. endpointsToPaint = [],
  8650. anchorsToUpdate = [];
  8651. timestamp = timestamp || jsPlumbInstance.timestamp();
  8652. // offsetToUI are values that would have been calculated in the dragManager when registering
  8653. // an endpoint for an element that had a parent (somewhere in the hierarchy) that had been
  8654. // registered as draggable.
  8655. offsetToUI = offsetToUI || {left: 0, top: 0};
  8656. if (ui) {
  8657. ui = {
  8658. left: ui.left + offsetToUI.left,
  8659. top: ui.top + offsetToUI.top
  8660. };
  8661. }
  8662. // valid for one paint cycle.
  8663. var myOffset = jsPlumbInstance.updateOffset({ elId: elementId, offset: ui, recalc: false, timestamp: timestamp }),
  8664. orientationCache = {};
  8665. // actually, first we should compute the orientation of this element to all other elements to which
  8666. // this element is connected with a continuous anchor (whether both ends of the connection have
  8667. // a continuous anchor or just one)
  8668. for (var i = 0; i < endpointConnections.length; i++) {
  8669. var conn = endpointConnections[i][0],
  8670. sourceId = conn.sourceId,
  8671. targetId = conn.targetId,
  8672. sourceContinuous = conn.endpoints[0].anchor.isContinuous,
  8673. targetContinuous = conn.endpoints[1].anchor.isContinuous;
  8674. if (sourceContinuous || targetContinuous) {
  8675. var oKey = sourceId + "_" + targetId,
  8676. o = orientationCache[oKey],
  8677. oIdx = conn.sourceId === elementId ? 1 : 0;
  8678. if (sourceContinuous && !anchorLists[sourceId]) {
  8679. anchorLists[sourceId] = { top: [], right: [], bottom: [], left: [] };
  8680. }
  8681. if (targetContinuous && !anchorLists[targetId]) {
  8682. anchorLists[targetId] = { top: [], right: [], bottom: [], left: [] };
  8683. }
  8684. if (elementId !== targetId) {
  8685. jsPlumbInstance.updateOffset({ elId: targetId, timestamp: timestamp });
  8686. }
  8687. if (elementId !== sourceId) {
  8688. jsPlumbInstance.updateOffset({ elId: sourceId, timestamp: timestamp });
  8689. }
  8690. var td = jsPlumbInstance.getCachedData(targetId),
  8691. sd = jsPlumbInstance.getCachedData(sourceId);
  8692. if (targetId === sourceId && (sourceContinuous || targetContinuous)) {
  8693. // here we may want to improve this by somehow determining the face we'd like
  8694. // to put the connector on. ideally, when drawing, the face should be calculated
  8695. // by determining which face is closest to the point at which the mouse button
  8696. // was released. for now, we're putting it on the top face.
  8697. _updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint);
  8698. _updateAnchorList( anchorLists[targetId], -Math.PI / 2, 0, conn, false, sourceId, 1, false, "top", targetId, connectionsToPaint, endpointsToPaint);
  8699. }
  8700. else {
  8701. if (!o) {
  8702. o = calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor);
  8703. orientationCache[oKey] = o;
  8704. // this would be a performance enhancement, but the computed angles need to be clamped to
  8705. //the (-PI/2 -> PI/2) range in order for the sorting to work properly.
  8706. /* orientationCache[oKey2] = {
  8707. orientation:o.orientation,
  8708. a:[o.a[1], o.a[0]],
  8709. theta:o.theta + Math.PI,
  8710. theta2:o.theta2 + Math.PI
  8711. };*/
  8712. }
  8713. if (sourceContinuous) {
  8714. _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
  8715. }
  8716. if (targetContinuous) {
  8717. _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
  8718. }
  8719. }
  8720. if (sourceContinuous) {
  8721. _ju.addWithFunction(anchorsToUpdate, sourceId, function (a) {
  8722. return a === sourceId;
  8723. });
  8724. }
  8725. if (targetContinuous) {
  8726. _ju.addWithFunction(anchorsToUpdate, targetId, function (a) {
  8727. return a === targetId;
  8728. });
  8729. }
  8730. _ju.addWithFunction(connectionsToPaint, conn, function (c) {
  8731. return c.id === conn.id;
  8732. });
  8733. if ((sourceContinuous && oIdx === 0) || (targetContinuous && oIdx === 1)) {
  8734. _ju.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function (e) {
  8735. return e.id === conn.endpoints[oIdx].id;
  8736. });
  8737. }
  8738. }
  8739. }
  8740. // place Endpoints whose anchors are continuous but have no Connections
  8741. for (i = 0; i < ep.length; i++) {
  8742. if (ep[i].connections.length === 0 && ep[i].anchor.isContinuous) {
  8743. if (!anchorLists[elementId]) {
  8744. anchorLists[elementId] = { top: [], right: [], bottom: [], left: [] };
  8745. }
  8746. _updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints: [ep[i], ep[i]], paint: function () {
  8747. }}, false, elementId, 0, false, ep[i].anchor.getDefaultFace(), elementId, connectionsToPaint, endpointsToPaint);
  8748. _ju.addWithFunction(anchorsToUpdate, elementId, function (a) {
  8749. return a === elementId;
  8750. });
  8751. }
  8752. }
  8753. // now place all the continuous anchors we need to;
  8754. for (i = 0; i < anchorsToUpdate.length; i++) {
  8755. placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]);
  8756. }
  8757. // now that continuous anchors have been placed, paint all the endpoints for this element
  8758. // TODO performance: add the endpoint ids to a temp array, and then when iterating in the next
  8759. // loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way.
  8760. for (i = 0; i < ep.length; i++) {
  8761. ep[i].paint({ timestamp: timestamp, offset: myOffset, dimensions: myOffset.s, recalc: doNotRecalcEndpoint !== true });
  8762. }
  8763. // ... and any other endpoints we came across as a result of the continuous anchors.
  8764. for (i = 0; i < endpointsToPaint.length; i++) {
  8765. var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId);
  8766. endpointsToPaint[i].paint({ timestamp: timestamp, offset: cd, dimensions: cd.s });
  8767. }
  8768. // paint all the standard and "dynamic connections", which are connections whose other anchor is
  8769. // static and therefore does need to be recomputed; we make sure that happens only one time.
  8770. // TODO we could have compiled a list of these in the first pass through connections; might save some time.
  8771. for (i = 0; i < endpointConnections.length; i++) {
  8772. var otherEndpoint = endpointConnections[i][1];
  8773. if (otherEndpoint.anchor.constructor === _jp.DynamicAnchor) {
  8774. otherEndpoint.paint({ elementWithPrecedence: elementId, timestamp: timestamp });
  8775. _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
  8776. return c.id === endpointConnections[i][0].id;
  8777. });
  8778. // all the connections for the other endpoint now need to be repainted
  8779. for (var k = 0; k < otherEndpoint.connections.length; k++) {
  8780. if (otherEndpoint.connections[k] !== endpointConnections[i][0]) {
  8781. _ju.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function (c) {
  8782. return c.id === otherEndpoint.connections[k].id;
  8783. });
  8784. }
  8785. }
  8786. } else {
  8787. _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
  8788. return c.id === endpointConnections[i][0].id;
  8789. });
  8790. }
  8791. }
  8792. // paint current floating connection for this element, if there is one.
  8793. var fc = floatingConnections[elementId];
  8794. if (fc) {
  8795. fc.paint({timestamp: timestamp, recalc: false, elId: elementId});
  8796. }
  8797. // paint all the connections
  8798. for (i = 0; i < connectionsToPaint.length; i++) {
  8799. connectionsToPaint[i].paint({elId: elementId, timestamp: timestamp, recalc: false, clearEdits: clearEdits});
  8800. }
  8801. }
  8802. };
  8803. var ContinuousAnchor = function (anchorParams) {
  8804. _ju.EventGenerator.apply(this);
  8805. this.type = "Continuous";
  8806. this.isDynamic = true;
  8807. this.isContinuous = true;
  8808. var faces = anchorParams.faces || ["top", "right", "bottom", "left"],
  8809. clockwise = !(anchorParams.clockwise === false),
  8810. availableFaces = { },
  8811. opposites = { "top": "bottom", "right": "left", "left": "right", "bottom": "top" },
  8812. clockwiseOptions = { "top": "right", "right": "bottom", "left": "top", "bottom": "left" },
  8813. antiClockwiseOptions = { "top": "left", "right": "top", "left": "bottom", "bottom": "right" },
  8814. secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions,
  8815. lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions,
  8816. cssClass = anchorParams.cssClass || "",
  8817. _currentFace = null, _lockedFace = null, X_AXIS_FACES = ["left", "right"], Y_AXIS_FACES = ["top", "bottom"],
  8818. _lockedAxis = null;
  8819. for (var i = 0; i < faces.length; i++) {
  8820. availableFaces[faces[i]] = true;
  8821. }
  8822. this.getDefaultFace = function () {
  8823. return faces.length === 0 ? "top" : faces[0];
  8824. };
  8825. // if the given edge is supported, returns it. otherwise looks for a substitute that _is_
  8826. // supported. if none supported we also return the request edge.
  8827. this.verifyEdge = function (edge) {
  8828. if (availableFaces[edge]) {
  8829. return edge;
  8830. }
  8831. else if (availableFaces[opposites[edge]]) {
  8832. return opposites[edge];
  8833. }
  8834. else if (availableFaces[secondBest[edge]]) {
  8835. return secondBest[edge];
  8836. }
  8837. else if (availableFaces[lastChoice[edge]]) {
  8838. return lastChoice[edge];
  8839. }
  8840. return edge; // we have to give them something.
  8841. };
  8842. this.isEdgeSupported = function (edge) {
  8843. return _lockedAxis == null ?
  8844. (_lockedFace == null ? availableFaces[edge] === true : _lockedFace === edge)
  8845. : _lockedAxis.indexOf(edge) !== -1;
  8846. };
  8847. this.setCurrentFace = function(face) {
  8848. _currentFace = face;
  8849. };
  8850. this.getCurrentFace = function() { return _currentFace; };
  8851. this.lockCurrentFace = function() {
  8852. _lockedFace = _currentFace;
  8853. };
  8854. this.unlockCurrentFace = function() { _lockedFace = null; };
  8855. this.lockCurrentAxis = function() {
  8856. if (_currentFace != null) {
  8857. _lockedAxis = (_currentFace === "left" || _currentFace === "right") ? X_AXIS_FACES : Y_AXIS_FACES;
  8858. }
  8859. };
  8860. this.unlockCurrentAxis = function() {
  8861. _lockedAxis = null;
  8862. };
  8863. this.compute = function (params) {
  8864. return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0];
  8865. };
  8866. this.getCurrentLocation = function (params) {
  8867. return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0];
  8868. };
  8869. this.getOrientation = function (endpoint) {
  8870. return continuousAnchorOrientations[endpoint.id] || [0, 0];
  8871. };
  8872. this.clearUserDefinedLocation = function () {
  8873. delete userDefinedContinuousAnchorLocations[anchorParams.elementId];
  8874. };
  8875. this.setUserDefinedLocation = function (loc) {
  8876. userDefinedContinuousAnchorLocations[anchorParams.elementId] = loc;
  8877. };
  8878. this.getCssClass = function () {
  8879. return cssClass;
  8880. };
  8881. };
  8882. // continuous anchors
  8883. jsPlumbInstance.continuousAnchorFactory = {
  8884. get: function (params) {
  8885. return new ContinuousAnchor(params);
  8886. },
  8887. clear: function (elementId) {
  8888. delete userDefinedContinuousAnchorLocations[elementId];
  8889. delete continuousAnchorLocations[elementId];
  8890. }
  8891. };
  8892. };
  8893. /**
  8894. * 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
  8895. * 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"),
  8896. * 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
  8897. * creation of Anchors without user intervention.
  8898. */
  8899. _jp.Anchor = function (params) {
  8900. this.x = params.x || 0;
  8901. this.y = params.y || 0;
  8902. this.elementId = params.elementId;
  8903. this.cssClass = params.cssClass || "";
  8904. this.userDefinedLocation = null;
  8905. this.orientation = params.orientation || [ 0, 0 ];
  8906. this.lastReturnValue = null;
  8907. this.offsets = params.offsets || [ 0, 0 ];
  8908. this.timestamp = null;
  8909. _ju.EventGenerator.apply(this);
  8910. this.compute = function (params) {
  8911. var xy = params.xy, wh = params.wh, timestamp = params.timestamp;
  8912. if (params.clearUserDefinedLocation) {
  8913. this.userDefinedLocation = null;
  8914. }
  8915. if (timestamp && timestamp === this.timestamp) {
  8916. return this.lastReturnValue;
  8917. }
  8918. if (this.userDefinedLocation != null) {
  8919. this.lastReturnValue = this.userDefinedLocation;
  8920. }
  8921. else {
  8922. this.lastReturnValue = [ xy[0] + (this.x * wh[0]) + this.offsets[0], xy[1] + (this.y * wh[1]) + this.offsets[1] ];
  8923. }
  8924. this.timestamp = timestamp;
  8925. return this.lastReturnValue;
  8926. };
  8927. this.getCurrentLocation = function (params) {
  8928. params = params || {};
  8929. return (this.lastReturnValue == null || (params.timestamp != null && this.timestamp !== params.timestamp)) ? this.compute(params) : this.lastReturnValue;
  8930. };
  8931. };
  8932. _ju.extend(_jp.Anchor, _ju.EventGenerator, {
  8933. equals: function (anchor) {
  8934. if (!anchor) {
  8935. return false;
  8936. }
  8937. var ao = anchor.getOrientation(),
  8938. o = this.getOrientation();
  8939. return this.x === anchor.x && this.y === anchor.y && this.offsets[0] === anchor.offsets[0] && this.offsets[1] === anchor.offsets[1] && o[0] === ao[0] && o[1] === ao[1];
  8940. },
  8941. getUserDefinedLocation: function () {
  8942. return this.userDefinedLocation;
  8943. },
  8944. setUserDefinedLocation: function (l) {
  8945. this.userDefinedLocation = l;
  8946. },
  8947. clearUserDefinedLocation: function () {
  8948. this.userDefinedLocation = null;
  8949. },
  8950. getOrientation: function () {
  8951. return this.orientation;
  8952. },
  8953. getCssClass: function () {
  8954. return this.cssClass;
  8955. }
  8956. });
  8957. /**
  8958. * An Anchor that floats. its orientation is computed dynamically from
  8959. * its position relative to the anchor it is floating relative to. It is used when creating
  8960. * a connection through drag and drop.
  8961. *
  8962. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  8963. */
  8964. _jp.FloatingAnchor = function (params) {
  8965. _jp.Anchor.apply(this, arguments);
  8966. // this is the anchor that this floating anchor is referenced to for
  8967. // purposes of calculating the orientation.
  8968. var ref = params.reference,
  8969. // the canvas this refers to.
  8970. refCanvas = params.referenceCanvas,
  8971. size = _jp.getSize(refCanvas),
  8972. // these are used to store the current relative position of our
  8973. // anchor wrt the reference anchor. they only indicate
  8974. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  8975. // values are written by the compute method, and read
  8976. // by the getOrientation method.
  8977. xDir = 0, yDir = 0,
  8978. // temporary member used to store an orientation when the floating
  8979. // anchor is hovering over another anchor.
  8980. orientation = null,
  8981. _lastResult = null;
  8982. // clear from parent. we want floating anchor orientation to always be computed.
  8983. this.orientation = null;
  8984. // set these to 0 each; they are used by certain types of connectors in the loopback case,
  8985. // when the connector is trying to clear the element it is on. but for floating anchor it's not
  8986. // very important.
  8987. this.x = 0;
  8988. this.y = 0;
  8989. this.isFloating = true;
  8990. this.compute = function (params) {
  8991. var xy = params.xy,
  8992. 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.
  8993. _lastResult = result;
  8994. return result;
  8995. };
  8996. this.getOrientation = function (_endpoint) {
  8997. if (orientation) {
  8998. return orientation;
  8999. }
  9000. else {
  9001. var o = ref.getOrientation(_endpoint);
  9002. // here we take into account the orientation of the other
  9003. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  9004. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  9005. return [ Math.abs(o[0]) * xDir * -1,
  9006. Math.abs(o[1]) * yDir * -1 ];
  9007. }
  9008. };
  9009. /**
  9010. * notification the endpoint associated with this anchor is hovering
  9011. * over another anchor; we want to assume that anchor's orientation
  9012. * for the duration of the hover.
  9013. */
  9014. this.over = function (anchor, endpoint) {
  9015. orientation = anchor.getOrientation(endpoint);
  9016. };
  9017. /**
  9018. * notification the endpoint associated with this anchor is no
  9019. * longer hovering over another anchor; we should resume calculating
  9020. * orientation as we normally do.
  9021. */
  9022. this.out = function () {
  9023. orientation = null;
  9024. };
  9025. this.getCurrentLocation = function (params) {
  9026. return _lastResult == null ? this.compute(params) : _lastResult;
  9027. };
  9028. };
  9029. _ju.extend(_jp.FloatingAnchor, _jp.Anchor);
  9030. var _convertAnchor = function (anchor, jsPlumbInstance, elementId) {
  9031. return anchor.constructor === _jp.Anchor ? anchor : jsPlumbInstance.makeAnchor(anchor, elementId, jsPlumbInstance);
  9032. };
  9033. /*
  9034. * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
  9035. * through at compute time to find the one that is located closest to
  9036. * the center of the target element, and returns that Anchor's compute
  9037. * method result. this causes endpoints to follow each other with
  9038. * respect to the orientation of their target elements, which is a useful
  9039. * feature for some applications.
  9040. *
  9041. */
  9042. _jp.DynamicAnchor = function (params) {
  9043. _jp.Anchor.apply(this, arguments);
  9044. this.isDynamic = true;
  9045. this.anchors = [];
  9046. this.elementId = params.elementId;
  9047. this.jsPlumbInstance = params.jsPlumbInstance;
  9048. for (var i = 0; i < params.anchors.length; i++) {
  9049. this.anchors[i] = _convertAnchor(params.anchors[i], this.jsPlumbInstance, this.elementId);
  9050. }
  9051. this.getAnchors = function () {
  9052. return this.anchors;
  9053. };
  9054. this.locked = false;
  9055. var _curAnchor = this.anchors.length > 0 ? this.anchors[0] : null,
  9056. _lastAnchor = _curAnchor,
  9057. self = this,
  9058. // helper method to calculate the distance between the centers of the two elements.
  9059. _distance = function (anchor, cx, cy, xy, wh) {
  9060. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]),
  9061. acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2);
  9062. return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) +
  9063. Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2)));
  9064. },
  9065. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  9066. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  9067. // xy - xy loc of the anchor's element
  9068. // wh - anchor's element's dimensions
  9069. // txy - xy loc of the element of the other anchor in the connection
  9070. // twh - dimensions of the element of the other anchor in the connection.
  9071. // anchors - the list of selectable anchors
  9072. _anchorSelector = params.selector || function (xy, wh, txy, twh, anchors) {
  9073. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  9074. var minIdx = -1, minDist = Infinity;
  9075. for (var i = 0; i < anchors.length; i++) {
  9076. var d = _distance(anchors[i], cx, cy, xy, wh);
  9077. if (d < minDist) {
  9078. minIdx = i + 0;
  9079. minDist = d;
  9080. }
  9081. }
  9082. return anchors[minIdx];
  9083. };
  9084. this.compute = function (params) {
  9085. var xy = params.xy, wh = params.wh, txy = params.txy, twh = params.twh;
  9086. this.timestamp = params.timestamp;
  9087. var udl = self.getUserDefinedLocation();
  9088. if (udl != null) {
  9089. return udl;
  9090. }
  9091. // if anchor is locked or an opposite element was not given, we
  9092. // maintain our state. anchor will be locked
  9093. // if it is the source of a drag and drop.
  9094. if (this.locked || txy == null || twh == null) {
  9095. return _curAnchor.compute(params);
  9096. }
  9097. else {
  9098. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  9099. }
  9100. _curAnchor = _anchorSelector(xy, wh, txy, twh, this.anchors);
  9101. this.x = _curAnchor.x;
  9102. this.y = _curAnchor.y;
  9103. if (_curAnchor !== _lastAnchor) {
  9104. this.fire("anchorChanged", _curAnchor);
  9105. }
  9106. _lastAnchor = _curAnchor;
  9107. return _curAnchor.compute(params);
  9108. };
  9109. this.getCurrentLocation = function (params) {
  9110. return this.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation(params) : null);
  9111. };
  9112. this.getOrientation = function (_endpoint) {
  9113. return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ];
  9114. };
  9115. this.over = function (anchor, endpoint) {
  9116. if (_curAnchor != null) {
  9117. _curAnchor.over(anchor, endpoint);
  9118. }
  9119. };
  9120. this.out = function () {
  9121. if (_curAnchor != null) {
  9122. _curAnchor.out();
  9123. }
  9124. };
  9125. this.getCssClass = function () {
  9126. return (_curAnchor && _curAnchor.getCssClass()) || "";
  9127. };
  9128. };
  9129. _ju.extend(_jp.DynamicAnchor, _jp.Anchor);
  9130. // -------- basic anchors ------------------
  9131. var _curryAnchor = function (x, y, ox, oy, type, fnInit) {
  9132. _jp.Anchors[type] = function (params) {
  9133. var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
  9134. a.type = type;
  9135. if (fnInit) {
  9136. fnInit(a, params);
  9137. }
  9138. return a;
  9139. };
  9140. };
  9141. _curryAnchor(0.5, 0, 0, -1, "TopCenter");
  9142. _curryAnchor(0.5, 1, 0, 1, "BottomCenter");
  9143. _curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
  9144. _curryAnchor(1, 0.5, 1, 0, "RightMiddle");
  9145. _curryAnchor(0.5, 0, 0, -1, "Top");
  9146. _curryAnchor(0.5, 1, 0, 1, "Bottom");
  9147. _curryAnchor(0, 0.5, -1, 0, "Left");
  9148. _curryAnchor(1, 0.5, 1, 0, "Right");
  9149. _curryAnchor(0.5, 0.5, 0, 0, "Center");
  9150. _curryAnchor(1, 0, 0, -1, "TopRight");
  9151. _curryAnchor(1, 1, 0, 1, "BottomRight");
  9152. _curryAnchor(0, 0, 0, -1, "TopLeft");
  9153. _curryAnchor(0, 1, 0, 1, "BottomLeft");
  9154. // ------- dynamic anchors -------------------
  9155. // default dynamic anchors chooses from Top, Right, Bottom, Left
  9156. _jp.Defaults.DynamicAnchors = function (params) {
  9157. return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
  9158. };
  9159. // default dynamic anchors bound to name 'AutoDefault'
  9160. _jp.Anchors.AutoDefault = function (params) {
  9161. var a = params.jsPlumbInstance.makeDynamicAnchor(_jp.Defaults.DynamicAnchors(params));
  9162. a.type = "AutoDefault";
  9163. return a;
  9164. };
  9165. // ------- continuous anchors -------------------
  9166. var _curryContinuousAnchor = function (type, faces) {
  9167. _jp.Anchors[type] = function (params) {
  9168. var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces: faces }], params.elementId, params.jsPlumbInstance);
  9169. a.type = type;
  9170. return a;
  9171. };
  9172. };
  9173. _jp.Anchors.Continuous = function (params) {
  9174. return params.jsPlumbInstance.continuousAnchorFactory.get(params);
  9175. };
  9176. _curryContinuousAnchor("ContinuousLeft", ["left"]);
  9177. _curryContinuousAnchor("ContinuousTop", ["top"]);
  9178. _curryContinuousAnchor("ContinuousBottom", ["bottom"]);
  9179. _curryContinuousAnchor("ContinuousRight", ["right"]);
  9180. // ------- position assign anchors -------------------
  9181. // this anchor type lets you assign the position at connection time.
  9182. _curryAnchor(0, 0, 0, 0, "Assign", function (anchor, params) {
  9183. // find what to use as the "position finder". the user may have supplied a String which represents
  9184. // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
  9185. // position finder as a function. we find out what to use and then set it on the anchor.
  9186. var pf = params.position || "Fixed";
  9187. anchor.positionFinder = pf.constructor === String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf;
  9188. // always set the constructor params; the position finder might need them later (the Grid one does,
  9189. // for example)
  9190. anchor.constructorParams = params;
  9191. });
  9192. // these are the default anchor positions finders, which are used by the makeTarget function. supplying
  9193. // a position finder argument to that function allows you to specify where the resulting anchor will
  9194. // be located
  9195. root.jsPlumbInstance.prototype.AnchorPositionFinders = {
  9196. "Fixed": function (dp, ep, es) {
  9197. return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
  9198. },
  9199. "Grid": function (dp, ep, es, params) {
  9200. var dx = dp.left - ep.left, dy = dp.top - ep.top,
  9201. gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]),
  9202. mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
  9203. return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
  9204. }
  9205. };
  9206. // ------- perimeter anchors -------------------
  9207. _jp.Anchors.Perimeter = function (params) {
  9208. params = params || {};
  9209. var anchorCount = params.anchorCount || 60,
  9210. shape = params.shape;
  9211. if (!shape) {
  9212. throw new Error("no shape supplied to Perimeter Anchor type");
  9213. }
  9214. var _circle = function () {
  9215. var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = [];
  9216. for (var i = 0; i < anchorCount; i++) {
  9217. var x = r + (r * Math.sin(current)),
  9218. y = r + (r * Math.cos(current));
  9219. a.push([ x, y, 0, 0 ]);
  9220. current += step;
  9221. }
  9222. return a;
  9223. },
  9224. _path = function (segments) {
  9225. var anchorsPerFace = anchorCount / segments.length, a = [],
  9226. _computeFace = function (x1, y1, x2, y2, fractionalLength) {
  9227. anchorsPerFace = anchorCount * fractionalLength;
  9228. var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace;
  9229. for (var i = 0; i < anchorsPerFace; i++) {
  9230. a.push([
  9231. x1 + (dx * i),
  9232. y1 + (dy * i),
  9233. 0,
  9234. 0
  9235. ]);
  9236. }
  9237. };
  9238. for (var i = 0; i < segments.length; i++) {
  9239. _computeFace.apply(null, segments[i]);
  9240. }
  9241. return a;
  9242. },
  9243. _shape = function (faces) {
  9244. var s = [];
  9245. for (var i = 0; i < faces.length; i++) {
  9246. s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]);
  9247. }
  9248. return _path(s);
  9249. },
  9250. _rectangle = function () {
  9251. return _shape([
  9252. [ 0, 0, 1, 0 ],
  9253. [ 1, 0, 1, 1 ],
  9254. [ 1, 1, 0, 1 ],
  9255. [ 0, 1, 0, 0 ]
  9256. ]);
  9257. };
  9258. var _shapes = {
  9259. "Circle": _circle,
  9260. "Ellipse": _circle,
  9261. "Diamond": function () {
  9262. return _shape([
  9263. [ 0.5, 0, 1, 0.5 ],
  9264. [ 1, 0.5, 0.5, 1 ],
  9265. [ 0.5, 1, 0, 0.5 ],
  9266. [ 0, 0.5, 0.5, 0 ]
  9267. ]);
  9268. },
  9269. "Rectangle": _rectangle,
  9270. "Square": _rectangle,
  9271. "Triangle": function () {
  9272. return _shape([
  9273. [ 0.5, 0, 1, 1 ],
  9274. [ 1, 1, 0, 1 ],
  9275. [ 0, 1, 0.5, 0]
  9276. ]);
  9277. },
  9278. "Path": function (params) {
  9279. var points = params.points, p = [], tl = 0;
  9280. for (var i = 0; i < points.length - 1; i++) {
  9281. var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1]));
  9282. tl += l;
  9283. p.push([points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], l]);
  9284. }
  9285. for (var j = 0; j < p.length; j++) {
  9286. p[j][4] = p[j][4] / tl;
  9287. }
  9288. return _path(p);
  9289. }
  9290. },
  9291. _rotate = function (points, amountInDegrees) {
  9292. var o = [], theta = amountInDegrees / 180 * Math.PI;
  9293. for (var i = 0; i < points.length; i++) {
  9294. var _x = points[i][0] - 0.5,
  9295. _y = points[i][1] - 0.5;
  9296. o.push([
  9297. 0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))),
  9298. 0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))),
  9299. points[i][2],
  9300. points[i][3]
  9301. ]);
  9302. }
  9303. return o;
  9304. };
  9305. if (!_shapes[shape]) {
  9306. throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type");
  9307. }
  9308. var da = _shapes[shape](params);
  9309. if (params.rotation) {
  9310. da = _rotate(da, params.rotation);
  9311. }
  9312. var a = params.jsPlumbInstance.makeDynamicAnchor(da);
  9313. a.type = "Perimeter";
  9314. return a;
  9315. };
  9316. }).call(typeof window !== 'undefined' ? window : this);
  9317. /*
  9318. * This file contains the default Connectors, Endpoint and Overlay definitions.
  9319. *
  9320. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  9321. *
  9322. * https://jsplumbtoolkit.com
  9323. * https://github.com/jsplumb/jsplumb
  9324. *
  9325. * Dual licensed under the MIT and GPL2 licenses.
  9326. */
  9327. ;
  9328. (function () {
  9329. "use strict";
  9330. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jg = root.Biltong;
  9331. _jp.Segments = {
  9332. /*
  9333. * Class: AbstractSegment
  9334. * A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc',
  9335. * 'Bezier'. This is new from 1.4.2, and gives us a lot more flexibility when drawing connections: things such
  9336. * as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are
  9337. * much easier to do now.
  9338. *
  9339. * A Segment is responsible for providing coordinates for painting it, and also must be able to report its length.
  9340. *
  9341. */
  9342. AbstractSegment: function (params) {
  9343. this.params = params;
  9344. /**
  9345. * Function: findClosestPointOnPath
  9346. * Finds the closest point on this segment to the given [x, y],
  9347. * returning both the x and y of the point plus its distance from
  9348. * the supplied point, and its location along the length of the
  9349. * path inscribed by the segment. This implementation returns
  9350. * Infinity for distance and null values for everything else;
  9351. * subclasses are expected to override.
  9352. */
  9353. this.findClosestPointOnPath = function (x, y) {
  9354. return {
  9355. d: Infinity,
  9356. x: null,
  9357. y: null,
  9358. l: null
  9359. };
  9360. };
  9361. this.getBounds = function () {
  9362. return {
  9363. minX: Math.min(params.x1, params.x2),
  9364. minY: Math.min(params.y1, params.y2),
  9365. maxX: Math.max(params.x1, params.x2),
  9366. maxY: Math.max(params.y1, params.y2)
  9367. };
  9368. };
  9369. },
  9370. Straight: function (params) {
  9371. var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
  9372. length, m, m2, x1, x2, y1, y2,
  9373. _recalc = function () {
  9374. length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  9375. m = _jg.gradient({x: x1, y: y1}, {x: x2, y: y2});
  9376. m2 = -1 / m;
  9377. };
  9378. this.type = "Straight";
  9379. this.getLength = function () {
  9380. return length;
  9381. };
  9382. this.getGradient = function () {
  9383. return m;
  9384. };
  9385. this.getCoordinates = function () {
  9386. return { x1: x1, y1: y1, x2: x2, y2: y2 };
  9387. };
  9388. this.setCoordinates = function (coords) {
  9389. x1 = coords.x1;
  9390. y1 = coords.y1;
  9391. x2 = coords.x2;
  9392. y2 = coords.y2;
  9393. _recalc();
  9394. };
  9395. this.setCoordinates({x1: params.x1, y1: params.y1, x2: params.x2, y2: params.y2});
  9396. this.getBounds = function () {
  9397. return {
  9398. minX: Math.min(x1, x2),
  9399. minY: Math.min(y1, y2),
  9400. maxX: Math.max(x1, x2),
  9401. maxY: Math.max(y1, y2)
  9402. };
  9403. };
  9404. /**
  9405. * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
  9406. * 0 to 1 inclusive. for the straight line segment this is simple maths.
  9407. */
  9408. this.pointOnPath = function (location, absolute) {
  9409. if (location === 0 && !absolute) {
  9410. return { x: x1, y: y1 };
  9411. }
  9412. else if (location === 1 && !absolute) {
  9413. return { x: x2, y: y2 };
  9414. }
  9415. else {
  9416. var l = absolute ? location > 0 ? location : length + location : location * length;
  9417. return _jg.pointOnLine({x: x1, y: y1}, {x: x2, y: y2}, l);
  9418. }
  9419. };
  9420. /**
  9421. * returns the gradient of the segment at the given point - which for us is constant.
  9422. */
  9423. this.gradientAtPoint = function (_) {
  9424. return m;
  9425. };
  9426. /**
  9427. * returns the point on the segment's path that is 'distance' along the length of the path from 'location', where
  9428. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
  9429. * this hands off to jsPlumbUtil to do the maths, supplying two points and the distance.
  9430. */
  9431. this.pointAlongPathFrom = function (location, distance, absolute) {
  9432. var p = this.pointOnPath(location, absolute),
  9433. farAwayPoint = distance <= 0 ? {x: x1, y: y1} : {x: x2, y: y2 };
  9434. /*
  9435. location == 1 ? {
  9436. x:x1 + ((x2 - x1) * 10),
  9437. y:y1 + ((y1 - y2) * 10)
  9438. } :
  9439. */
  9440. if (distance <= 0 && Math.abs(distance) > 1) {
  9441. distance *= -1;
  9442. }
  9443. return _jg.pointOnLine(p, farAwayPoint, distance);
  9444. };
  9445. // is c between a and b?
  9446. var within = function (a, b, c) {
  9447. return c >= Math.min(a, b) && c <= Math.max(a, b);
  9448. };
  9449. // find which of a and b is closest to c
  9450. var closest = function (a, b, c) {
  9451. return Math.abs(c - a) < Math.abs(c - b) ? a : b;
  9452. };
  9453. /**
  9454. Function: findClosestPointOnPath
  9455. Finds the closest point on this segment to [x,y]. See
  9456. notes on this method in AbstractSegment.
  9457. */
  9458. this.findClosestPointOnPath = function (x, y) {
  9459. var out = {
  9460. d: Infinity,
  9461. x: null,
  9462. y: null,
  9463. l: null,
  9464. x1: x1,
  9465. x2: x2,
  9466. y1: y1,
  9467. y2: y2
  9468. };
  9469. if (m === 0) {
  9470. out.y = y1;
  9471. out.x = within(x1, x2, x) ? x : closest(x1, x2, x);
  9472. }
  9473. else if (m === Infinity || m === -Infinity) {
  9474. out.x = x1;
  9475. out.y = within(y1, y2, y) ? y : closest(y1, y2, y);
  9476. }
  9477. else {
  9478. // closest point lies on normal from given point to this line.
  9479. var b = y1 - (m * x1),
  9480. b2 = y - (m2 * x),
  9481. // y1 = m.x1 + b and y1 = m2.x1 + b2
  9482. // so m.x1 + b = m2.x1 + b2
  9483. // x1(m - m2) = b2 - b
  9484. // x1 = (b2 - b) / (m - m2)
  9485. _x1 = (b2 - b) / (m - m2),
  9486. _y1 = (m * _x1) + b;
  9487. out.x = within(x1, x2, _x1) ? _x1 : closest(x1, x2, _x1);//_x1;
  9488. out.y = within(y1, y2, _y1) ? _y1 : closest(y1, y2, _y1);//_y1;
  9489. }
  9490. var fractionInSegment = _jg.lineLength([ out.x, out.y ], [ x1, y1 ]);
  9491. out.d = _jg.lineLength([x, y], [out.x, out.y]);
  9492. out.l = fractionInSegment / length;
  9493. return out;
  9494. };
  9495. },
  9496. /*
  9497. Arc Segment. You need to supply:
  9498. r - radius
  9499. cx - center x for the arc
  9500. cy - center y for the arc
  9501. ac - whether the arc is anticlockwise or not. default is clockwise.
  9502. and then either:
  9503. startAngle - startAngle for the arc.
  9504. endAngle - endAngle for the arc.
  9505. or:
  9506. x1 - x for start point
  9507. y1 - y for start point
  9508. x2 - x for end point
  9509. y2 - y for end point
  9510. */
  9511. Arc: function (params) {
  9512. var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
  9513. _calcAngle = function (_x, _y) {
  9514. return _jg.theta([params.cx, params.cy], [_x, _y]);
  9515. },
  9516. _calcAngleForLocation = function (segment, location) {
  9517. if (segment.anticlockwise) {
  9518. var sa = segment.startAngle < segment.endAngle ? segment.startAngle + TWO_PI : segment.startAngle,
  9519. s = Math.abs(sa - segment.endAngle);
  9520. return sa - (s * location);
  9521. }
  9522. else {
  9523. var ea = segment.endAngle < segment.startAngle ? segment.endAngle + TWO_PI : segment.endAngle,
  9524. ss = Math.abs(ea - segment.startAngle);
  9525. return segment.startAngle + (ss * location);
  9526. }
  9527. },
  9528. TWO_PI = 2 * Math.PI;
  9529. this.radius = params.r;
  9530. this.anticlockwise = params.ac;
  9531. this.type = "Arc";
  9532. if (params.startAngle && params.endAngle) {
  9533. this.startAngle = params.startAngle;
  9534. this.endAngle = params.endAngle;
  9535. this.x1 = params.cx + (this.radius * Math.cos(params.startAngle));
  9536. this.y1 = params.cy + (this.radius * Math.sin(params.startAngle));
  9537. this.x2 = params.cx + (this.radius * Math.cos(params.endAngle));
  9538. this.y2 = params.cy + (this.radius * Math.sin(params.endAngle));
  9539. }
  9540. else {
  9541. this.startAngle = _calcAngle(params.x1, params.y1);
  9542. this.endAngle = _calcAngle(params.x2, params.y2);
  9543. this.x1 = params.x1;
  9544. this.y1 = params.y1;
  9545. this.x2 = params.x2;
  9546. this.y2 = params.y2;
  9547. }
  9548. if (this.endAngle < 0) {
  9549. this.endAngle += TWO_PI;
  9550. }
  9551. if (this.startAngle < 0) {
  9552. this.startAngle += TWO_PI;
  9553. }
  9554. // segment is used by vml
  9555. //this.segment = _jg.quadrant([this.x1, this.y1], [this.x2, this.y2]);
  9556. // we now have startAngle and endAngle as positive numbers, meaning the
  9557. // absolute difference (|d|) between them is the sweep (s) of this arc, unless the
  9558. // arc is 'anticlockwise' in which case 's' is given by 2PI - |d|.
  9559. var ea = this.endAngle < this.startAngle ? this.endAngle + TWO_PI : this.endAngle;
  9560. this.sweep = Math.abs(ea - this.startAngle);
  9561. if (this.anticlockwise) {
  9562. this.sweep = TWO_PI - this.sweep;
  9563. }
  9564. var circumference = 2 * Math.PI * this.radius,
  9565. frac = this.sweep / TWO_PI,
  9566. length = circumference * frac;
  9567. this.getLength = function () {
  9568. return length;
  9569. };
  9570. this.getBounds = function () {
  9571. return {
  9572. minX: params.cx - params.r,
  9573. maxX: params.cx + params.r,
  9574. minY: params.cy - params.r,
  9575. maxY: params.cy + params.r
  9576. };
  9577. };
  9578. var VERY_SMALL_VALUE = 0.0000000001,
  9579. gentleRound = function (n) {
  9580. var f = Math.floor(n), r = Math.ceil(n);
  9581. if (n - f < VERY_SMALL_VALUE) {
  9582. return f;
  9583. }
  9584. else if (r - n < VERY_SMALL_VALUE) {
  9585. return r;
  9586. }
  9587. return n;
  9588. };
  9589. /**
  9590. * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
  9591. * 0 to 1 inclusive.
  9592. */
  9593. this.pointOnPath = function (location, absolute) {
  9594. if (location === 0) {
  9595. return { x: this.x1, y: this.y1, theta: this.startAngle };
  9596. }
  9597. else if (location === 1) {
  9598. return { x: this.x2, y: this.y2, theta: this.endAngle };
  9599. }
  9600. if (absolute) {
  9601. location = location / length;
  9602. }
  9603. var angle = _calcAngleForLocation(this, location),
  9604. _x = params.cx + (params.r * Math.cos(angle)),
  9605. _y = params.cy + (params.r * Math.sin(angle));
  9606. return { x: gentleRound(_x), y: gentleRound(_y), theta: angle };
  9607. };
  9608. /**
  9609. * returns the gradient of the segment at the given point.
  9610. */
  9611. this.gradientAtPoint = function (location, absolute) {
  9612. var p = this.pointOnPath(location, absolute);
  9613. var m = _jg.normal([ params.cx, params.cy ], [p.x, p.y ]);
  9614. if (!this.anticlockwise && (m === Infinity || m === -Infinity)) {
  9615. m *= -1;
  9616. }
  9617. return m;
  9618. };
  9619. this.pointAlongPathFrom = function (location, distance, absolute) {
  9620. var p = this.pointOnPath(location, absolute),
  9621. arcSpan = distance / circumference * 2 * Math.PI,
  9622. dir = this.anticlockwise ? -1 : 1,
  9623. startAngle = p.theta + (dir * arcSpan),
  9624. startX = params.cx + (this.radius * Math.cos(startAngle)),
  9625. startY = params.cy + (this.radius * Math.sin(startAngle));
  9626. return {x: startX, y: startY};
  9627. };
  9628. },
  9629. Bezier: function (params) {
  9630. this.curve = [
  9631. { x: params.x1, y: params.y1},
  9632. { x: params.cp1x, y: params.cp1y },
  9633. { x: params.cp2x, y: params.cp2y },
  9634. { x: params.x2, y: params.y2 }
  9635. ];
  9636. var _super = _jp.Segments.AbstractSegment.apply(this, arguments);
  9637. // although this is not a strictly rigorous determination of bounds
  9638. // of a bezier curve, it works for the types of curves that this segment
  9639. // type produces.
  9640. this.bounds = {
  9641. minX: Math.min(params.x1, params.x2, params.cp1x, params.cp2x),
  9642. minY: Math.min(params.y1, params.y2, params.cp1y, params.cp2y),
  9643. maxX: Math.max(params.x1, params.x2, params.cp1x, params.cp2x),
  9644. maxY: Math.max(params.y1, params.y2, params.cp1y, params.cp2y)
  9645. };
  9646. this.type = "Bezier";
  9647. var _translateLocation = function (_curve, location, absolute) {
  9648. if (absolute) {
  9649. location = root.jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location);
  9650. }
  9651. return location;
  9652. };
  9653. /**
  9654. * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
  9655. * 0 to 1 inclusive.
  9656. */
  9657. this.pointOnPath = function (location, absolute) {
  9658. location = _translateLocation(this.curve, location, absolute);
  9659. return root.jsBezier.pointOnCurve(this.curve, location);
  9660. };
  9661. /**
  9662. * returns the gradient of the segment at the given point.
  9663. */
  9664. this.gradientAtPoint = function (location, absolute) {
  9665. location = _translateLocation(this.curve, location, absolute);
  9666. return root.jsBezier.gradientAtPoint(this.curve, location);
  9667. };
  9668. this.pointAlongPathFrom = function (location, distance, absolute) {
  9669. location = _translateLocation(this.curve, location, absolute);
  9670. return root.jsBezier.pointAlongCurveFrom(this.curve, location, distance);
  9671. };
  9672. this.getLength = function () {
  9673. return root.jsBezier.getLength(this.curve);
  9674. };
  9675. this.getBounds = function () {
  9676. return this.bounds;
  9677. };
  9678. }
  9679. };
  9680. _jp.SegmentRenderer = {
  9681. getPath: function (segment) {
  9682. return ({
  9683. "Straight": function () {
  9684. var d = segment.getCoordinates();
  9685. return "M " + d.x1 + " " + d.y1 + " L " + d.x2 + " " + d.y2;
  9686. },
  9687. "Bezier": function () {
  9688. var d = segment.params;
  9689. return "M " + d.x1 + " " + d.y1 +
  9690. " C " + d.cp1x + " " + d.cp1y + " " + d.cp2x + " " + d.cp2y + " " + d.x2 + " " + d.y2;
  9691. },
  9692. "Arc": function () {
  9693. var d = segment.params,
  9694. laf = segment.sweep > Math.PI ? 1 : 0,
  9695. sf = segment.anticlockwise ? 0 : 1;
  9696. return "M" + segment.x1 + " " + segment.y1 + " A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2;
  9697. }
  9698. })[segment.type]();
  9699. }
  9700. };
  9701. /*
  9702. Class: UIComponent
  9703. Superclass for Connector and AbstractEndpoint.
  9704. */
  9705. var AbstractComponent = function () {
  9706. this.resetBounds = function () {
  9707. this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
  9708. };
  9709. this.resetBounds();
  9710. };
  9711. /*
  9712. * Class: Connector
  9713. * Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it
  9714. * can be accessed from other files. You should not try to instantiate one of these directly.
  9715. *
  9716. * When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch
  9717. * that request to. This is done by keeping track of the total connector length as segments are added, and also
  9718. * their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching
  9719. * the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.)
  9720. */
  9721. _jp.Connectors.AbstractConnector = function (params) {
  9722. AbstractComponent.apply(this, arguments);
  9723. var segments = [],
  9724. totalLength = 0,
  9725. segmentProportions = [],
  9726. segmentProportionalLengths = [],
  9727. stub = params.stub || 0,
  9728. sourceStub = _ju.isArray(stub) ? stub[0] : stub,
  9729. targetStub = _ju.isArray(stub) ? stub[1] : stub,
  9730. gap = params.gap || 0,
  9731. sourceGap = _ju.isArray(gap) ? gap[0] : gap,
  9732. targetGap = _ju.isArray(gap) ? gap[1] : gap,
  9733. userProvidedSegments = null,
  9734. edited = false,
  9735. paintInfo = null,
  9736. geometry = null,
  9737. editable = params.editable !== false && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null;
  9738. var _setGeometry = this.setGeometry = function(g, internallyComputed) {
  9739. edited = (!internallyComputed);
  9740. geometry = g;
  9741. };
  9742. var _getGeometry = this.getGeometry = function() {
  9743. return geometry;
  9744. };
  9745. this.getPathData = function() {
  9746. var p = "";
  9747. for (var i = 0; i < segments.length; i++) {
  9748. p += _jp.SegmentRenderer.getPath(segments[i]);
  9749. p += " ";
  9750. }
  9751. return p;
  9752. };
  9753. this.hasBeenEdited = function() { return edited; };
  9754. this.isEditing = function() { return this.editor != null && this.editor.isActive(); };
  9755. this.setEditable = function(e) {
  9756. // if this connector has an editor already, or
  9757. // if an editor for this connector's type is available, or
  9758. // if the child declares an overrideSetEditable and it does not return false, editable is true.
  9759. if (e && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null && (this.overrideSetEditable == null || this.overrideSetEditable())) {
  9760. editable = e;
  9761. } else {
  9762. editable = false;
  9763. }
  9764. return editable;
  9765. };
  9766. this.isEditable = function() { return editable; };
  9767. /**
  9768. * Function: findSegmentForPoint
  9769. * Returns the segment that is closest to the given [x,y],
  9770. * null if nothing found. This function returns a JS
  9771. * object with:
  9772. *
  9773. * d - distance from segment
  9774. * l - proportional location in segment
  9775. * x - x point on the segment
  9776. * y - y point on the segment
  9777. * s - the segment itself.
  9778. */
  9779. this.findSegmentForPoint = function (x, y) {
  9780. var out = { d: Infinity, s: null, x: null, y: null, l: null };
  9781. for (var i = 0; i < segments.length; i++) {
  9782. var _s = segments[i].findClosestPointOnPath(x, y);
  9783. if (_s.d < out.d) {
  9784. out.d = _s.d;
  9785. out.l = _s.l;
  9786. out.x = _s.x;
  9787. out.y = _s.y;
  9788. out.s = segments[i];
  9789. out.x1 = _s.x1;
  9790. out.x2 = _s.x2;
  9791. out.y1 = _s.y1;
  9792. out.y2 = _s.y2;
  9793. out.index = i;
  9794. }
  9795. }
  9796. return out;
  9797. };
  9798. var _updateSegmentProportions = function () {
  9799. var curLoc = 0;
  9800. for (var i = 0; i < segments.length; i++) {
  9801. var sl = segments[i].getLength();
  9802. segmentProportionalLengths[i] = sl / totalLength;
  9803. segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ];
  9804. }
  9805. },
  9806. /**
  9807. * returns [segment, proportion of travel in segment, segment index] for the segment
  9808. * that contains the point which is 'location' distance along the entire path, where
  9809. * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
  9810. * are made up of a list of segments, each of which contributes some fraction to
  9811. * the total length.
  9812. * From 1.3.10 this also supports the 'absolute' property, which lets us specify a location
  9813. * as the absolute distance in pixels, rather than a proportion of the total path.
  9814. */
  9815. _findSegmentForLocation = function (location, absolute) {
  9816. if (absolute) {
  9817. location = location > 0 ? location / totalLength : (totalLength + location) / totalLength;
  9818. }
  9819. var idx = segmentProportions.length - 1, inSegmentProportion = 1;
  9820. for (var i = 0; i < segmentProportions.length; i++) {
  9821. if (segmentProportions[i][1] >= location) {
  9822. idx = i;
  9823. // todo is this correct for all connector path types?
  9824. inSegmentProportion = location === 1 ? 1 : location === 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
  9825. break;
  9826. }
  9827. }
  9828. return { segment: segments[idx], proportion: inSegmentProportion, index: idx };
  9829. },
  9830. _addSegment = function (conn, type, params) {
  9831. if (params.x1 === params.x2 && params.y1 === params.y2) {
  9832. return;
  9833. }
  9834. var s = new _jp.Segments[type](params);
  9835. segments.push(s);
  9836. totalLength += s.getLength();
  9837. conn.updateBounds(s);
  9838. },
  9839. _clearSegments = function () {
  9840. totalLength = segments.length = segmentProportions.length = segmentProportionalLengths.length = 0;
  9841. };
  9842. this.setSegments = function (_segs) {
  9843. userProvidedSegments = [];
  9844. totalLength = 0;
  9845. for (var i = 0; i < _segs.length; i++) {
  9846. userProvidedSegments.push(_segs[i]);
  9847. totalLength += _segs[i].getLength();
  9848. }
  9849. };
  9850. this.getLength = function() {
  9851. return totalLength;
  9852. };
  9853. var _prepareCompute = function (params) {
  9854. this.strokeWidth = params.strokeWidth;
  9855. var segment = _jg.quadrant(params.sourcePos, params.targetPos),
  9856. swapX = params.targetPos[0] < params.sourcePos[0],
  9857. swapY = params.targetPos[1] < params.sourcePos[1],
  9858. lw = params.strokeWidth || 1,
  9859. so = params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint),
  9860. to = params.targetEndpoint.anchor.getOrientation(params.targetEndpoint),
  9861. x = swapX ? params.targetPos[0] : params.sourcePos[0],
  9862. y = swapY ? params.targetPos[1] : params.sourcePos[1],
  9863. w = Math.abs(params.targetPos[0] - params.sourcePos[0]),
  9864. h = Math.abs(params.targetPos[1] - params.sourcePos[1]);
  9865. // if either anchor does not have an orientation set, we derive one from their relative
  9866. // positions. we fix the axis to be the one in which the two elements are further apart, and
  9867. // point each anchor at the other element. this is also used when dragging a new connection.
  9868. if (so[0] === 0 && so[1] === 0 || to[0] === 0 && to[1] === 0) {
  9869. var index = w > h ? 0 : 1, oIndex = [1, 0][index];
  9870. so = [];
  9871. to = [];
  9872. so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1;
  9873. to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1;
  9874. so[oIndex] = 0;
  9875. to[oIndex] = 0;
  9876. }
  9877. var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0],
  9878. sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1],
  9879. tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]),
  9880. ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]),
  9881. oProduct = ((so[0] * to[0]) + (so[1] * to[1]));
  9882. var result = {
  9883. sx: sx, sy: sy, tx: tx, ty: ty, lw: lw,
  9884. xSpan: Math.abs(tx - sx),
  9885. ySpan: Math.abs(ty - sy),
  9886. mx: (sx + tx) / 2,
  9887. my: (sy + ty) / 2,
  9888. so: so, to: to, x: x, y: y, w: w, h: h,
  9889. segment: segment,
  9890. startStubX: sx + (so[0] * sourceStub),
  9891. startStubY: sy + (so[1] * sourceStub),
  9892. endStubX: tx + (to[0] * targetStub),
  9893. endStubY: ty + (to[1] * targetStub),
  9894. isXGreaterThanStubTimes2: Math.abs(sx - tx) > (sourceStub + targetStub),
  9895. isYGreaterThanStubTimes2: Math.abs(sy - ty) > (sourceStub + targetStub),
  9896. opposite: oProduct === -1,
  9897. perpendicular: oProduct === 0,
  9898. orthogonal: oProduct === 1,
  9899. sourceAxis: so[0] === 0 ? "y" : "x",
  9900. points: [x, y, w, h, sx, sy, tx, ty ],
  9901. stubs:[sourceStub, targetStub]
  9902. };
  9903. result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular";
  9904. return result;
  9905. };
  9906. this.getSegments = function () {
  9907. return segments;
  9908. };
  9909. this.updateBounds = function (segment) {
  9910. var segBounds = segment.getBounds();
  9911. this.bounds.minX = Math.min(this.bounds.minX, segBounds.minX);
  9912. this.bounds.maxX = Math.max(this.bounds.maxX, segBounds.maxX);
  9913. this.bounds.minY = Math.min(this.bounds.minY, segBounds.minY);
  9914. this.bounds.maxY = Math.max(this.bounds.maxY, segBounds.maxY);
  9915. };
  9916. var dumpSegmentsToConsole = function () {
  9917. console.log("SEGMENTS:");
  9918. for (var i = 0; i < segments.length; i++) {
  9919. console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]);
  9920. }
  9921. };
  9922. this.pointOnPath = function (location, absolute) {
  9923. var seg = _findSegmentForLocation(location, absolute);
  9924. return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || [0, 0];
  9925. };
  9926. this.gradientAtPoint = function (location, absolute) {
  9927. var seg = _findSegmentForLocation(location, absolute);
  9928. return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0;
  9929. };
  9930. this.pointAlongPathFrom = function (location, distance, absolute) {
  9931. var seg = _findSegmentForLocation(location, absolute);
  9932. // TODO what happens if this crosses to the next segment?
  9933. return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || [0, 0];
  9934. };
  9935. this.compute = function (params) {
  9936. paintInfo = _prepareCompute.call(this, params);
  9937. _clearSegments();
  9938. this._compute(paintInfo, params);
  9939. this.x = paintInfo.points[0];
  9940. this.y = paintInfo.points[1];
  9941. this.w = paintInfo.points[2];
  9942. this.h = paintInfo.points[3];
  9943. this.segment = paintInfo.segment;
  9944. _updateSegmentProportions();
  9945. };
  9946. return {
  9947. addSegment: _addSegment,
  9948. prepareCompute: _prepareCompute,
  9949. sourceStub: sourceStub,
  9950. targetStub: targetStub,
  9951. maxStub: Math.max(sourceStub, targetStub),
  9952. sourceGap: sourceGap,
  9953. targetGap: targetGap,
  9954. maxGap: Math.max(sourceGap, targetGap),
  9955. setGeometry:_setGeometry,
  9956. getGeometry:_getGeometry
  9957. };
  9958. };
  9959. _ju.extend(_jp.Connectors.AbstractConnector, AbstractComponent);
  9960. // ********************************* END OF CONNECTOR TYPES *******************************************************************
  9961. // ********************************* ENDPOINT TYPES *******************************************************************
  9962. _jp.Endpoints.AbstractEndpoint = function (params) {
  9963. AbstractComponent.apply(this, arguments);
  9964. var compute = this.compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9965. var out = this._compute.apply(this, arguments);
  9966. this.x = out[0];
  9967. this.y = out[1];
  9968. this.w = out[2];
  9969. this.h = out[3];
  9970. this.bounds.minX = this.x;
  9971. this.bounds.minY = this.y;
  9972. this.bounds.maxX = this.x + this.w;
  9973. this.bounds.maxY = this.y + this.h;
  9974. return out;
  9975. };
  9976. return {
  9977. compute: compute,
  9978. cssClass: params.cssClass
  9979. };
  9980. };
  9981. _ju.extend(_jp.Endpoints.AbstractEndpoint, AbstractComponent);
  9982. /**
  9983. * Class: Endpoints.Dot
  9984. * A round endpoint, with default radius 10 pixels.
  9985. */
  9986. /**
  9987. * Function: Constructor
  9988. *
  9989. * Parameters:
  9990. *
  9991. * radius - radius of the endpoint. defaults to 10 pixels.
  9992. */
  9993. _jp.Endpoints.Dot = function (params) {
  9994. this.type = "Dot";
  9995. var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  9996. params = params || {};
  9997. this.radius = params.radius || 10;
  9998. this.defaultOffset = 0.5 * this.radius;
  9999. this.defaultInnerRadius = this.radius / 3;
  10000. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  10001. this.radius = endpointStyle.radius || this.radius;
  10002. var x = anchorPoint[0] - this.radius,
  10003. y = anchorPoint[1] - this.radius,
  10004. w = this.radius * 2,
  10005. h = this.radius * 2;
  10006. if (endpointStyle.stroke) {
  10007. var lw = endpointStyle.strokeWidth || 1;
  10008. x -= lw;
  10009. y -= lw;
  10010. w += (lw * 2);
  10011. h += (lw * 2);
  10012. }
  10013. return [ x, y, w, h, this.radius ];
  10014. };
  10015. };
  10016. _ju.extend(_jp.Endpoints.Dot, _jp.Endpoints.AbstractEndpoint);
  10017. _jp.Endpoints.Rectangle = function (params) {
  10018. this.type = "Rectangle";
  10019. var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  10020. params = params || {};
  10021. this.width = params.width || 20;
  10022. this.height = params.height || 20;
  10023. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  10024. var width = endpointStyle.width || this.width,
  10025. height = endpointStyle.height || this.height,
  10026. x = anchorPoint[0] - (width / 2),
  10027. y = anchorPoint[1] - (height / 2);
  10028. return [ x, y, width, height];
  10029. };
  10030. };
  10031. _ju.extend(_jp.Endpoints.Rectangle, _jp.Endpoints.AbstractEndpoint);
  10032. var DOMElementEndpoint = function (params) {
  10033. _jp.jsPlumbUIComponent.apply(this, arguments);
  10034. this._jsPlumb.displayElements = [];
  10035. };
  10036. _ju.extend(DOMElementEndpoint, _jp.jsPlumbUIComponent, {
  10037. getDisplayElements: function () {
  10038. return this._jsPlumb.displayElements;
  10039. },
  10040. appendDisplayElement: function (el) {
  10041. this._jsPlumb.displayElements.push(el);
  10042. }
  10043. });
  10044. /**
  10045. * Class: Endpoints.Image
  10046. * Draws an image as the Endpoint.
  10047. */
  10048. /**
  10049. * Function: Constructor
  10050. *
  10051. * Parameters:
  10052. *
  10053. * src - location of the image to use.
  10054. TODO: multiple references to self. not sure quite how to get rid of them entirely. perhaps self = null in the cleanup
  10055. function will suffice
  10056. TODO this class still might leak memory.
  10057. */
  10058. _jp.Endpoints.Image = function (params) {
  10059. this.type = "Image";
  10060. DOMElementEndpoint.apply(this, arguments);
  10061. _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  10062. var _onload = params.onload,
  10063. src = params.src || params.url,
  10064. clazz = params.cssClass ? " " + params.cssClass : "";
  10065. this._jsPlumb.img = new Image();
  10066. this._jsPlumb.ready = false;
  10067. this._jsPlumb.initialized = false;
  10068. this._jsPlumb.deleted = false;
  10069. this._jsPlumb.widthToUse = params.width;
  10070. this._jsPlumb.heightToUse = params.height;
  10071. this._jsPlumb.endpoint = params.endpoint;
  10072. this._jsPlumb.img.onload = function () {
  10073. if (this._jsPlumb != null) {
  10074. this._jsPlumb.ready = true;
  10075. this._jsPlumb.widthToUse = this._jsPlumb.widthToUse || this._jsPlumb.img.width;
  10076. this._jsPlumb.heightToUse = this._jsPlumb.heightToUse || this._jsPlumb.img.height;
  10077. if (_onload) {
  10078. _onload(this);
  10079. }
  10080. }
  10081. }.bind(this);
  10082. /*
  10083. Function: setImage
  10084. Sets the Image to use in this Endpoint.
  10085. Parameters:
  10086. img - may be a URL or an Image object
  10087. onload - optional; a callback to execute once the image has loaded.
  10088. */
  10089. this._jsPlumb.endpoint.setImage = function (_img, onload) {
  10090. var s = _img.constructor === String ? _img : _img.src;
  10091. _onload = onload;
  10092. this._jsPlumb.img.src = s;
  10093. if (this.canvas != null) {
  10094. this.canvas.setAttribute("src", this._jsPlumb.img.src);
  10095. }
  10096. }.bind(this);
  10097. this._jsPlumb.endpoint.setImage(src, _onload);
  10098. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  10099. this.anchorPoint = anchorPoint;
  10100. if (this._jsPlumb.ready) {
  10101. return [anchorPoint[0] - this._jsPlumb.widthToUse / 2, anchorPoint[1] - this._jsPlumb.heightToUse / 2,
  10102. this._jsPlumb.widthToUse, this._jsPlumb.heightToUse];
  10103. }
  10104. else {
  10105. return [0, 0, 0, 0];
  10106. }
  10107. };
  10108. this.canvas = _jp.createElement("img", {
  10109. position:"absolute",
  10110. margin:0,
  10111. padding:0,
  10112. outline:0
  10113. }, this._jsPlumb.instance.endpointClass + clazz);
  10114. if (this._jsPlumb.widthToUse) {
  10115. this.canvas.setAttribute("width", this._jsPlumb.widthToUse);
  10116. }
  10117. if (this._jsPlumb.heightToUse) {
  10118. this.canvas.setAttribute("height", this._jsPlumb.heightToUse);
  10119. }
  10120. this._jsPlumb.instance.appendElement(this.canvas);
  10121. this.actuallyPaint = function (d, style, anchor) {
  10122. if (!this._jsPlumb.deleted) {
  10123. if (!this._jsPlumb.initialized) {
  10124. this.canvas.setAttribute("src", this._jsPlumb.img.src);
  10125. this.appendDisplayElement(this.canvas);
  10126. this._jsPlumb.initialized = true;
  10127. }
  10128. var x = this.anchorPoint[0] - (this._jsPlumb.widthToUse / 2),
  10129. y = this.anchorPoint[1] - (this._jsPlumb.heightToUse / 2);
  10130. _ju.sizeElement(this.canvas, x, y, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse);
  10131. }
  10132. };
  10133. this.paint = function (style, anchor) {
  10134. if (this._jsPlumb != null) { // may have been deleted
  10135. if (this._jsPlumb.ready) {
  10136. this.actuallyPaint(style, anchor);
  10137. }
  10138. else {
  10139. root.setTimeout(function () {
  10140. this.paint(style, anchor);
  10141. }.bind(this), 200);
  10142. }
  10143. }
  10144. };
  10145. };
  10146. _ju.extend(_jp.Endpoints.Image, [ DOMElementEndpoint, _jp.Endpoints.AbstractEndpoint ], {
  10147. cleanup: function (force) {
  10148. if (force) {
  10149. this._jsPlumb.deleted = true;
  10150. if (this.canvas) {
  10151. this.canvas.parentNode.removeChild(this.canvas);
  10152. }
  10153. this.canvas = null;
  10154. }
  10155. }
  10156. });
  10157. /*
  10158. * Class: Endpoints.Blank
  10159. * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints.
  10160. */
  10161. _jp.Endpoints.Blank = function (params) {
  10162. var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  10163. this.type = "Blank";
  10164. DOMElementEndpoint.apply(this, arguments);
  10165. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  10166. return [anchorPoint[0], anchorPoint[1], 10, 0];
  10167. };
  10168. var clazz = params.cssClass ? " " + params.cssClass : "";
  10169. this.canvas = _jp.createElement("div", {
  10170. display: "block",
  10171. width: "1px",
  10172. height: "1px",
  10173. background: "transparent",
  10174. position: "absolute"
  10175. }, this._jsPlumb.instance.endpointClass + clazz);
  10176. this._jsPlumb.instance.appendElement(this.canvas);
  10177. this.paint = function (style, anchor) {
  10178. _ju.sizeElement(this.canvas, this.x, this.y, this.w, this.h);
  10179. };
  10180. };
  10181. _ju.extend(_jp.Endpoints.Blank, [_jp.Endpoints.AbstractEndpoint, DOMElementEndpoint], {
  10182. cleanup: function () {
  10183. if (this.canvas && this.canvas.parentNode) {
  10184. this.canvas.parentNode.removeChild(this.canvas);
  10185. }
  10186. }
  10187. });
  10188. /*
  10189. * Class: Endpoints.Triangle
  10190. * A triangular Endpoint.
  10191. */
  10192. /*
  10193. * Function: Constructor
  10194. *
  10195. * Parameters:
  10196. *
  10197. * width width of the triangle's base. defaults to 55 pixels.
  10198. * height height of the triangle from base to apex. defaults to 55 pixels.
  10199. */
  10200. _jp.Endpoints.Triangle = function (params) {
  10201. this.type = "Triangle";
  10202. _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  10203. var self = this;
  10204. params = params || { };
  10205. params.width = params.width || 55;
  10206. params.height = params.height || 55;
  10207. this.width = params.width;
  10208. this.height = params.height;
  10209. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  10210. var width = endpointStyle.width || self.width,
  10211. height = endpointStyle.height || self.height,
  10212. x = anchorPoint[0] - (width / 2),
  10213. y = anchorPoint[1] - (height / 2);
  10214. return [ x, y, width, height ];
  10215. };
  10216. };
  10217. // ********************************* END OF ENDPOINT TYPES *******************************************************************
  10218. // ********************************* OVERLAY DEFINITIONS ***********************************************************************
  10219. var AbstractOverlay = _jp.Overlays.AbstractOverlay = function (params) {
  10220. this.visible = true;
  10221. this.isAppendedAtTopLevel = true;
  10222. this.component = params.component;
  10223. this.loc = params.location == null ? 0.5 : params.location;
  10224. this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation;
  10225. this.visible = params.visible !== false;
  10226. };
  10227. AbstractOverlay.prototype = {
  10228. cleanup: function (force) {
  10229. if (force) {
  10230. this.component = null;
  10231. this.canvas = null;
  10232. this.endpointLoc = null;
  10233. }
  10234. },
  10235. reattach:function(instance, component) { },
  10236. setVisible: function (val) {
  10237. this.visible = val;
  10238. this.component.repaint();
  10239. },
  10240. isVisible: function () {
  10241. return this.visible;
  10242. },
  10243. hide: function () {
  10244. this.setVisible(false);
  10245. },
  10246. show: function () {
  10247. this.setVisible(true);
  10248. },
  10249. incrementLocation: function (amount) {
  10250. this.loc += amount;
  10251. this.component.repaint();
  10252. },
  10253. setLocation: function (l) {
  10254. this.loc = l;
  10255. this.component.repaint();
  10256. },
  10257. getLocation: function () {
  10258. return this.loc;
  10259. },
  10260. updateFrom:function() { }
  10261. };
  10262. /*
  10263. * Class: Overlays.Arrow
  10264. *
  10265. * 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
  10266. * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
  10267. * 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
  10268. * across the tail.
  10269. */
  10270. /*
  10271. * @constructor
  10272. *
  10273. * @param {Object} params Constructor params.
  10274. * @param {Number} [params.length] Distance in pixels from head to tail baseline. default 20.
  10275. * @param {Number} [params.width] Width in pixels of the tail baseline. default 20.
  10276. * @param {String} [params.fill] Style to use when filling the arrow. defaults to "black".
  10277. * @param {String} [params.stroke] Style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
  10278. * @param {Number} [params.stroke-width] Line width to use when stroking the arrow. defaults to 1, but only used if stroke is not null.
  10279. * @param {Number} [params.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.
  10280. * @param {Number} [params.location] Distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
  10281. * @param {NUmber} [params.direction] Indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
  10282. */
  10283. _jp.Overlays.Arrow = function (params) {
  10284. this.type = "Arrow";
  10285. AbstractOverlay.apply(this, arguments);
  10286. this.isAppendedAtTopLevel = false;
  10287. params = params || {};
  10288. var self = this;
  10289. this.length = params.length || 20;
  10290. this.width = params.width || 20;
  10291. this.id = params.id;
  10292. var direction = (params.direction || 1) < 0 ? -1 : 1,
  10293. paintStyle = params.paintStyle || { "stroke-width": 1 },
  10294. // how far along the arrow the lines folding back in come to. default is 62.3%.
  10295. foldback = params.foldback || 0.623;
  10296. this.computeMaxSize = function () {
  10297. return self.width * 1.5;
  10298. };
  10299. this.elementCreated = function(p, component) {
  10300. this.path = p;
  10301. if (params.events) {
  10302. for (var i in params.events) {
  10303. _jp.on(p, i, params.events[i]);
  10304. }
  10305. }
  10306. };
  10307. this.draw = function (component, currentConnectionPaintStyle) {
  10308. var hxy, mid, txy, tail, cxy;
  10309. if (component.pointAlongPathFrom) {
  10310. if (_ju.isString(this.loc) || this.loc > 1 || this.loc < 0) {
  10311. var l = parseInt(this.loc, 10),
  10312. fromLoc = this.loc < 0 ? 1 : 0;
  10313. hxy = component.pointAlongPathFrom(fromLoc, l, false);
  10314. mid = component.pointAlongPathFrom(fromLoc, l - (direction * this.length / 2), false);
  10315. txy = _jg.pointOnLine(hxy, mid, this.length);
  10316. }
  10317. else if (this.loc === 1) {
  10318. hxy = component.pointOnPath(this.loc);
  10319. mid = component.pointAlongPathFrom(this.loc, -(this.length));
  10320. txy = _jg.pointOnLine(hxy, mid, this.length);
  10321. if (direction === -1) {
  10322. var _ = txy;
  10323. txy = hxy;
  10324. hxy = _;
  10325. }
  10326. }
  10327. else if (this.loc === 0) {
  10328. txy = component.pointOnPath(this.loc);
  10329. mid = component.pointAlongPathFrom(this.loc, this.length);
  10330. hxy = _jg.pointOnLine(txy, mid, this.length);
  10331. if (direction === -1) {
  10332. var __ = txy;
  10333. txy = hxy;
  10334. hxy = __;
  10335. }
  10336. }
  10337. else {
  10338. hxy = component.pointAlongPathFrom(this.loc, direction * this.length / 2);
  10339. mid = component.pointOnPath(this.loc);
  10340. txy = _jg.pointOnLine(hxy, mid, this.length);
  10341. }
  10342. tail = _jg.perpendicularLineTo(hxy, txy, this.width);
  10343. cxy = _jg.pointOnLine(hxy, txy, foldback * this.length);
  10344. var d = { hxy: hxy, tail: tail, cxy: cxy },
  10345. stroke = paintStyle.stroke || currentConnectionPaintStyle.stroke,
  10346. fill = paintStyle.fill || currentConnectionPaintStyle.stroke,
  10347. lineWidth = paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth;
  10348. return {
  10349. component: component,
  10350. d: d,
  10351. "stroke-width": lineWidth,
  10352. stroke: stroke,
  10353. fill: fill,
  10354. minX: Math.min(hxy.x, tail[0].x, tail[1].x),
  10355. maxX: Math.max(hxy.x, tail[0].x, tail[1].x),
  10356. minY: Math.min(hxy.y, tail[0].y, tail[1].y),
  10357. maxY: Math.max(hxy.y, tail[0].y, tail[1].y)
  10358. };
  10359. }
  10360. else {
  10361. return {component: component, minX: 0, maxX: 0, minY: 0, maxY: 0};
  10362. }
  10363. };
  10364. };
  10365. _ju.extend(_jp.Overlays.Arrow, AbstractOverlay, {
  10366. updateFrom:function(d) {
  10367. this.length = d.length || this.length;
  10368. this.width = d.width|| this.width;
  10369. this.direction = d.direction != null ? d.direction : this.direction;
  10370. this.foldback = d.foldback|| this.foldback;
  10371. }
  10372. });
  10373. /*
  10374. * Class: Overlays.PlainArrow
  10375. *
  10376. * 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
  10377. * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
  10378. * a 'call' to Arrow with foldback set appropriately.
  10379. */
  10380. /*
  10381. * Function: Constructor
  10382. * See <Overlays.Arrow> for allowed parameters for this overlay.
  10383. */
  10384. _jp.Overlays.PlainArrow = function (params) {
  10385. params = params || {};
  10386. var p = _jp.extend(params, {foldback: 1});
  10387. _jp.Overlays.Arrow.call(this, p);
  10388. this.type = "PlainArrow";
  10389. };
  10390. _ju.extend(_jp.Overlays.PlainArrow, _jp.Overlays.Arrow);
  10391. /*
  10392. * Class: Overlays.Diamond
  10393. *
  10394. * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
  10395. * happens that in this case, that point is greater than the length of the the arrow.
  10396. *
  10397. * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
  10398. * 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
  10399. * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
  10400. * would be -l/4 in this case - move along one quarter of the total length.
  10401. */
  10402. /*
  10403. * Function: Constructor
  10404. * See <Overlays.Arrow> for allowed parameters for this overlay.
  10405. */
  10406. _jp.Overlays.Diamond = function (params) {
  10407. params = params || {};
  10408. var l = params.length || 40,
  10409. p = _jp.extend(params, {length: l / 2, foldback: 2});
  10410. _jp.Overlays.Arrow.call(this, p);
  10411. this.type = "Diamond";
  10412. };
  10413. _ju.extend(_jp.Overlays.Diamond, _jp.Overlays.Arrow);
  10414. var _getDimensions = function (component, forceRefresh) {
  10415. if (component._jsPlumb.cachedDimensions == null || forceRefresh) {
  10416. component._jsPlumb.cachedDimensions = component.getDimensions();
  10417. }
  10418. return component._jsPlumb.cachedDimensions;
  10419. };
  10420. // abstract superclass for overlays that add an element to the DOM.
  10421. var AbstractDOMOverlay = function (params) {
  10422. _jp.jsPlumbUIComponent.apply(this, arguments);
  10423. AbstractOverlay.apply(this, arguments);
  10424. // hand off fired events to associated component.
  10425. var _f = this.fire;
  10426. this.fire = function () {
  10427. _f.apply(this, arguments);
  10428. if (this.component) {
  10429. this.component.fire.apply(this.component, arguments);
  10430. }
  10431. };
  10432. this.detached=false;
  10433. this.id = params.id;
  10434. this._jsPlumb.div = null;
  10435. this._jsPlumb.initialised = false;
  10436. this._jsPlumb.component = params.component;
  10437. this._jsPlumb.cachedDimensions = null;
  10438. this._jsPlumb.create = params.create;
  10439. this._jsPlumb.initiallyInvisible = params.visible === false;
  10440. this.getElement = function () {
  10441. if (this._jsPlumb.div == null) {
  10442. var div = this._jsPlumb.div = _jp.getElement(this._jsPlumb.create(this._jsPlumb.component));
  10443. div.style.position = "absolute";
  10444. div.className = this._jsPlumb.instance.overlayClass + " " +
  10445. (this.cssClass ? this.cssClass :
  10446. params.cssClass ? params.cssClass : "");
  10447. this._jsPlumb.instance.appendElement(div);
  10448. this._jsPlumb.instance.getId(div);
  10449. this.canvas = div;
  10450. // in IE the top left corner is what it placed at the desired location. This will not
  10451. // be fixed. IE8 is not going to be supported for much longer.
  10452. var ts = "translate(-50%, -50%)";
  10453. div.style.webkitTransform = ts;
  10454. div.style.mozTransform = ts;
  10455. div.style.msTransform = ts;
  10456. div.style.oTransform = ts;
  10457. div.style.transform = ts;
  10458. // write the related component into the created element
  10459. div._jsPlumb = this;
  10460. if (params.visible === false) {
  10461. div.style.display = "none";
  10462. }
  10463. }
  10464. return this._jsPlumb.div;
  10465. };
  10466. this.draw = function (component, currentConnectionPaintStyle, absolutePosition) {
  10467. var td = _getDimensions(this);
  10468. if (td != null && td.length === 2) {
  10469. var cxy = { x: 0, y: 0 };
  10470. // absolutePosition would have been set by a call to connection.setAbsoluteOverlayPosition.
  10471. if (absolutePosition) {
  10472. cxy = { x: absolutePosition[0], y: absolutePosition[1] };
  10473. }
  10474. else if (component.pointOnPath) {
  10475. var loc = this.loc, absolute = false;
  10476. if (_ju.isString(this.loc) || this.loc < 0 || this.loc > 1) {
  10477. loc = parseInt(this.loc, 10);
  10478. absolute = true;
  10479. }
  10480. cxy = component.pointOnPath(loc, absolute); // a connection
  10481. }
  10482. else {
  10483. var locToUse = this.loc.constructor === Array ? this.loc : this.endpointLoc;
  10484. cxy = { x: locToUse[0] * component.w,
  10485. y: locToUse[1] * component.h };
  10486. }
  10487. var minx = cxy.x - (td[0] / 2),
  10488. miny = cxy.y - (td[1] / 2);
  10489. return {
  10490. component: component,
  10491. d: { minx: minx, miny: miny, td: td, cxy: cxy },
  10492. minX: minx,
  10493. maxX: minx + td[0],
  10494. minY: miny,
  10495. maxY: miny + td[1]
  10496. };
  10497. }
  10498. else {
  10499. return {minX: 0, maxX: 0, minY: 0, maxY: 0};
  10500. }
  10501. };
  10502. };
  10503. _ju.extend(AbstractDOMOverlay, [_jp.jsPlumbUIComponent, AbstractOverlay], {
  10504. getDimensions: function () {
  10505. return [1,1];
  10506. },
  10507. setVisible: function (state) {
  10508. if (this._jsPlumb.div) {
  10509. this._jsPlumb.div.style.display = state ? "block" : "none";
  10510. // if initially invisible, dimensions are 0,0 and never get updated
  10511. if (state && this._jsPlumb.initiallyInvisible) {
  10512. _getDimensions(this, true);
  10513. this.component.repaint();
  10514. this._jsPlumb.initiallyInvisible = false;
  10515. }
  10516. }
  10517. },
  10518. /*
  10519. * Function: clearCachedDimensions
  10520. * Clears the cached dimensions for the label. As a performance enhancement, label dimensions are
  10521. * cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but
  10522. * there are other reasons why the text dimensions might change - if you make a change through CSS, for
  10523. * example, you might change the font size. in that case you should explicitly call this method.
  10524. */
  10525. clearCachedDimensions: function () {
  10526. this._jsPlumb.cachedDimensions = null;
  10527. },
  10528. cleanup: function (force) {
  10529. if (force) {
  10530. if (this._jsPlumb.div != null) {
  10531. this._jsPlumb.div._jsPlumb = null;
  10532. this._jsPlumb.instance.removeElement(this._jsPlumb.div);
  10533. }
  10534. }
  10535. else {
  10536. // if not a forced cleanup, just detach child from parent for now.
  10537. if (this._jsPlumb && this._jsPlumb.div && this._jsPlumb.div.parentNode) {
  10538. this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
  10539. }
  10540. this.detached = true;
  10541. }
  10542. },
  10543. reattach:function(instance, component) {
  10544. if (this._jsPlumb.div != null) {
  10545. instance.getContainer().appendChild(this._jsPlumb.div);
  10546. }
  10547. this.detached = false;
  10548. },
  10549. computeMaxSize: function () {
  10550. var td = _getDimensions(this);
  10551. return Math.max(td[0], td[1]);
  10552. },
  10553. paint: function (p, containerExtents) {
  10554. if (!this._jsPlumb.initialised) {
  10555. this.getElement();
  10556. p.component.appendDisplayElement(this._jsPlumb.div);
  10557. this._jsPlumb.initialised = true;
  10558. if (this.detached) {
  10559. this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
  10560. }
  10561. }
  10562. this._jsPlumb.div.style.left = (p.component.x + p.d.minx) + "px";
  10563. this._jsPlumb.div.style.top = (p.component.y + p.d.miny) + "px";
  10564. }
  10565. });
  10566. /*
  10567. * Class: Overlays.Custom
  10568. * A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it.
  10569. * The 'create' function is passed a Connection or Endpoint.
  10570. */
  10571. /*
  10572. * Function: Constructor
  10573. *
  10574. * Parameters:
  10575. * create - function for jsPlumb to call that returns a DOM element.
  10576. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  10577. * id - optional id to use for later retrieval of this overlay.
  10578. *
  10579. */
  10580. _jp.Overlays.Custom = function (params) {
  10581. this.type = "Custom";
  10582. AbstractDOMOverlay.apply(this, arguments);
  10583. };
  10584. _ju.extend(_jp.Overlays.Custom, AbstractDOMOverlay);
  10585. _jp.Overlays.GuideLines = function () {
  10586. var self = this;
  10587. self.length = 50;
  10588. self.strokeWidth = 5;
  10589. this.type = "GuideLines";
  10590. AbstractOverlay.apply(this, arguments);
  10591. _jp.jsPlumbUIComponent.apply(this, arguments);
  10592. this.draw = function (connector, currentConnectionPaintStyle) {
  10593. var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
  10594. mid = connector.pointOnPath(self.loc),
  10595. tail = _jg.pointOnLine(head, mid, self.length),
  10596. tailLine = _jg.perpendicularLineTo(head, tail, 40),
  10597. headLine = _jg.perpendicularLineTo(tail, head, 20);
  10598. return {
  10599. connector: connector,
  10600. head: head,
  10601. tail: tail,
  10602. headLine: headLine,
  10603. tailLine: tailLine,
  10604. minX: Math.min(head.x, tail.x, headLine[0].x, headLine[1].x),
  10605. minY: Math.min(head.y, tail.y, headLine[0].y, headLine[1].y),
  10606. maxX: Math.max(head.x, tail.x, headLine[0].x, headLine[1].x),
  10607. maxY: Math.max(head.y, tail.y, headLine[0].y, headLine[1].y)
  10608. };
  10609. };
  10610. // this.cleanup = function() { }; // nothing to clean up for GuideLines
  10611. };
  10612. /*
  10613. * Class: Overlays.Label
  10614. */
  10615. /*
  10616. * Function: Constructor
  10617. *
  10618. * Parameters:
  10619. * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
  10620. * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
  10621. * 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
  10622. * label function returns null. empty strings _will_ be painted.
  10623. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  10624. * id - optional id to use for later retrieval of this overlay.
  10625. *
  10626. *
  10627. */
  10628. _jp.Overlays.Label = function (params) {
  10629. this.labelStyle = params.labelStyle;
  10630. var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
  10631. this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null;
  10632. var p = _jp.extend({
  10633. create: function () {
  10634. return _jp.createElement("div");
  10635. }}, params);
  10636. _jp.Overlays.Custom.call(this, p);
  10637. this.type = "Label";
  10638. this.label = params.label || "";
  10639. this.labelText = null;
  10640. if (this.labelStyle) {
  10641. var el = this.getElement();
  10642. this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
  10643. el.style.font = this.labelStyle.font;
  10644. el.style.color = this.labelStyle.color || "black";
  10645. if (this.labelStyle.fill) {
  10646. el.style.background = this.labelStyle.fill;
  10647. }
  10648. if (this.labelStyle.borderWidth > 0) {
  10649. var dStyle = this.labelStyle.borderStyle ? this.labelStyle.borderStyle : "black";
  10650. el.style.border = this.labelStyle.borderWidth + "px solid " + dStyle;
  10651. }
  10652. if (this.labelStyle.padding) {
  10653. el.style.padding = this.labelStyle.padding;
  10654. }
  10655. }
  10656. };
  10657. _ju.extend(_jp.Overlays.Label, _jp.Overlays.Custom, {
  10658. cleanup: function (force) {
  10659. if (force) {
  10660. this.div = null;
  10661. this.label = null;
  10662. this.labelText = null;
  10663. this.cssClass = null;
  10664. this.labelStyle = null;
  10665. }
  10666. },
  10667. getLabel: function () {
  10668. return this.label;
  10669. },
  10670. /*
  10671. * Function: setLabel
  10672. * sets the label's, um, label. you would think i'd call this function
  10673. * 'setText', but you can pass either a Function or a String to this, so
  10674. * it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep
  10675. * that in mind if you need escaped HTML.
  10676. */
  10677. setLabel: function (l) {
  10678. this.label = l;
  10679. this.labelText = null;
  10680. this.clearCachedDimensions();
  10681. this.update();
  10682. this.component.repaint();
  10683. },
  10684. getDimensions: function () {
  10685. this.update();
  10686. return AbstractDOMOverlay.prototype.getDimensions.apply(this, arguments);
  10687. },
  10688. update: function () {
  10689. if (typeof this.label === "function") {
  10690. var lt = this.label(this);
  10691. this.getElement().innerHTML = lt.replace(/\r\n/g, "<br/>");
  10692. }
  10693. else {
  10694. if (this.labelText == null) {
  10695. this.labelText = this.label;
  10696. this.getElement().innerHTML = this.labelText.replace(/\r\n/g, "<br/>");
  10697. }
  10698. }
  10699. },
  10700. updateFrom:function(d) {
  10701. if(d.label != null){
  10702. this.setLabel(d.label);
  10703. }
  10704. }
  10705. });
  10706. // ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
  10707. }).call(typeof window !== 'undefined' ? window : this);
  10708. /*
  10709. * This file contains the base class for library adapters.
  10710. *
  10711. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  10712. *
  10713. * https://jsplumbtoolkit.com
  10714. * https://github.com/jsplumb/jsplumb
  10715. *
  10716. * Dual licensed under the MIT and GPL2 licenses.
  10717. */
  10718. ;(function() {
  10719. "use strict";
  10720. var root = this,
  10721. _jp = root.jsPlumb;
  10722. var _getEventManager = function(instance) {
  10723. var e = instance._mottle;
  10724. if (!e) {
  10725. e = instance._mottle = new root.Mottle();
  10726. }
  10727. return e;
  10728. };
  10729. _jp.extend(root.jsPlumbInstance.prototype, {
  10730. getEventManager:function() {
  10731. return _getEventManager(this);
  10732. },
  10733. on : function(el, event, callback) {
  10734. // TODO: here we would like to map the tap event if we know its
  10735. // an internal bind to a click. we have to know its internal because only
  10736. // then can we be sure that the UP event wont be consumed (tap is a synthesized
  10737. // event from a mousedown followed by a mouseup).
  10738. //event = { "click":"tap", "dblclick":"dbltap"}[event] || event;
  10739. this.getEventManager().on.apply(this, arguments);
  10740. return this;
  10741. },
  10742. off : function(el, event, callback) {
  10743. this.getEventManager().off.apply(this, arguments);
  10744. return this;
  10745. }
  10746. });
  10747. }).call(typeof window !== 'undefined' ? window : this);
  10748. /*
  10749. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  10750. *
  10751. * https://jsplumbtoolkit.com
  10752. * https://github.com/jsplumb/jsplumb
  10753. *
  10754. * Dual licensed under the MIT and GPL2 licenses.
  10755. */
  10756. ;(function() {
  10757. "use strict";
  10758. var root = this,
  10759. _ju = root.jsPlumbUtil,
  10760. _jpi = root.jsPlumbInstance;
  10761. var GROUP_COLLAPSED_CLASS = "jtk-group-collapsed";
  10762. var GROUP_EXPANDED_CLASS = "jtk-group-expanded";
  10763. var GROUP_CONTAINER_SELECTOR = "[jtk-group-content]";
  10764. var ELEMENT_DRAGGABLE_EVENT = "elementDraggable";
  10765. var STOP = "stop";
  10766. var REVERT = "revert";
  10767. var GROUP_MANAGER = "_groupManager";
  10768. var GROUP = "_jsPlumbGroup";
  10769. var GROUP_DRAG_SCOPE = "_jsPlumbGroupDrag";
  10770. var EVT_CHILD_ADDED = "group:addMember";
  10771. var EVT_CHILD_REMOVED = "group:removeMember";
  10772. var EVT_GROUP_ADDED = "group:add";
  10773. var EVT_GROUP_REMOVED = "group:remove";
  10774. var EVT_EXPAND = "group:expand";
  10775. var EVT_COLLAPSE = "group:collapse";
  10776. var EVT_GROUP_DRAG_STOP = "groupDragStop";
  10777. var EVT_CONNECTION_MOVED = "connectionMoved";
  10778. var EVT_INTERNAL_CONNECTION_DETACHED = "internal.connectionDetached";
  10779. var CMD_REMOVE_ALL = "removeAll";
  10780. var CMD_ORPHAN_ALL = "orphanAll";
  10781. var CMD_SHOW = "show";
  10782. var CMD_HIDE = "hide";
  10783. var GroupManager = function(_jsPlumb) {
  10784. var _managedGroups = {}, _connectionSourceMap = {}, _connectionTargetMap = {}, self = this;
  10785. _jsPlumb.bind("connection", function(p) {
  10786. if (p.source[GROUP] != null && p.target[GROUP] != null && p.source[GROUP] === p.target[GROUP]) {
  10787. _connectionSourceMap[p.connection.id] = p.source[GROUP];
  10788. _connectionTargetMap[p.connection.id] = p.source[GROUP];
  10789. }
  10790. else {
  10791. if (p.source[GROUP] != null) {
  10792. _ju.suggest(p.source[GROUP].connections.source, p.connection);
  10793. _connectionSourceMap[p.connection.id] = p.source[GROUP];
  10794. }
  10795. if (p.target[GROUP] != null) {
  10796. _ju.suggest(p.target[GROUP].connections.target, p.connection);
  10797. _connectionTargetMap[p.connection.id] = p.target[GROUP];
  10798. }
  10799. }
  10800. });
  10801. function _cleanupDetachedConnection(conn) {
  10802. delete conn.proxies;
  10803. var group = _connectionSourceMap[conn.id], f;
  10804. if (group != null) {
  10805. f = function(c) { return c.id === conn.id; };
  10806. _ju.removeWithFunction(group.connections.source, f);
  10807. _ju.removeWithFunction(group.connections.target, f);
  10808. delete _connectionSourceMap[conn.id];
  10809. }
  10810. group = _connectionTargetMap[conn.id];
  10811. if (group != null) {
  10812. f = function(c) { return c.id === conn.id; };
  10813. _ju.removeWithFunction(group.connections.source, f);
  10814. _ju.removeWithFunction(group.connections.target, f);
  10815. delete _connectionTargetMap[conn.id];
  10816. }
  10817. }
  10818. _jsPlumb.bind(EVT_INTERNAL_CONNECTION_DETACHED, function(p) {
  10819. _cleanupDetachedConnection(p.connection);
  10820. });
  10821. _jsPlumb.bind(EVT_CONNECTION_MOVED, function(p) {
  10822. var connMap = p.index === 0 ? _connectionSourceMap : _connectionTargetMap;
  10823. var group = connMap[p.connection.id];
  10824. if (group) {
  10825. var list = group.connections[p.index === 0 ? "source" : "target"];
  10826. var idx = list.indexOf(p.connection);
  10827. if (idx !== -1) {
  10828. list.splice(idx, 1);
  10829. }
  10830. }
  10831. });
  10832. this.addGroup = function(group) {
  10833. _jsPlumb.addClass(group.getEl(), GROUP_EXPANDED_CLASS);
  10834. _managedGroups[group.id] = group;
  10835. group.manager = this;
  10836. _updateConnectionsForGroup(group);
  10837. _jsPlumb.fire(EVT_GROUP_ADDED, { group:group });
  10838. };
  10839. this.addToGroup = function(group, el, doNotFireEvent) {
  10840. group = this.getGroup(group);
  10841. if (group) {
  10842. //group.add(el, doNotFireEvent);
  10843. var groupEl = group.getEl();
  10844. if (el._isJsPlumbGroup) {
  10845. return;
  10846. }
  10847. var currentGroup = el._jsPlumbGroup;
  10848. // if already a member of this group, do nothing
  10849. if (currentGroup !== group) {
  10850. var elpos = _jsPlumb.getOffset(el, true);
  10851. var cpos = group.collapsed ? _jsPlumb.getOffset(groupEl, true) : _jsPlumb.getOffset(group.getDragArea(), true);
  10852. // otherwise, transfer to this group.
  10853. if (currentGroup != null) {
  10854. currentGroup.remove(el, doNotFireEvent);
  10855. self.updateConnectionsForGroup(currentGroup);
  10856. }
  10857. group.add(el, doNotFireEvent);
  10858. var handleDroppedConnections = function (list, index) {
  10859. var oidx = index === 0 ? 1 : 0;
  10860. list.each(function (c) {
  10861. c.setVisible(false);
  10862. if (c.endpoints[oidx].element._jsPlumbGroup === group) {
  10863. c.endpoints[oidx].setVisible(false);
  10864. self.expandConnection(c, oidx, group);
  10865. }
  10866. else {
  10867. c.endpoints[index].setVisible(false);
  10868. self.collapseConnection(c, index, group);
  10869. }
  10870. });
  10871. };
  10872. if (group.collapsed) {
  10873. handleDroppedConnections(_jsPlumb.select({source: el}), 0);
  10874. handleDroppedConnections(_jsPlumb.select({target: el}), 1);
  10875. }
  10876. var elId = _jsPlumb.getId(el);
  10877. _jsPlumb.dragManager.setParent(el, elId, groupEl, _jsPlumb.getId(groupEl), elpos);
  10878. var newPosition = { left: elpos.left - cpos.left, top: elpos.top - cpos.top };
  10879. _jsPlumb.setPosition(el, newPosition);
  10880. _jsPlumb.dragManager.revalidateParent(el, elId, elpos);
  10881. self.updateConnectionsForGroup(group);
  10882. _jsPlumb.revalidate(elId);
  10883. setTimeout(function () {
  10884. _jsPlumb.fire(EVT_CHILD_ADDED, {group: group, el: el});
  10885. }, 0);
  10886. }
  10887. }
  10888. };
  10889. this.removeFromGroup = function(group, el, doNotFireEvent) {
  10890. group = this.getGroup(group);
  10891. if (group) {
  10892. group.remove(el, null, doNotFireEvent);
  10893. }
  10894. };
  10895. this.getGroup = function(groupId) {
  10896. var group = groupId;
  10897. if (_ju.isString(groupId)) {
  10898. group = _managedGroups[groupId];
  10899. if (group == null) {
  10900. throw new TypeError("No such group [" + groupId + "]");
  10901. }
  10902. }
  10903. return group;
  10904. };
  10905. this.getGroups = function() {
  10906. var o = [];
  10907. for (var g in _managedGroups) {
  10908. o.push(_managedGroups[g]);
  10909. }
  10910. return o;
  10911. };
  10912. this.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
  10913. group = this.getGroup(group);
  10914. this.expandGroup(group, true); // this reinstates any original connections and removes all proxies, but does not fire an event.
  10915. group[deleteMembers ? CMD_REMOVE_ALL : CMD_ORPHAN_ALL](manipulateDOM, doNotFireEvent);
  10916. _jsPlumb.remove(group.getEl());
  10917. delete _managedGroups[group.id];
  10918. delete _jsPlumb._groups[group.id];
  10919. _jsPlumb.fire(EVT_GROUP_REMOVED, { group:group });
  10920. };
  10921. this.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
  10922. for (var g in _managedGroups) {
  10923. this.removeGroup(_managedGroups[g], deleteMembers, manipulateDOM, doNotFireEvent);
  10924. }
  10925. };
  10926. function _setVisible(group, state) {
  10927. var m = group.getMembers();
  10928. for (var i = 0; i < m.length; i++) {
  10929. _jsPlumb[state ? CMD_SHOW : CMD_HIDE](m[i], true);
  10930. }
  10931. }
  10932. var _collapseConnection = this.collapseConnection = function(c, index, group) {
  10933. var proxyEp, groupEl = group.getEl(), groupElId = _jsPlumb.getId(groupEl),
  10934. originalElementId = c.endpoints[index].elementId;
  10935. var otherEl = c.endpoints[index === 0 ? 1 : 0].element;
  10936. if (otherEl[GROUP] && (!otherEl[GROUP].shouldProxy() && otherEl[GROUP].collapsed)) {
  10937. return;
  10938. }
  10939. c.proxies = c.proxies || [];
  10940. if(c.proxies[index]) {
  10941. proxyEp = c.proxies[index].ep;
  10942. }else {
  10943. proxyEp = _jsPlumb.addEndpoint(groupEl, {
  10944. endpoint:group.getEndpoint(c, index),
  10945. anchor:group.getAnchor(c, index),
  10946. parameters:{
  10947. isProxyEndpoint:true
  10948. }
  10949. });
  10950. }
  10951. proxyEp.setDeleteOnEmpty(true);
  10952. // for this index, stash proxy info: the new EP, the original EP.
  10953. c.proxies[index] = { ep:proxyEp, originalEp: c.endpoints[index] };
  10954. // and advise the anchor manager
  10955. if (index === 0) {
  10956. // TODO why are there two differently named methods? Why is there not one method that says "some end of this
  10957. // connection changed (you give the index), and here's the new element and element id."
  10958. _jsPlumb.anchorManager.sourceChanged(originalElementId, groupElId, c, groupEl);
  10959. }
  10960. else {
  10961. _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, originalElementId, groupElId, c);
  10962. c.target = groupEl;
  10963. c.targetId = groupElId;
  10964. }
  10965. // detach the original EP from the connection.
  10966. c.proxies[index].originalEp.detachFromConnection(c, null, true);
  10967. // set the proxy as the new ep
  10968. proxyEp.connections = [ c ];
  10969. c.endpoints[index] = proxyEp;
  10970. c.setVisible(true);
  10971. };
  10972. this.collapseGroup = function(group) {
  10973. group = this.getGroup(group);
  10974. if (group == null || group.collapsed) {
  10975. return;
  10976. }
  10977. var groupEl = group.getEl();
  10978. // todo remove old proxy endpoints first, just in case?
  10979. //group.proxies.length = 0;
  10980. // hide all connections
  10981. _setVisible(group, false);
  10982. if (group.shouldProxy()) {
  10983. // collapses all connections in a group.
  10984. var _collapseSet = function (conns, index) {
  10985. for (var i = 0; i < conns.length; i++) {
  10986. var c = conns[i];
  10987. _collapseConnection(c, index, group);
  10988. }
  10989. };
  10990. // setup proxies for sources and targets
  10991. _collapseSet(group.connections.source, 0);
  10992. _collapseSet(group.connections.target, 1);
  10993. }
  10994. group.collapsed = true;
  10995. _jsPlumb.removeClass(groupEl, GROUP_EXPANDED_CLASS);
  10996. _jsPlumb.addClass(groupEl, GROUP_COLLAPSED_CLASS);
  10997. _jsPlumb.revalidate(groupEl);
  10998. _jsPlumb.fire(EVT_COLLAPSE, { group:group });
  10999. };
  11000. var _expandConnection = this.expandConnection = function(c, index, group) {
  11001. // if no proxies or none for this end of the connection, abort.
  11002. if (c.proxies == null || c.proxies[index] == null) {
  11003. return;
  11004. }
  11005. var groupElId = _jsPlumb.getId(group.getEl()),
  11006. originalElement = c.proxies[index].originalEp.element,
  11007. originalElementId = c.proxies[index].originalEp.elementId;
  11008. c.endpoints[index] = c.proxies[index].originalEp;
  11009. // and advise the anchor manager
  11010. if (index === 0) {
  11011. // TODO why are there two differently named methods? Why is there not one method that says "some end of this
  11012. // connection changed (you give the index), and here's the new element and element id."
  11013. _jsPlumb.anchorManager.sourceChanged(groupElId, originalElementId, c, originalElement);
  11014. }
  11015. else {
  11016. _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, groupElId, originalElementId, c);
  11017. c.target = originalElement;
  11018. c.targetId = originalElementId;
  11019. }
  11020. // detach the proxy EP from the connection (which will cause it to be removed as we no longer need it)
  11021. c.proxies[index].ep.detachFromConnection(c, null);
  11022. c.proxies[index].originalEp.addConnection(c);
  11023. // cleanup
  11024. delete c.proxies[index];
  11025. };
  11026. this.expandGroup = function(group, doNotFireEvent) {
  11027. group = this.getGroup(group);
  11028. if (group == null || !group.collapsed) {
  11029. return;
  11030. }
  11031. var groupEl = group.getEl();
  11032. _setVisible(group, true);
  11033. if (group.shouldProxy()) {
  11034. // collapses all connections in a group.
  11035. var _expandSet = function (conns, index) {
  11036. for (var i = 0; i < conns.length; i++) {
  11037. var c = conns[i];
  11038. _expandConnection(c, index, group);
  11039. }
  11040. };
  11041. // setup proxies for sources and targets
  11042. _expandSet(group.connections.source, 0);
  11043. _expandSet(group.connections.target, 1);
  11044. }
  11045. group.collapsed = false;
  11046. _jsPlumb.addClass(groupEl, GROUP_EXPANDED_CLASS);
  11047. _jsPlumb.removeClass(groupEl, GROUP_COLLAPSED_CLASS);
  11048. _jsPlumb.revalidate(groupEl);
  11049. this.repaintGroup(group);
  11050. if (!doNotFireEvent) {
  11051. _jsPlumb.fire(EVT_EXPAND, { group: group});
  11052. }
  11053. };
  11054. this.repaintGroup = function(group) {
  11055. group = this.getGroup(group);
  11056. var m = group.getMembers();
  11057. for (var i = 0; i < m.length; i++) {
  11058. _jsPlumb.revalidate(m[i]);
  11059. }
  11060. };
  11061. // TODO refactor this with the code that responds to `connection` events.
  11062. function _updateConnectionsForGroup(group) {
  11063. var members = group.getMembers();
  11064. var c1 = _jsPlumb.getConnections({source:members, scope:"*"}, true);
  11065. var c2 = _jsPlumb.getConnections({target:members, scope:"*"}, true);
  11066. var processed = {};
  11067. group.connections.source.length = 0;
  11068. group.connections.target.length = 0;
  11069. var oneSet = function(c) {
  11070. for (var i = 0; i < c.length; i++) {
  11071. if (processed[c[i].id]) {
  11072. continue;
  11073. }
  11074. processed[c[i].id] = true;
  11075. if (c[i].source._jsPlumbGroup === group) {
  11076. if (c[i].target._jsPlumbGroup !== group) {
  11077. group.connections.source.push(c[i]);
  11078. }
  11079. _connectionSourceMap[c[i].id] = group;
  11080. }
  11081. else if (c[i].target._jsPlumbGroup === group) {
  11082. group.connections.target.push(c[i]);
  11083. _connectionTargetMap[c[i].id] = group;
  11084. }
  11085. }
  11086. };
  11087. oneSet(c1); oneSet(c2);
  11088. }
  11089. this.updateConnectionsForGroup = _updateConnectionsForGroup;
  11090. this.refreshAllGroups = function() {
  11091. for (var g in _managedGroups) {
  11092. _updateConnectionsForGroup(_managedGroups[g]);
  11093. _jsPlumb.dragManager.updateOffsets(_jsPlumb.getId(_managedGroups[g].getEl()));
  11094. }
  11095. };
  11096. };
  11097. /**
  11098. *
  11099. * @param {jsPlumbInstance} _jsPlumb Associated jsPlumb instance.
  11100. * @param {Object} params
  11101. * @param {Element} params.el The DOM element representing the Group.
  11102. * @param {String} [params.id] Optional ID for the Group. A UUID will be assigned as the Group's ID if you do not provide one.
  11103. * @param {Boolean} [params.constrain=false] If true, child elements will not be able to be dragged outside of the Group container.
  11104. * @param {Boolean} [params.revert=true] By default, child elements revert to the container if dragged outside. You can change this by setting `revert:false`. This behaviour is also overridden if you set `orphan` or `prune`.
  11105. * @param {Boolean} [params.orphan=false] If true, child elements dropped outside of the Group container will be removed from the Group (but not from the DOM).
  11106. * @param {Boolean} [params.prune=false] If true, child elements dropped outside of the Group container will be removed from the Group and also from the DOM.
  11107. * @param {Boolean} [params.dropOverride=false] If true, a child element that has been dropped onto some other Group will not be subject to the controls imposed by `prune`, `revert` or `orphan`.
  11108. * @constructor
  11109. */
  11110. var Group = function(_jsPlumb, params) {
  11111. var self = this;
  11112. var el = params.el;
  11113. this.getEl = function() { return el; };
  11114. this.id = params.id || _ju.uuid();
  11115. el._isJsPlumbGroup = true;
  11116. var getDragArea = this.getDragArea = function() {
  11117. var da = _jsPlumb.getSelector(el, GROUP_CONTAINER_SELECTOR);
  11118. return da && da.length > 0 ? da[0] : el;
  11119. };
  11120. var ghost = params.ghost === true;
  11121. var constrain = ghost || (params.constrain === true);
  11122. var revert = params.revert !== false;
  11123. var orphan = params.orphan === true;
  11124. var prune = params.prune === true;
  11125. var dropOverride = params.dropOverride === true;
  11126. var proxied = params.proxied !== false;
  11127. var elements = [];
  11128. this.connections = { source:[], target:[], internal:[] };
  11129. // this function, and getEndpoint below, are stubs for a future setup in which we can choose endpoint
  11130. // and anchor based upon the connection and the index (source/target) of the endpoint to be proxied.
  11131. this.getAnchor = function(conn, endpointIndex) {
  11132. return params.anchor || "Continuous";
  11133. };
  11134. this.getEndpoint = function(conn, endpointIndex) {
  11135. return params.endpoint || [ "Dot", { radius:10 }];
  11136. };
  11137. this.collapsed = false;
  11138. if (params.draggable !== false) {
  11139. var opts = {
  11140. stop:function(params) {
  11141. _jsPlumb.fire(EVT_GROUP_DRAG_STOP, jsPlumb.extend(params, {group:self}));
  11142. },
  11143. scope:GROUP_DRAG_SCOPE
  11144. };
  11145. if (params.dragOptions) {
  11146. root.jsPlumb.extend(opts, params.dragOptions);
  11147. }
  11148. _jsPlumb.draggable(params.el, opts);
  11149. }
  11150. if (params.droppable !== false) {
  11151. _jsPlumb.droppable(params.el, {
  11152. drop:function(p) {
  11153. var el = p.drag.el;
  11154. if (el._isJsPlumbGroup) {
  11155. return;
  11156. }
  11157. var currentGroup = el._jsPlumbGroup;
  11158. if (currentGroup !== self) {
  11159. if (currentGroup != null) {
  11160. if (currentGroup.overrideDrop(el, self)) {
  11161. return;
  11162. }
  11163. }
  11164. _jsPlumb.getGroupManager().addToGroup(self, el, false);
  11165. }
  11166. }
  11167. });
  11168. }
  11169. var _each = function(_el, fn) {
  11170. var els = _el.nodeType == null ? _el : [ _el ];
  11171. for (var i = 0; i < els.length; i++) {
  11172. fn(els[i]);
  11173. }
  11174. };
  11175. this.overrideDrop = function(_el, targetGroup) {
  11176. return dropOverride && (revert || prune || orphan);
  11177. };
  11178. this.add = function(_el, doNotFireEvent) {
  11179. var dragArea = getDragArea();
  11180. _each(_el, function(__el) {
  11181. if (__el._jsPlumbGroup != null) {
  11182. if (__el._jsPlumbGroup === self) {
  11183. return;
  11184. } else {
  11185. __el._jsPlumbGroup.remove(__el, true, doNotFireEvent, false);
  11186. }
  11187. }
  11188. __el._jsPlumbGroup = self;
  11189. elements.push(__el);
  11190. // test if draggable and add handlers if so.
  11191. if (_jsPlumb.isAlreadyDraggable(__el)) {
  11192. _bindDragHandlers(__el);
  11193. }
  11194. if (__el.parentNode !== dragArea) {
  11195. dragArea.appendChild(__el);
  11196. }
  11197. if (!doNotFireEvent) {
  11198. _jsPlumb.fire(EVT_CHILD_ADDED, {group: self, el: __el});
  11199. }
  11200. });
  11201. _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
  11202. };
  11203. this.remove = function(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections) {
  11204. _each(el, function(__el) {
  11205. delete __el._jsPlumbGroup;
  11206. _ju.removeWithFunction(elements, function(e) {
  11207. return e === __el;
  11208. });
  11209. if (manipulateDOM) {
  11210. try { self.getDragArea().removeChild(__el); }
  11211. catch (e) {
  11212. jsPlumbUtil.log("Could not remove element from Group " + e);
  11213. }
  11214. }
  11215. _unbindDragHandlers(__el);
  11216. if (!doNotFireEvent) {
  11217. _jsPlumb.fire(EVT_CHILD_REMOVED, {group: self, el: __el});
  11218. }
  11219. });
  11220. if (!doNotUpdateConnections) {
  11221. _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
  11222. }
  11223. };
  11224. this.removeAll = function(manipulateDOM, doNotFireEvent) {
  11225. for (var i = 0, l = elements.length; i < l; i++) {
  11226. self.remove(elements[0], manipulateDOM, doNotFireEvent, true);
  11227. }
  11228. elements.length = 0;
  11229. _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
  11230. };
  11231. this.orphanAll = function() {
  11232. for (var i = 0; i < elements.length; i++) {
  11233. _orphan(elements[i]);
  11234. }
  11235. elements.length = 0;
  11236. };
  11237. this.getMembers = function() { return elements; };
  11238. el[GROUP] = this;
  11239. _jsPlumb.bind(ELEMENT_DRAGGABLE_EVENT, function(dragParams) {
  11240. // if its for the current group,
  11241. if (dragParams.el._jsPlumbGroup === this) {
  11242. _bindDragHandlers(dragParams.el);
  11243. }
  11244. }.bind(this));
  11245. function _findParent(_el) {
  11246. return _el.offsetParent;
  11247. }
  11248. function _isInsideParent(_el, pos) {
  11249. var p = _findParent(_el),
  11250. s = _jsPlumb.getSize(p),
  11251. ss = _jsPlumb.getSize(_el),
  11252. leftEdge = pos[0],
  11253. rightEdge = leftEdge + ss[0],
  11254. topEdge = pos[1],
  11255. bottomEdge = topEdge + ss[1];
  11256. return rightEdge > 0 && leftEdge < s[0] && bottomEdge > 0 && topEdge < s[1];
  11257. }
  11258. //
  11259. // orphaning an element means taking it out of the group and adding it to the main jsplumb container.
  11260. //
  11261. function _orphan(_el) {
  11262. var id = _jsPlumb.getId(_el);
  11263. var pos = _jsPlumb.getOffset(_el);
  11264. _el.parentNode.removeChild(_el);
  11265. _jsPlumb.getContainer().appendChild(_el);
  11266. _jsPlumb.setPosition(_el, pos);
  11267. delete _el._jsPlumbGroup;
  11268. _unbindDragHandlers(_el);
  11269. _jsPlumb.dragManager.clearParent(_el, id);
  11270. }
  11271. //
  11272. // remove an element from the group, then either prune it from the jsplumb instance, or just orphan it.
  11273. //
  11274. function _pruneOrOrphan(p) {
  11275. if (!_isInsideParent(p.el, p.pos)) {
  11276. var group = p.el._jsPlumbGroup;
  11277. if (prune) {
  11278. _jsPlumb.remove(p.el);
  11279. } else {
  11280. _orphan(p.el);
  11281. }
  11282. group.remove(p.el);
  11283. }
  11284. }
  11285. //
  11286. // redraws the element
  11287. //
  11288. function _revalidate(_el) {
  11289. var id = _jsPlumb.getId(_el);
  11290. _jsPlumb.revalidate(_el);
  11291. _jsPlumb.dragManager.revalidateParent(_el, id);
  11292. }
  11293. //
  11294. // unbind the group specific drag/revert handlers.
  11295. //
  11296. function _unbindDragHandlers(_el) {
  11297. if (!_el._katavorioDrag) {
  11298. return;
  11299. }
  11300. if (prune || orphan) {
  11301. _el._katavorioDrag.off(STOP, _pruneOrOrphan);
  11302. }
  11303. if (!prune && !orphan && revert) {
  11304. _el._katavorioDrag.off(REVERT, _revalidate);
  11305. _el._katavorioDrag.setRevert(null);
  11306. }
  11307. }
  11308. function _bindDragHandlers(_el) {
  11309. if (!_el._katavorioDrag) {
  11310. return;
  11311. }
  11312. if (prune || orphan) {
  11313. _el._katavorioDrag.on(STOP, _pruneOrOrphan);
  11314. }
  11315. if (constrain) {
  11316. _el._katavorioDrag.setConstrain(true);
  11317. }
  11318. if (ghost) {
  11319. _el._katavorioDrag.setUseGhostProxy(true);
  11320. }
  11321. if (!prune && !orphan && revert) {
  11322. _el._katavorioDrag.on(REVERT, _revalidate);
  11323. _el._katavorioDrag.setRevert(function(__el, pos) {
  11324. return !_isInsideParent(__el, pos);
  11325. });
  11326. }
  11327. }
  11328. this.shouldProxy = function() {
  11329. return proxied;
  11330. };
  11331. _jsPlumb.getGroupManager().addGroup(this);
  11332. };
  11333. /**
  11334. * Adds a group to the jsPlumb instance.
  11335. * @method addGroup
  11336. * @param {Object} params
  11337. * @return {Group} The newly created Group.
  11338. */
  11339. _jpi.prototype.addGroup = function(params) {
  11340. var j = this;
  11341. j._groups = j._groups || {};
  11342. if (j._groups[params.id] != null) {
  11343. throw new TypeError("cannot create Group [" + params.id + "]; a Group with that ID exists");
  11344. }
  11345. if (params.el[GROUP] != null) {
  11346. throw new TypeError("cannot create Group [" + params.id + "]; the given element is already a Group");
  11347. }
  11348. var group = new Group(j, params);
  11349. j._groups[group.id] = group;
  11350. if (params.collapsed) {
  11351. this.collapseGroup(group);
  11352. }
  11353. return group;
  11354. };
  11355. /**
  11356. * Add an element to a group.
  11357. * @method addToGroup
  11358. * @param {String} group Group, or ID of the group, to add the element to.
  11359. * @param {Element} el Element to add to the group.
  11360. */
  11361. _jpi.prototype.addToGroup = function(group, el, doNotFireEvent) {
  11362. var _one = function(_el) {
  11363. var id = this.getId(_el);
  11364. this.manage(id, _el);
  11365. this.getGroupManager().addToGroup(group, _el, doNotFireEvent);
  11366. }.bind(this);
  11367. if (Array.isArray(el)) {
  11368. for (var i = 0; i < el.length; i++) {
  11369. _one(el[i]);
  11370. }
  11371. } else {
  11372. _one(el);
  11373. }
  11374. };
  11375. /**
  11376. * Remove an element from a group.
  11377. * @method removeFromGroup
  11378. * @param {String} group Group, or ID of the group, to remove the element from.
  11379. * @param {Element} el Element to add to the group.
  11380. */
  11381. _jpi.prototype.removeFromGroup = function(group, el, doNotFireEvent) {
  11382. this.getGroupManager().removeFromGroup(group, el, doNotFireEvent);
  11383. };
  11384. /**
  11385. * Remove a group, and optionally remove its members from the jsPlumb instance.
  11386. * @method removeGroup
  11387. * @param {String|Group} group Group to delete, or ID of Group to delete.
  11388. * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will
  11389. * just be 'orphaned' (returned to the main container).
  11390. */
  11391. _jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
  11392. this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent);
  11393. };
  11394. /**
  11395. * Remove all groups, and optionally remove their members from the jsPlumb instance.
  11396. * @method removeAllGroup
  11397. * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will
  11398. * just be 'orphaned' (returned to the main container).
  11399. */
  11400. _jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
  11401. this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent);
  11402. };
  11403. /**
  11404. * Get a Group
  11405. * @method getGroup
  11406. * @param {String} groupId ID of the group to get
  11407. * @return {Group} Group with the given ID, null if not found.
  11408. */
  11409. _jpi.prototype.getGroup = function(groupId) {
  11410. return this.getGroupManager().getGroup(groupId);
  11411. };
  11412. /**
  11413. * Gets all the Groups managed by the jsPlumb instance.
  11414. * @returns {Group[]} List of Groups. Empty if none.
  11415. */
  11416. _jpi.prototype.getGroups = function() {
  11417. return this.getGroupManager().getGroups();
  11418. };
  11419. /**
  11420. * Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group
  11421. * will vary from application to application. jsPlumb does these things:
  11422. *
  11423. * - Hides any connections that are internal to the group (connections between members, and connections from member of
  11424. * the group to the group itself)
  11425. * - Proxies all connections for which the source or target is a member of the group.
  11426. * - Hides the proxied connections.
  11427. * - Adds the jtk-group-expanded class to the group's element
  11428. * - Removes the jtk-group-collapsed class from the group's element.
  11429. *
  11430. * @method expandGroup
  11431. * @param {String|Group} group Group to expand, or ID of Group to expand.
  11432. */
  11433. _jpi.prototype.expandGroup = function(group) {
  11434. this.getGroupManager().expandGroup(group);
  11435. };
  11436. /**
  11437. * Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group
  11438. * will vary from application to application. jsPlumb does these things:
  11439. *
  11440. * - Shows any connections that are internal to the group (connections between members, and connections from member of
  11441. * the group to the group itself)
  11442. * - Removes proxies for all connections for which the source or target is a member of the group.
  11443. * - Shows the previously proxied connections.
  11444. * - Adds the jtk-group-collapsed class to the group's element
  11445. * - Removes the jtk-group-expanded class from the group's element.
  11446. *
  11447. * @method expandGroup
  11448. * @param {String|Group} group Group to expand, or ID of Group to expand.
  11449. */
  11450. _jpi.prototype.collapseGroup = function(groupId) {
  11451. this.getGroupManager().collapseGroup(groupId);
  11452. };
  11453. _jpi.prototype.repaintGroup = function(group) {
  11454. this.getGroupManager().repaintGroup(group);
  11455. };
  11456. /**
  11457. * Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method.
  11458. *
  11459. * @method toggleGroup
  11460. * @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse.
  11461. */
  11462. _jpi.prototype.toggleGroup = function(group) {
  11463. group = this.getGroupManager().getGroup(group);
  11464. if (group != null) {
  11465. this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group);
  11466. }
  11467. };
  11468. //
  11469. // lazy init a group manager for the given jsplumb instance.
  11470. //
  11471. _jpi.prototype.getGroupManager = function() {
  11472. var mgr = this[GROUP_MANAGER];
  11473. if (mgr == null) {
  11474. mgr = this[GROUP_MANAGER] = new GroupManager(this);
  11475. }
  11476. return mgr;
  11477. };
  11478. _jpi.prototype.removeGroupManager = function() {
  11479. delete this[GROUP_MANAGER];
  11480. };
  11481. /**
  11482. * Gets the Group that the given element belongs to, null if none.
  11483. * @method getGroupFor
  11484. * @param {String|Element} el Element, or element ID.
  11485. * @returns {Group} A Group, if found, or null.
  11486. */
  11487. _jpi.prototype.getGroupFor = function(el) {
  11488. el = this.getElement(el);
  11489. if (el) {
  11490. return el[GROUP];
  11491. }
  11492. };
  11493. }).call(typeof window !== 'undefined' ? window : this);
  11494. /*
  11495. * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
  11496. *
  11497. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  11498. *
  11499. * https://jsplumbtoolkit.com
  11500. * https://github.com/jsplumb/jsplumb
  11501. *
  11502. * Dual licensed under the MIT and GPL2 licenses.
  11503. */
  11504. ;
  11505. (function () {
  11506. "use strict";
  11507. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11508. var STRAIGHT = "Straight";
  11509. var ARC = "Arc";
  11510. var Flowchart = function (params) {
  11511. this.type = "Flowchart";
  11512. params = params || {};
  11513. params.stub = params.stub == null ? 30 : params.stub;
  11514. var segments,
  11515. _super = _jp.Connectors.AbstractConnector.apply(this, arguments),
  11516. midpoint = params.midpoint == null ? 0.5 : params.midpoint,
  11517. alwaysRespectStubs = params.alwaysRespectStubs === true,
  11518. lastx = null, lasty = null, lastOrientation,
  11519. cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0,
  11520. // TODO now common between this and AbstractBezierEditor; refactor into superclass?
  11521. loopbackRadius = params.loopbackRadius || 25,
  11522. isLoopbackCurrently = false,
  11523. sgn = function (n) {
  11524. return n < 0 ? -1 : n === 0 ? 0 : 1;
  11525. },
  11526. segmentDirections = function(segment) {
  11527. return [
  11528. sgn( segment[2] - segment[0] ),
  11529. sgn( segment[3] - segment[1] )
  11530. ];
  11531. },
  11532. /**
  11533. * helper method to add a segment.
  11534. */
  11535. addSegment = function (segments, x, y, paintInfo) {
  11536. if (lastx === x && lasty === y) {
  11537. return;
  11538. }
  11539. var lx = lastx == null ? paintInfo.sx : lastx,
  11540. ly = lasty == null ? paintInfo.sy : lasty,
  11541. o = lx === x ? "v" : "h";
  11542. lastx = x;
  11543. lasty = y;
  11544. segments.push([ lx, ly, x, y, o ]);
  11545. },
  11546. segLength = function (s) {
  11547. return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2));
  11548. },
  11549. _cloneArray = function (a) {
  11550. var _a = [];
  11551. _a.push.apply(_a, a);
  11552. return _a;
  11553. },
  11554. writeSegments = function (conn, segments, paintInfo) {
  11555. var current = null, next, currentDirection, nextDirection;
  11556. for (var i = 0; i < segments.length - 1; i++) {
  11557. current = current || _cloneArray(segments[i]);
  11558. next = _cloneArray(segments[i + 1]);
  11559. currentDirection = segmentDirections(current);
  11560. nextDirection = segmentDirections(next);
  11561. if (cornerRadius > 0 && current[4] !== next[4]) {
  11562. var radiusToUse = Math.min(cornerRadius, segLength(current), segLength(next));
  11563. current[2] -= currentDirection[0] * radiusToUse;
  11564. current[3] -= currentDirection[1] * radiusToUse;
  11565. next[0] += nextDirection[0] * radiusToUse;
  11566. next[1] += nextDirection[1] * radiusToUse;
  11567. var ac = (currentDirection[1] === nextDirection[0] && nextDirection[0] === 1) ||
  11568. ((currentDirection[1] === nextDirection[0] && nextDirection[0] === 0) && currentDirection[0] !== nextDirection[1]) ||
  11569. (currentDirection[1] === nextDirection[0] && nextDirection[0] === -1),
  11570. sgny = next[1] > current[3] ? 1 : -1,
  11571. sgnx = next[0] > current[2] ? 1 : -1,
  11572. sgnEqual = sgny === sgnx,
  11573. cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2],
  11574. cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1];
  11575. _super.addSegment(conn, STRAIGHT, {
  11576. x1: current[0], y1: current[1], x2: current[2], y2: current[3]
  11577. });
  11578. _super.addSegment(conn, ARC, {
  11579. r: radiusToUse,
  11580. x1: current[2],
  11581. y1: current[3],
  11582. x2: next[0],
  11583. y2: next[1],
  11584. cx: cx,
  11585. cy: cy,
  11586. ac: ac
  11587. });
  11588. }
  11589. else {
  11590. // dx + dy are used to adjust for line width.
  11591. var dx = (current[2] === current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2),
  11592. dy = (current[3] === current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2);
  11593. _super.addSegment(conn, STRAIGHT, {
  11594. x1: current[0] - dx, y1: current[1] - dy, x2: current[2] + dx, y2: current[3] + dy
  11595. });
  11596. }
  11597. current = next;
  11598. }
  11599. if (next != null) {
  11600. // last segment
  11601. _super.addSegment(conn, STRAIGHT, {
  11602. x1: next[0], y1: next[1], x2: next[2], y2: next[3]
  11603. });
  11604. }
  11605. };
  11606. this._compute = function (paintInfo, params) {
  11607. segments = [];
  11608. lastx = null;
  11609. lasty = null;
  11610. lastOrientation = null;
  11611. var geometry = this.getGeometry(),
  11612. sp = [ paintInfo.x, paintInfo.y ],
  11613. tp = [ paintInfo.x + paintInfo.w, paintInfo.y + paintInfo.h ];
  11614. if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.segments != null && geometry.segments.length > 0) {
  11615. segments = geometry.segments;
  11616. _super.setGeometry({
  11617. segments:segments,
  11618. sourcePos:sp,
  11619. targetPos:tp
  11620. });
  11621. } else {
  11622. var commonStubCalculator = function () {
  11623. return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY];
  11624. },
  11625. stubCalculators = {
  11626. perpendicular: commonStubCalculator,
  11627. orthogonal: commonStubCalculator,
  11628. opposite: function (axis) {
  11629. var pi = paintInfo,
  11630. idx = axis === "x" ? 0 : 1,
  11631. areInProximity = {
  11632. "x": function () {
  11633. return ( (pi.so[idx] === 1 && (
  11634. ( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) ||
  11635. ( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) ||
  11636. ( (pi.so[idx] === -1 && (
  11637. ( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) ||
  11638. ( (pi.sx < pi.endStubX) && (pi.tx < pi.sx)))));
  11639. },
  11640. "y": function () {
  11641. return ( (pi.so[idx] === 1 && (
  11642. ( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) ||
  11643. ( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) ||
  11644. ( (pi.so[idx] === -1 && (
  11645. ( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) ||
  11646. ( (pi.sy < pi.endStubY) && (pi.ty < pi.sy)))));
  11647. }
  11648. };
  11649. if (!alwaysRespectStubs && areInProximity[axis]()) {
  11650. return {
  11651. "x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY],
  11652. "y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2]
  11653. }[axis];
  11654. }
  11655. else {
  11656. return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY];
  11657. }
  11658. }
  11659. };
  11660. // calculate Stubs.
  11661. var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis),
  11662. idx = paintInfo.sourceAxis === "x" ? 0 : 1,
  11663. oidx = paintInfo.sourceAxis === "x" ? 1 : 0,
  11664. ss = stubs[idx],
  11665. oss = stubs[oidx],
  11666. es = stubs[idx + 2],
  11667. oes = stubs[oidx + 2];
  11668. // add the start stub segment. use stubs for loopback as it will look better, with the loop spaced
  11669. // away from the element.
  11670. addSegment(segments, stubs[0], stubs[1], paintInfo);
  11671. // if its a loopback and we should treat it differently.
  11672. // if (false && params.sourcePos[0] === params.targetPos[0] && params.sourcePos[1] === params.targetPos[1]) {
  11673. //
  11674. // // we use loopbackRadius here, as statemachine connectors do.
  11675. // // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius,
  11676. // // down by 2*radius, left by radius.
  11677. // addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo);
  11678. // addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
  11679. // addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
  11680. // addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo);
  11681. // addSegment(segments, stubs[0], stubs[1], paintInfo);
  11682. //
  11683. // }
  11684. // else {
  11685. var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint),
  11686. midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint);
  11687. var orientations = {x: [0, 1], y: [1, 0]},
  11688. lineCalculators = {
  11689. perpendicular: function (axis) {
  11690. var pi = paintInfo,
  11691. sis = {
  11692. x: [
  11693. [[1, 2, 3, 4], null, [2, 1, 4, 3]],
  11694. null,
  11695. [[4, 3, 2, 1], null, [3, 4, 1, 2]]
  11696. ],
  11697. y: [
  11698. [[3, 2, 1, 4], null, [2, 3, 4, 1]],
  11699. null,
  11700. [[4, 1, 2, 3], null, [1, 4, 3, 2]]
  11701. ]
  11702. },
  11703. stubs = {
  11704. x: [[pi.startStubX, pi.endStubX], null, [pi.endStubX, pi.startStubX]],
  11705. y: [[pi.startStubY, pi.endStubY], null, [pi.endStubY, pi.startStubY]]
  11706. },
  11707. midLines = {
  11708. x: [[midx, pi.startStubY], [midx, pi.endStubY]],
  11709. y: [[pi.startStubX, midy], [pi.endStubX, midy]]
  11710. },
  11711. linesToEnd = {
  11712. x: [[pi.endStubX, pi.startStubY]],
  11713. y: [[pi.startStubX, pi.endStubY]]
  11714. },
  11715. startToEnd = {
  11716. x: [[pi.startStubX, pi.endStubY], [pi.endStubX, pi.endStubY]],
  11717. y: [[pi.endStubX, pi.startStubY], [pi.endStubX, pi.endStubY]]
  11718. },
  11719. startToMidToEnd = {
  11720. x: [[pi.startStubX, midy], [pi.endStubX, midy], [pi.endStubX, pi.endStubY]],
  11721. y: [[midx, pi.startStubY], [midx, pi.endStubY], [pi.endStubX, pi.endStubY]]
  11722. },
  11723. otherStubs = {
  11724. x: [pi.startStubY, pi.endStubY],
  11725. y: [pi.startStubX, pi.endStubX]
  11726. },
  11727. soIdx = orientations[axis][0], toIdx = orientations[axis][1],
  11728. _so = pi.so[soIdx] + 1,
  11729. _to = pi.to[toIdx] + 1,
  11730. otherFlipped = (pi.to[toIdx] === -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] === 1 && (otherStubs[axis][1] > otherStubs[axis][0])),
  11731. stub1 = stubs[axis][_so][0],
  11732. stub2 = stubs[axis][_so][1],
  11733. segmentIndexes = sis[axis][_so][_to];
  11734. if (pi.segment === segmentIndexes[3] || (pi.segment === segmentIndexes[2] && otherFlipped)) {
  11735. return midLines[axis];
  11736. }
  11737. else if (pi.segment === segmentIndexes[2] && stub2 < stub1) {
  11738. return linesToEnd[axis];
  11739. }
  11740. else if ((pi.segment === segmentIndexes[2] && stub2 >= stub1) || (pi.segment === segmentIndexes[1] && !otherFlipped)) {
  11741. return startToMidToEnd[axis];
  11742. }
  11743. else if (pi.segment === segmentIndexes[0] || (pi.segment === segmentIndexes[1] && otherFlipped)) {
  11744. return startToEnd[axis];
  11745. }
  11746. },
  11747. orthogonal: function (axis, startStub, otherStartStub, endStub, otherEndStub) {
  11748. var pi = paintInfo,
  11749. extent = {
  11750. "x": pi.so[0] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub),
  11751. "y": pi.so[1] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub)
  11752. }[axis];
  11753. return {
  11754. "x": [
  11755. [extent, otherStartStub],
  11756. [extent, otherEndStub],
  11757. [endStub, otherEndStub]
  11758. ],
  11759. "y": [
  11760. [otherStartStub, extent],
  11761. [otherEndStub, extent],
  11762. [otherEndStub, endStub]
  11763. ]
  11764. }[axis];
  11765. },
  11766. opposite: function (axis, ss, oss, es) {
  11767. var pi = paintInfo,
  11768. otherAxis = {"x": "y", "y": "x"}[axis],
  11769. dim = {"x": "height", "y": "width"}[axis],
  11770. comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"];
  11771. if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) {
  11772. var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub;
  11773. return {
  11774. "x": [
  11775. [ss, _val],
  11776. [es, _val]
  11777. ],
  11778. "y": [
  11779. [_val, ss],
  11780. [_val, es]
  11781. ]
  11782. }[axis];
  11783. }
  11784. else if (!comparator || (pi.so[idx] === 1 && ss > es) || (pi.so[idx] === -1 && ss < es)) {
  11785. return {
  11786. "x": [
  11787. [ss, midy],
  11788. [es, midy]
  11789. ],
  11790. "y": [
  11791. [midx, ss],
  11792. [midx, es]
  11793. ]
  11794. }[axis];
  11795. }
  11796. else if ((pi.so[idx] === 1 && ss < es) || (pi.so[idx] === -1 && ss > es)) {
  11797. return {
  11798. "x": [
  11799. [midx, pi.sy],
  11800. [midx, pi.ty]
  11801. ],
  11802. "y": [
  11803. [pi.sx, midy],
  11804. [pi.tx, midy]
  11805. ]
  11806. }[axis];
  11807. }
  11808. }
  11809. };
  11810. // compute the rest of the line
  11811. var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes);
  11812. if (p) {
  11813. for (var i = 0; i < p.length; i++) {
  11814. addSegment(segments, p[i][0], p[i][1], paintInfo);
  11815. }
  11816. }
  11817. // line to end stub
  11818. addSegment(segments, stubs[2], stubs[3], paintInfo);
  11819. //}
  11820. // end stub to end (common)
  11821. addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo);
  11822. _super.setGeometry({
  11823. segments:segments,
  11824. sourcePos:sp,
  11825. targetPos:tp
  11826. }, true);
  11827. }
  11828. // write out the segments.
  11829. writeSegments(this, segments, paintInfo);
  11830. };
  11831. };
  11832. _jp.Connectors.Flowchart = Flowchart;
  11833. _ju.extend(_jp.Connectors.Flowchart, _jp.Connectors.AbstractConnector);
  11834. }).call(typeof window !== 'undefined' ? window : this);
  11835. /*
  11836. * This file contains the code for the Bezier connector type.
  11837. *
  11838. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  11839. *
  11840. * https://jsplumbtoolkit.com
  11841. * https://github.com/jsplumb/jsplumb
  11842. *
  11843. * Dual licensed under the MIT and GPL2 licenses.
  11844. */
  11845. ;
  11846. (function () {
  11847. "use strict";
  11848. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11849. _jp.Connectors.AbstractBezierConnector = function(params) {
  11850. params = params || {};
  11851. var showLoopback = params.showLoopback !== false,
  11852. curviness = params.curviness || 10,
  11853. margin = params.margin || 5,
  11854. proximityLimit = params.proximityLimit || 80,
  11855. clockwise = params.orientation && params.orientation === "clockwise",
  11856. loopbackRadius = params.loopbackRadius || 25,
  11857. isLoopbackCurrently = false,
  11858. _super;
  11859. this.overrideSetEditable = function() { return !isLoopbackCurrently; };
  11860. this._compute = function (paintInfo, p) {
  11861. var sp = p.sourcePos,
  11862. tp = p.targetPos,
  11863. _w = Math.abs(sp[0] - tp[0]),
  11864. _h = Math.abs(sp[1] - tp[1]);
  11865. if (!showLoopback || (p.sourceEndpoint.elementId !== p.targetEndpoint.elementId)) {
  11866. isLoopbackCurrently = false;
  11867. this._computeBezier(paintInfo, p, sp, tp, _w, _h);
  11868. } else {
  11869. isLoopbackCurrently = true;
  11870. // a loopback connector. draw an arc from one anchor to the other.
  11871. var x1 = p.sourcePos[0], y1 = p.sourcePos[1] - margin,
  11872. cx = x1, cy = y1 - loopbackRadius,
  11873. // canvas sizing stuff, to ensure the whole painted area is visible.
  11874. _x = cx - loopbackRadius,
  11875. _y = cy - loopbackRadius;
  11876. _w = 2 * loopbackRadius;
  11877. _h = 2 * loopbackRadius;
  11878. paintInfo.points[0] = _x;
  11879. paintInfo.points[1] = _y;
  11880. paintInfo.points[2] = _w;
  11881. paintInfo.points[3] = _h;
  11882. // ADD AN ARC SEGMENT.
  11883. _super.addSegment(this, "Arc", {
  11884. loopback: true,
  11885. x1: (x1 - _x) + 4,
  11886. y1: y1 - _y,
  11887. startAngle: 0,
  11888. endAngle: 2 * Math.PI,
  11889. r: loopbackRadius,
  11890. ac: !clockwise,
  11891. x2: (x1 - _x) - 4,
  11892. y2: y1 - _y,
  11893. cx: cx - _x,
  11894. cy: cy - _y
  11895. });
  11896. }
  11897. };
  11898. _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
  11899. return _super;
  11900. };
  11901. _ju.extend(_jp.Connectors.AbstractBezierConnector, _jp.Connectors.AbstractConnector);
  11902. var Bezier = function (params) {
  11903. params = params || {};
  11904. this.type = "Bezier";
  11905. var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
  11906. majorAnchor = params.curviness || 150,
  11907. minorAnchor = 10;
  11908. this.getCurviness = function () {
  11909. return majorAnchor;
  11910. };
  11911. this._findControlPoint = function (point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, soo, too) {
  11912. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  11913. // points around if so (code could be tightened up)
  11914. var perpendicular = soo[0] !== too[0] || soo[1] === too[1],
  11915. p = [];
  11916. if (!perpendicular) {
  11917. if (soo[0] === 0) {
  11918. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
  11919. }
  11920. else {
  11921. p.push(point[0] - (majorAnchor * soo[0]));
  11922. }
  11923. if (soo[1] === 0) {
  11924. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
  11925. }
  11926. else {
  11927. p.push(point[1] + (majorAnchor * too[1]));
  11928. }
  11929. }
  11930. else {
  11931. if (too[0] === 0) {
  11932. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
  11933. }
  11934. else {
  11935. p.push(point[0] + (majorAnchor * too[0]));
  11936. }
  11937. if (too[1] === 0) {
  11938. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
  11939. }
  11940. else {
  11941. p.push(point[1] + (majorAnchor * soo[1]));
  11942. }
  11943. }
  11944. return p;
  11945. };
  11946. this._computeBezier = function (paintInfo, p, sp, tp, _w, _h) {
  11947. var geometry = this.getGeometry(), _CP, _CP2,
  11948. _sx = sp[0] < tp[0] ? _w : 0,
  11949. _sy = sp[1] < tp[1] ? _h : 0,
  11950. _tx = sp[0] < tp[0] ? 0 : _w,
  11951. _ty = sp[1] < tp[1] ? 0 : _h;
  11952. if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.controlPoints != null && geometry.controlPoints[0] != null && geometry.controlPoints[1] != null) {
  11953. _CP = geometry.controlPoints[0];
  11954. _CP2 = geometry.controlPoints[1];
  11955. }
  11956. else {
  11957. _CP = this._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint, paintInfo.so, paintInfo.to);
  11958. _CP2 = this._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint, paintInfo.to, paintInfo.so);
  11959. }
  11960. _super.setGeometry({
  11961. controlPoints:[_CP, _CP2],
  11962. sourcePos:sp,
  11963. targetPos:tp
  11964. }, true);
  11965. _super.addSegment(this, "Bezier", {
  11966. x1: _sx, y1: _sy, x2: _tx, y2: _ty,
  11967. cp1x: _CP[0], cp1y: _CP[1], cp2x: _CP2[0], cp2y: _CP2[1]
  11968. });
  11969. };
  11970. };
  11971. _jp.Connectors.Bezier = Bezier;
  11972. _ju.extend(Bezier, _jp.Connectors.AbstractBezierConnector);
  11973. }).call(typeof window !== 'undefined' ? window : this);
  11974. /*
  11975. * This file contains the state machine connectors, which extend AbstractBezierConnector.
  11976. *
  11977. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  11978. *
  11979. * https://jsplumbtoolkit.com
  11980. * https://github.com/jsplumb/jsplumb
  11981. *
  11982. * Dual licensed under the MIT and GPL2 licenses.
  11983. */
  11984. ;
  11985. (function () {
  11986. "use strict";
  11987. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11988. var _segment = function (x1, y1, x2, y2) {
  11989. if (x1 <= x2 && y2 <= y1) {
  11990. return 1;
  11991. }
  11992. else if (x1 <= x2 && y1 <= y2) {
  11993. return 2;
  11994. }
  11995. else if (x2 <= x1 && y2 >= y1) {
  11996. return 3;
  11997. }
  11998. return 4;
  11999. },
  12000. // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the
  12001. // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they
  12002. // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the
  12003. // 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
  12004. // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element
  12005. // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left.
  12006. //
  12007. // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are:
  12008. //
  12009. // 0 - absolute x
  12010. // 1 - absolute y
  12011. // 2 - proportional x in element (0 is left edge, 1 is right edge)
  12012. // 3 - proportional y in element (0 is top edge, 1 is bottom edge)
  12013. //
  12014. _findControlPoint = function (midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) {
  12015. // TODO (maybe)
  12016. // - if anchor pos is 0.5, make the control point take into account the relative position of the elements.
  12017. if (distance <= proximityLimit) {
  12018. return [midx, midy];
  12019. }
  12020. if (segment === 1) {
  12021. if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) {
  12022. return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  12023. }
  12024. else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) {
  12025. return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  12026. }
  12027. else {
  12028. return [ midx + (-1 * dx) , midy + (-1 * dy) ];
  12029. }
  12030. }
  12031. else if (segment === 2) {
  12032. if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) {
  12033. return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  12034. }
  12035. else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) {
  12036. return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  12037. }
  12038. else {
  12039. return [ midx + dx, midy + (-1 * dy) ];
  12040. }
  12041. }
  12042. else if (segment === 3) {
  12043. if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) {
  12044. return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  12045. }
  12046. else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) {
  12047. return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  12048. }
  12049. else {
  12050. return [ midx + (-1 * dx) , midy + (-1 * dy) ];
  12051. }
  12052. }
  12053. else if (segment === 4) {
  12054. if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) {
  12055. return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  12056. }
  12057. else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) {
  12058. return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  12059. }
  12060. else {
  12061. return [ midx + dx , midy + (-1 * dy) ];
  12062. }
  12063. }
  12064. };
  12065. var StateMachine = function (params) {
  12066. params = params || {};
  12067. this.type = "StateMachine";
  12068. var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
  12069. curviness = params.curviness || 10,
  12070. margin = params.margin || 5,
  12071. proximityLimit = params.proximityLimit || 80,
  12072. clockwise = params.orientation && params.orientation === "clockwise",
  12073. _controlPoint;
  12074. this._computeBezier = function(paintInfo, params, sp, tp, w, h) {
  12075. var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w,
  12076. _sy = params.sourcePos[1] < params.targetPos[1] ? 0 : h,
  12077. _tx = params.sourcePos[0] < params.targetPos[0] ? w : 0,
  12078. _ty = params.sourcePos[1] < params.targetPos[1] ? h : 0;
  12079. // now adjust for the margin
  12080. if (params.sourcePos[2] === 0) {
  12081. _sx -= margin;
  12082. }
  12083. if (params.sourcePos[2] === 1) {
  12084. _sx += margin;
  12085. }
  12086. if (params.sourcePos[3] === 0) {
  12087. _sy -= margin;
  12088. }
  12089. if (params.sourcePos[3] === 1) {
  12090. _sy += margin;
  12091. }
  12092. if (params.targetPos[2] === 0) {
  12093. _tx -= margin;
  12094. }
  12095. if (params.targetPos[2] === 1) {
  12096. _tx += margin;
  12097. }
  12098. if (params.targetPos[3] === 0) {
  12099. _ty -= margin;
  12100. }
  12101. if (params.targetPos[3] === 1) {
  12102. _ty += margin;
  12103. }
  12104. //
  12105. // these connectors are quadratic bezier curves, having a single control point. if both anchors
  12106. // are located at 0.5 on their respective faces, the control point is set to the midpoint and you
  12107. // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since
  12108. // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned
  12109. // at 'curviness' pixels away along the normal to the straight line connecting the two anchors.
  12110. //
  12111. // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes
  12112. // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node,
  12113. // for example, we might increase the distance the control point is away from the midpoint in a bid to
  12114. // steer it around that node. this will work within limits, but i think those limits would also be the likely
  12115. // limits for, once again, aesthetic good sense in the layout of a chart using these connectors.
  12116. //
  12117. // the second possible change is actually two possible changes: firstly, it is possible we should gradually
  12118. // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some
  12119. // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors
  12120. // with respect to how far their anchor is from the center of its respective face. this could either look cool,
  12121. // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time.
  12122. //
  12123. var _midx = (_sx + _tx) / 2,
  12124. _midy = (_sy + _ty) / 2,
  12125. segment = _segment(_sx, _sy, _tx, _ty),
  12126. distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)),
  12127. cp1x, cp2x, cp1y, cp2y,
  12128. geometry = _super.getGeometry();
  12129. if ((this.hasBeenEdited() || this.isEditing()) && geometry != null) {
  12130. cp1x = geometry.controlPoints[0][0];
  12131. cp1y = geometry.controlPoints[0][1];
  12132. cp2x = geometry.controlPoints[1][0];
  12133. cp2y = geometry.controlPoints[1][1];
  12134. }
  12135. else {
  12136. // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it
  12137. // will work by extending the control point to force the curve to be, um, curvier.
  12138. _controlPoint = _findControlPoint(_midx,
  12139. _midy,
  12140. segment,
  12141. params.sourcePos,
  12142. params.targetPos,
  12143. curviness, curviness,
  12144. distance,
  12145. proximityLimit);
  12146. cp1x = _controlPoint[0];
  12147. cp2x = _controlPoint[0];
  12148. cp1y = _controlPoint[1];
  12149. cp2y = _controlPoint[1];
  12150. _super.setGeometry({
  12151. controlPoints:[_controlPoint, _controlPoint],
  12152. sourcePos:sp,
  12153. targetPos:tp,
  12154. quadrant:segment,
  12155. curviness:curviness
  12156. }, true);
  12157. }
  12158. _super.addSegment(this, "Bezier", {
  12159. x1: _tx, y1: _ty, x2: _sx, y2: _sy,
  12160. cp1x: cp1x, cp1y: cp1y,
  12161. cp2x: cp2x, cp2y: cp2y
  12162. });
  12163. };
  12164. };
  12165. _jp.Connectors.StateMachine = StateMachine;
  12166. _ju.extend(StateMachine, _jp.Connectors.AbstractBezierConnector);
  12167. }).call(typeof window !== 'undefined' ? window : this);
  12168. /*
  12169. * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
  12170. *
  12171. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  12172. *
  12173. * https://jsplumbtoolkit.com
  12174. * https://github.com/jsplumb/jsplumb
  12175. *
  12176. * Dual licensed under the MIT and GPL2 licenses.
  12177. */
  12178. ;
  12179. (function () {
  12180. "use strict";
  12181. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  12182. var STRAIGHT = "Straight";
  12183. var Straight = function (params) {
  12184. this.type = STRAIGHT;
  12185. var _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
  12186. this._compute = function (paintInfo, _) {
  12187. _super.addSegment(this, STRAIGHT, {x1: paintInfo.sx, y1: paintInfo.sy, x2: paintInfo.startStubX, y2: paintInfo.startStubY});
  12188. _super.addSegment(this, STRAIGHT, {x1: paintInfo.startStubX, y1: paintInfo.startStubY, x2: paintInfo.endStubX, y2: paintInfo.endStubY});
  12189. _super.addSegment(this, STRAIGHT, {x1: paintInfo.endStubX, y1: paintInfo.endStubY, x2: paintInfo.tx, y2: paintInfo.ty});
  12190. };
  12191. };
  12192. _jp.Connectors.Straight = Straight;
  12193. _ju.extend(Straight, _jp.Connectors.AbstractConnector);
  12194. }).call(typeof window !== 'undefined' ? window : this);
  12195. /*
  12196. * This file contains the SVG renderers.
  12197. *
  12198. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  12199. *
  12200. * https://jsplumbtoolkit.com
  12201. * https://github.com/jsplumb/jsplumb
  12202. *
  12203. * Dual licensed under the MIT and GPL2 licenses.
  12204. */
  12205. ;
  12206. (function () {
  12207. // ************************** SVG utility methods ********************************************
  12208. "use strict";
  12209. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  12210. var svgAttributeMap = {
  12211. "stroke-linejoin": "stroke-linejoin",
  12212. "stroke-dashoffset": "stroke-dashoffset",
  12213. "stroke-linecap": "stroke-linecap"
  12214. },
  12215. STROKE_DASHARRAY = "stroke-dasharray",
  12216. DASHSTYLE = "dashstyle",
  12217. LINEAR_GRADIENT = "linearGradient",
  12218. RADIAL_GRADIENT = "radialGradient",
  12219. DEFS = "defs",
  12220. FILL = "fill",
  12221. STOP = "stop",
  12222. STROKE = "stroke",
  12223. STROKE_WIDTH = "stroke-width",
  12224. STYLE = "style",
  12225. NONE = "none",
  12226. JSPLUMB_GRADIENT = "jsplumb_gradient_",
  12227. LINE_WIDTH = "strokeWidth",
  12228. ns = {
  12229. svg: "http://www.w3.org/2000/svg"
  12230. },
  12231. _attr = function (node, attributes) {
  12232. for (var i in attributes) {
  12233. node.setAttribute(i, "" + attributes[i]);
  12234. }
  12235. },
  12236. _node = function (name, attributes) {
  12237. attributes = attributes || {};
  12238. attributes.version = "1.1";
  12239. attributes.xmlns = ns.svg;
  12240. return _jp.createElementNS(ns.svg, name, null, null, attributes);
  12241. },
  12242. _pos = function (d) {
  12243. return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px";
  12244. },
  12245. _clearGradient = function (parent) {
  12246. var els = parent.querySelectorAll(" defs,linearGradient,radialGradient");
  12247. for (var i = 0; i < els.length; i++) {
  12248. els[i].parentNode.removeChild(els[i]);
  12249. }
  12250. },
  12251. _updateGradient = function (parent, node, style, dimensions, uiComponent) {
  12252. var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.instance.idstamp();
  12253. // first clear out any existing gradient
  12254. _clearGradient(parent);
  12255. // this checks for an 'offset' property in the gradient, and in the absence of it, assumes
  12256. // we want a linear gradient. if it's there, we create a radial gradient.
  12257. // it is possible that a more explicit means of defining the gradient type would be
  12258. // better. relying on 'offset' means that we can never have a radial gradient that uses
  12259. // some default offset, for instance.
  12260. // issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would
  12261. // not show gradients when the line was perfectly horizontal or vertical.
  12262. var g;
  12263. if (!style.gradient.offset) {
  12264. g = _node(LINEAR_GRADIENT, {id: id, gradientUnits: "userSpaceOnUse"});
  12265. }
  12266. else {
  12267. g = _node(RADIAL_GRADIENT, { id: id });
  12268. }
  12269. var defs = _node(DEFS);
  12270. parent.appendChild(defs);
  12271. defs.appendChild(g);
  12272. // the svg radial gradient seems to treat stops in the reverse
  12273. // order to how canvas does it. so we want to keep all the maths the same, but
  12274. // iterate the actual style declarations in reverse order, if the x indexes are not in order.
  12275. for (var i = 0; i < style.gradient.stops.length; i++) {
  12276. var styleToUse = uiComponent.segment === 1 || uiComponent.segment === 2 ? i : style.gradient.stops.length - 1 - i,
  12277. stopColor = style.gradient.stops[styleToUse][1],
  12278. s = _node(STOP, {"offset": Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color": stopColor});
  12279. g.appendChild(s);
  12280. }
  12281. var applyGradientTo = style.stroke ? STROKE : FILL;
  12282. node.setAttribute(applyGradientTo, "url(#" + id + ")");
  12283. },
  12284. _applyStyles = function (parent, node, style, dimensions, uiComponent) {
  12285. node.setAttribute(FILL, style.fill ? style.fill : NONE);
  12286. node.setAttribute(STROKE, style.stroke ? style.stroke : NONE);
  12287. if (style.gradient) {
  12288. _updateGradient(parent, node, style, dimensions, uiComponent);
  12289. }
  12290. else {
  12291. // make sure we clear any existing gradient
  12292. _clearGradient(parent);
  12293. node.setAttribute(STYLE, "");
  12294. }
  12295. if (style.strokeWidth) {
  12296. node.setAttribute(STROKE_WIDTH, style.strokeWidth);
  12297. }
  12298. // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
  12299. // the syntax in VML but is actually kind of nasty: values are given in the pixel
  12300. // coordinate space, whereas in VML they are multiples of the width of the stroked
  12301. // line, which makes a lot more sense. for that reason, jsPlumb is supporting both
  12302. // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
  12303. // VML, which will be the preferred method. the code below this converts a dashstyle
  12304. // attribute given in terms of stroke width into a pixel representation, by using the
  12305. // stroke's lineWidth.
  12306. if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) {
  12307. var sep = style[DASHSTYLE].indexOf(",") === -1 ? " " : ",",
  12308. parts = style[DASHSTYLE].split(sep),
  12309. styleToUse = "";
  12310. parts.forEach(function (p) {
  12311. styleToUse += (Math.floor(p * style.strokeWidth) + sep);
  12312. });
  12313. node.setAttribute(STROKE_DASHARRAY, styleToUse);
  12314. }
  12315. else if (style[STROKE_DASHARRAY]) {
  12316. node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]);
  12317. }
  12318. // extra attributes such as join type, dash offset.
  12319. for (var i in svgAttributeMap) {
  12320. if (style[i]) {
  12321. node.setAttribute(svgAttributeMap[i], style[i]);
  12322. }
  12323. }
  12324. },
  12325. _appendAtIndex = function (svg, path, idx) {
  12326. if (svg.childNodes.length > idx) {
  12327. svg.insertBefore(path, svg.childNodes[idx]);
  12328. }
  12329. else {
  12330. svg.appendChild(path);
  12331. }
  12332. };
  12333. /**
  12334. utility methods for other objects to use.
  12335. */
  12336. _ju.svg = {
  12337. node: _node,
  12338. attr: _attr,
  12339. pos: _pos
  12340. };
  12341. // ************************** / SVG utility methods ********************************************
  12342. /*
  12343. * Base class for SVG components.
  12344. */
  12345. var SvgComponent = function (params) {
  12346. var pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {};
  12347. _jp.jsPlumbUIComponent.apply(this, params.originalArgs);
  12348. this.canvas = null;
  12349. this.path = null;
  12350. this.svg = null;
  12351. this.bgCanvas = null;
  12352. var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""),
  12353. svgParams = {
  12354. "style": "",
  12355. "width": 0,
  12356. "height": 0,
  12357. "pointer-events": pointerEventsSpec,
  12358. "position": "absolute"
  12359. };
  12360. this.svg = _node("svg", svgParams);
  12361. if (params.useDivWrapper) {
  12362. this.canvas = _jp.createElement("div", { position : "absolute" });
  12363. _ju.sizeElement(this.canvas, 0, 0, 1, 1);
  12364. this.canvas.className = clazz;
  12365. }
  12366. else {
  12367. _attr(this.svg, { "class": clazz });
  12368. this.canvas = this.svg;
  12369. }
  12370. params._jsPlumb.appendElement(this.canvas, params.originalArgs[0].parent);
  12371. if (params.useDivWrapper) {
  12372. this.canvas.appendChild(this.svg);
  12373. }
  12374. var displayElements = [ this.canvas ];
  12375. this.getDisplayElements = function () {
  12376. return displayElements;
  12377. };
  12378. this.appendDisplayElement = function (el) {
  12379. displayElements.push(el);
  12380. };
  12381. this.paint = function (style, anchor, extents) {
  12382. if (style != null) {
  12383. var xy = [ this.x, this.y ], wh = [ this.w, this.h ], p;
  12384. if (extents != null) {
  12385. if (extents.xmin < 0) {
  12386. xy[0] += extents.xmin;
  12387. }
  12388. if (extents.ymin < 0) {
  12389. xy[1] += extents.ymin;
  12390. }
  12391. wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0);
  12392. wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0);
  12393. }
  12394. if (params.useDivWrapper) {
  12395. _ju.sizeElement(this.canvas, xy[0], xy[1], wh[0], wh[1]);
  12396. xy[0] = 0;
  12397. xy[1] = 0;
  12398. p = _pos([ 0, 0 ]);
  12399. }
  12400. else {
  12401. p = _pos([ xy[0], xy[1] ]);
  12402. }
  12403. renderer.paint.apply(this, arguments);
  12404. _attr(this.svg, {
  12405. "style": p,
  12406. "width": wh[0] || 0,
  12407. "height": wh[1] || 0
  12408. });
  12409. }
  12410. };
  12411. return {
  12412. renderer: renderer
  12413. };
  12414. };
  12415. _ju.extend(SvgComponent, _jp.jsPlumbUIComponent, {
  12416. cleanup: function (force) {
  12417. if (force || this.typeId == null) {
  12418. if (this.canvas) {
  12419. this.canvas._jsPlumb = null;
  12420. }
  12421. if (this.svg) {
  12422. this.svg._jsPlumb = null;
  12423. }
  12424. if (this.bgCanvas) {
  12425. this.bgCanvas._jsPlumb = null;
  12426. }
  12427. if (this.canvas && this.canvas.parentNode) {
  12428. this.canvas.parentNode.removeChild(this.canvas);
  12429. }
  12430. if (this.bgCanvas && this.bgCanvas.parentNode) {
  12431. this.canvas.parentNode.removeChild(this.canvas);
  12432. }
  12433. this.svg = null;
  12434. this.canvas = null;
  12435. this.path = null;
  12436. this.group = null;
  12437. }
  12438. else {
  12439. // if not a forced cleanup, just detach from DOM for now.
  12440. if (this.canvas && this.canvas.parentNode) {
  12441. this.canvas.parentNode.removeChild(this.canvas);
  12442. }
  12443. if (this.bgCanvas && this.bgCanvas.parentNode) {
  12444. this.bgCanvas.parentNode.removeChild(this.bgCanvas);
  12445. }
  12446. }
  12447. },
  12448. reattach:function(instance) {
  12449. var c = instance.getContainer();
  12450. if (this.canvas && this.canvas.parentNode == null) {
  12451. c.appendChild(this.canvas);
  12452. }
  12453. if (this.bgCanvas && this.bgCanvas.parentNode == null) {
  12454. c.appendChild(this.bgCanvas);
  12455. }
  12456. },
  12457. setVisible: function (v) {
  12458. if (this.canvas) {
  12459. this.canvas.style.display = v ? "block" : "none";
  12460. }
  12461. }
  12462. });
  12463. /*
  12464. * Base class for SVG connectors.
  12465. */
  12466. _jp.ConnectorRenderers.svg = function (params) {
  12467. var self = this,
  12468. _super = SvgComponent.apply(this, [
  12469. {
  12470. cssClass: params._jsPlumb.connectorClass + (this.isEditable() ? " " + params._jsPlumb.editableConnectorClass : ""),
  12471. originalArgs: arguments,
  12472. pointerEventsSpec: "none",
  12473. _jsPlumb: params._jsPlumb
  12474. }
  12475. ]);
  12476. var _superSetEditable = this.setEditable;
  12477. this.setEditable = function(e) {
  12478. var result = _superSetEditable.apply(this, [e]);
  12479. _jp[result ? "addClass" : "removeClass"](this.canvas, this._jsPlumb.instance.editableConnectorClass);
  12480. };
  12481. _super.renderer.paint = function (style, anchor, extents) {
  12482. var segments = self.getSegments(), p = "", offset = [0, 0];
  12483. if (extents.xmin < 0) {
  12484. offset[0] = -extents.xmin;
  12485. }
  12486. if (extents.ymin < 0) {
  12487. offset[1] = -extents.ymin;
  12488. }
  12489. if (segments.length > 0) {
  12490. p = self.getPathData();
  12491. var a = {
  12492. d: p,
  12493. transform: "translate(" + offset[0] + "," + offset[1] + ")",
  12494. "pointer-events": params["pointer-events"] || "visibleStroke"
  12495. },
  12496. outlineStyle = null,
  12497. d = [self.x, self.y, self.w, self.h];
  12498. // outline style. actually means drawing an svg object underneath the main one.
  12499. if (style.outlineStroke) {
  12500. var outlineWidth = style.outlineWidth || 1,
  12501. outlineStrokeWidth = style.strokeWidth + (2 * outlineWidth);
  12502. outlineStyle = _jp.extend({}, style);
  12503. delete outlineStyle.gradient;
  12504. outlineStyle.stroke = style.outlineStroke;
  12505. outlineStyle.strokeWidth = outlineStrokeWidth;
  12506. if (self.bgPath == null) {
  12507. self.bgPath = _node("path", a);
  12508. _jp.addClass(self.bgPath, _jp.connectorOutlineClass);
  12509. _appendAtIndex(self.svg, self.bgPath, 0);
  12510. }
  12511. else {
  12512. _attr(self.bgPath, a);
  12513. }
  12514. _applyStyles(self.svg, self.bgPath, outlineStyle, d, self);
  12515. }
  12516. if (self.path == null) {
  12517. self.path = _node("path", a);
  12518. _appendAtIndex(self.svg, self.path, style.outlineStroke ? 1 : 0);
  12519. }
  12520. else {
  12521. _attr(self.path, a);
  12522. }
  12523. _applyStyles(self.svg, self.path, style, d, self);
  12524. }
  12525. };
  12526. };
  12527. _ju.extend(_jp.ConnectorRenderers.svg, SvgComponent);
  12528. // ******************************* svg segment renderer *****************************************************
  12529. // ******************************* /svg segments *****************************************************
  12530. /*
  12531. * Base class for SVG endpoints.
  12532. */
  12533. var SvgEndpoint = _jp.SvgEndpoint = function (params) {
  12534. var _super = SvgComponent.apply(this, [
  12535. {
  12536. cssClass: params._jsPlumb.endpointClass,
  12537. originalArgs: arguments,
  12538. pointerEventsSpec: "all",
  12539. useDivWrapper: true,
  12540. _jsPlumb: params._jsPlumb
  12541. }
  12542. ]);
  12543. _super.renderer.paint = function (style) {
  12544. var s = _jp.extend({}, style);
  12545. if (s.outlineStroke) {
  12546. s.stroke = s.outlineStroke;
  12547. }
  12548. if (this.node == null) {
  12549. this.node = this.makeNode(s);
  12550. this.svg.appendChild(this.node);
  12551. }
  12552. else if (this.updateNode != null) {
  12553. this.updateNode(this.node);
  12554. }
  12555. _applyStyles(this.svg, this.node, s, [ this.x, this.y, this.w, this.h ], this);
  12556. _pos(this.node, [ this.x, this.y ]);
  12557. }.bind(this);
  12558. };
  12559. _ju.extend(SvgEndpoint, SvgComponent);
  12560. /*
  12561. * SVG Dot Endpoint
  12562. */
  12563. _jp.Endpoints.svg.Dot = function () {
  12564. _jp.Endpoints.Dot.apply(this, arguments);
  12565. SvgEndpoint.apply(this, arguments);
  12566. this.makeNode = function (style) {
  12567. return _node("circle", {
  12568. "cx": this.w / 2,
  12569. "cy": this.h / 2,
  12570. "r": this.radius
  12571. });
  12572. };
  12573. this.updateNode = function (node) {
  12574. _attr(node, {
  12575. "cx": this.w / 2,
  12576. "cy": this.h / 2,
  12577. "r": this.radius
  12578. });
  12579. };
  12580. };
  12581. _ju.extend(_jp.Endpoints.svg.Dot, [_jp.Endpoints.Dot, SvgEndpoint]);
  12582. /*
  12583. * SVG Rectangle Endpoint
  12584. */
  12585. _jp.Endpoints.svg.Rectangle = function () {
  12586. _jp.Endpoints.Rectangle.apply(this, arguments);
  12587. SvgEndpoint.apply(this, arguments);
  12588. this.makeNode = function (style) {
  12589. return _node("rect", {
  12590. "width": this.w,
  12591. "height": this.h
  12592. });
  12593. };
  12594. this.updateNode = function (node) {
  12595. _attr(node, {
  12596. "width": this.w,
  12597. "height": this.h
  12598. });
  12599. };
  12600. };
  12601. _ju.extend(_jp.Endpoints.svg.Rectangle, [_jp.Endpoints.Rectangle, SvgEndpoint]);
  12602. // ---------------------------------- Connectors ------------------------------------------------------------
  12603. _jp.Connectors.svg.Flowchart = function() {
  12604. _jp.Connectors.Flowchart.apply(this, arguments);
  12605. _jp.ConnectorRenderers.svg.apply(this, arguments);
  12606. };
  12607. _ju.extend(_jp.Connectors.svg.Flowchart, [ _jp.Connectors.Flowchart, _jp.ConnectorRenderers.svg]);
  12608. _jp.Connectors.svg.Bezier = function() {
  12609. _jp.Connectors.Bezier.apply(this, arguments);
  12610. _jp.ConnectorRenderers.svg.apply(this, arguments);
  12611. };
  12612. _ju.extend(_jp.Connectors.svg.Bezier, [ _jp.Connectors.Bezier, _jp.ConnectorRenderers.svg]);
  12613. _jp.Connectors.svg.Straight = function() {
  12614. _jp.Connectors.Straight.apply(this, arguments);
  12615. _jp.ConnectorRenderers.svg.apply(this, arguments);
  12616. };
  12617. _ju.extend(_jp.Connectors.svg.Straight, [ _jp.Connectors.Straight, _jp.ConnectorRenderers.svg]);
  12618. _jp.Connectors.svg.StateMachine = function() {
  12619. _jp.Connectors.StateMachine.apply(this, arguments);
  12620. _jp.ConnectorRenderers.svg.apply(this, arguments);
  12621. };
  12622. _ju.extend(_jp.Connectors.svg.StateMachine, [ _jp.Connectors.StateMachine, _jp.ConnectorRenderers.svg]);
  12623. // ------------------------------------------ / Connectors -----------------------------------------
  12624. /*
  12625. * SVG Image Endpoint is the default image endpoint.
  12626. */
  12627. _jp.Endpoints.svg.Image = _jp.Endpoints.Image;
  12628. /*
  12629. * Blank endpoint in svg renderer is the default Blank endpoint.
  12630. */
  12631. _jp.Endpoints.svg.Blank = _jp.Endpoints.Blank;
  12632. /*
  12633. * Label overlay in svg renderer is the default Label overlay.
  12634. */
  12635. _jp.Overlays.svg.Label = _jp.Overlays.Label;
  12636. /*
  12637. * Custom overlay in svg renderer is the default Custom overlay.
  12638. */
  12639. _jp.Overlays.svg.Custom = _jp.Overlays.Custom;
  12640. var AbstractSvgArrowOverlay = function (superclass, originalArgs) {
  12641. superclass.apply(this, originalArgs);
  12642. _jp.jsPlumbUIComponent.apply(this, originalArgs);
  12643. this.isAppendedAtTopLevel = false;
  12644. var self = this;
  12645. this.path = null;
  12646. this.paint = function (params, containerExtents) {
  12647. // only draws on connections, not endpoints.
  12648. if (params.component.svg && containerExtents) {
  12649. if (this.path == null) {
  12650. this.path = _node("path", {
  12651. "pointer-events": "all"
  12652. });
  12653. params.component.svg.appendChild(this.path);
  12654. if (this.elementCreated) {
  12655. this.elementCreated(this.path, params.component);
  12656. }
  12657. this.canvas = params.component.svg; // for the sake of completeness; this behaves the same as other overlays
  12658. }
  12659. var clazz = originalArgs && (originalArgs.length === 1) ? (originalArgs[0].cssClass || "") : "",
  12660. offset = [0, 0];
  12661. if (containerExtents.xmin < 0) {
  12662. offset[0] = -containerExtents.xmin;
  12663. }
  12664. if (containerExtents.ymin < 0) {
  12665. offset[1] = -containerExtents.ymin;
  12666. }
  12667. _attr(this.path, {
  12668. "d": makePath(params.d),
  12669. "class": clazz,
  12670. stroke: params.stroke ? params.stroke : null,
  12671. fill: params.fill ? params.fill : null,
  12672. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12673. });
  12674. }
  12675. };
  12676. var makePath = function (d) {
  12677. return (isNaN(d.cxy.x) || isNaN(d.cxy.y)) ? "" : "M" + d.hxy.x + "," + d.hxy.y +
  12678. " L" + d.tail[0].x + "," + d.tail[0].y +
  12679. " L" + d.cxy.x + "," + d.cxy.y +
  12680. " L" + d.tail[1].x + "," + d.tail[1].y +
  12681. " L" + d.hxy.x + "," + d.hxy.y;
  12682. };
  12683. this.transfer = function(target) {
  12684. if (target.canvas && this.path && this.path.parentNode) {
  12685. this.path.parentNode.removeChild(this.path);
  12686. target.canvas.appendChild(this.path);
  12687. }
  12688. };
  12689. };
  12690. _ju.extend(AbstractSvgArrowOverlay, [_jp.jsPlumbUIComponent, _jp.Overlays.AbstractOverlay], {
  12691. cleanup: function (force) {
  12692. if (this.path != null) {
  12693. if (force) {
  12694. this._jsPlumb.instance.removeElement(this.path);
  12695. }
  12696. else {
  12697. if (this.path.parentNode) {
  12698. this.path.parentNode.removeChild(this.path);
  12699. }
  12700. }
  12701. }
  12702. },
  12703. reattach:function(instance, component) {
  12704. if (this.path && component.canvas) {
  12705. component.canvas.appendChild(this.path);
  12706. }
  12707. },
  12708. setVisible: function (v) {
  12709. if (this.path != null) {
  12710. (this.path.style.display = (v ? "block" : "none"));
  12711. }
  12712. }
  12713. });
  12714. _jp.Overlays.svg.Arrow = function () {
  12715. AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Arrow, arguments]);
  12716. };
  12717. _ju.extend(_jp.Overlays.svg.Arrow, [ _jp.Overlays.Arrow, AbstractSvgArrowOverlay ]);
  12718. _jp.Overlays.svg.PlainArrow = function () {
  12719. AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.PlainArrow, arguments]);
  12720. };
  12721. _ju.extend(_jp.Overlays.svg.PlainArrow, [ _jp.Overlays.PlainArrow, AbstractSvgArrowOverlay ]);
  12722. _jp.Overlays.svg.Diamond = function () {
  12723. AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Diamond, arguments]);
  12724. };
  12725. _ju.extend(_jp.Overlays.svg.Diamond, [ _jp.Overlays.Diamond, AbstractSvgArrowOverlay ]);
  12726. // a test
  12727. _jp.Overlays.svg.GuideLines = function () {
  12728. var path = null, self = this, p1_1, p1_2;
  12729. _jp.Overlays.GuideLines.apply(this, arguments);
  12730. this.paint = function (params, containerExtents) {
  12731. if (path == null) {
  12732. path = _node("path");
  12733. params.connector.svg.appendChild(path);
  12734. self.attachListeners(path, params.connector);
  12735. self.attachListeners(path, self);
  12736. p1_1 = _node("path");
  12737. params.connector.svg.appendChild(p1_1);
  12738. self.attachListeners(p1_1, params.connector);
  12739. self.attachListeners(p1_1, self);
  12740. p1_2 = _node("path");
  12741. params.connector.svg.appendChild(p1_2);
  12742. self.attachListeners(p1_2, params.connector);
  12743. self.attachListeners(p1_2, self);
  12744. }
  12745. var offset = [0, 0];
  12746. if (containerExtents.xmin < 0) {
  12747. offset[0] = -containerExtents.xmin;
  12748. }
  12749. if (containerExtents.ymin < 0) {
  12750. offset[1] = -containerExtents.ymin;
  12751. }
  12752. _attr(path, {
  12753. "d": makePath(params.head, params.tail),
  12754. stroke: "red",
  12755. fill: null,
  12756. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12757. });
  12758. _attr(p1_1, {
  12759. "d": makePath(params.tailLine[0], params.tailLine[1]),
  12760. stroke: "blue",
  12761. fill: null,
  12762. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12763. });
  12764. _attr(p1_2, {
  12765. "d": makePath(params.headLine[0], params.headLine[1]),
  12766. stroke: "green",
  12767. fill: null,
  12768. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12769. });
  12770. };
  12771. var makePath = function (d1, d2) {
  12772. return "M " + d1.x + "," + d1.y +
  12773. " L" + d2.x + "," + d2.y;
  12774. };
  12775. };
  12776. _ju.extend(_jp.Overlays.svg.GuideLines, _jp.Overlays.GuideLines);
  12777. }).call(typeof window !== 'undefined' ? window : this);
  12778. /*
  12779. * This file contains the 'vanilla' adapter - having no external dependencies other than bundled libs.
  12780. *
  12781. * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
  12782. *
  12783. * https://jsplumbtoolkit.com
  12784. * https://github.com/jsplumb/jsplumb
  12785. *
  12786. * Dual licensed under the MIT and GPL2 licenses.
  12787. */
  12788. ;
  12789. (function () {
  12790. "use strict";
  12791. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil,
  12792. _jk = root.Katavorio, _jg = root.Biltong;
  12793. var _getDragManager = function (instance, category) {
  12794. category = category || "main";
  12795. var key = "_katavorio_" + category;
  12796. var k = instance[key],
  12797. e = instance.getEventManager();
  12798. if (!k) {
  12799. k = new _jk({
  12800. bind: e.on,
  12801. unbind: e.off,
  12802. getSize: _jp.getSize,
  12803. getConstrainingRectangle:function(el) {
  12804. return [ el.parentNode.scrollWidth, el.parentNode.scrollHeight ];
  12805. },
  12806. getPosition: function (el, relativeToRoot) {
  12807. // if this is a nested draggable then compute the offset against its own offsetParent, otherwise
  12808. // compute against the Container's origin. see also the getUIPosition method below.
  12809. var o = instance.getOffset(el, relativeToRoot, el._katavorioDrag ? el.offsetParent : null);
  12810. return [o.left, o.top];
  12811. },
  12812. setPosition: function (el, xy) {
  12813. el.style.left = xy[0] + "px";
  12814. el.style.top = xy[1] + "px";
  12815. },
  12816. addClass: _jp.addClass,
  12817. removeClass: _jp.removeClass,
  12818. intersects: _jg.intersects,
  12819. indexOf: function(l, i) { return l.indexOf(i); },
  12820. scope:instance.getDefaultScope(),
  12821. css: {
  12822. noSelect: instance.dragSelectClass,
  12823. droppable: "jtk-droppable",
  12824. draggable: "jtk-draggable",
  12825. drag: "jtk-drag",
  12826. selected: "jtk-drag-selected",
  12827. active: "jtk-drag-active",
  12828. hover: "jtk-drag-hover",
  12829. ghostProxy:"jtk-ghost-proxy"
  12830. }
  12831. });
  12832. k.setZoom(instance.getZoom());
  12833. instance[key] = k;
  12834. instance.bind("zoom", k.setZoom);
  12835. }
  12836. return k;
  12837. };
  12838. var _animProps = function (o, p) {
  12839. var _one = function (pName) {
  12840. if (p[pName] != null) {
  12841. if (_ju.isString(p[pName])) {
  12842. var m = p[pName].match(/-=/) ? -1 : 1,
  12843. v = p[pName].substring(2);
  12844. return o[pName] + (m * v);
  12845. }
  12846. else {
  12847. return p[pName];
  12848. }
  12849. }
  12850. else {
  12851. return o[pName];
  12852. }
  12853. };
  12854. return [ _one("left"), _one("top") ];
  12855. };
  12856. _jp.extend(root.jsPlumbInstance.prototype, {
  12857. animationSupported:true,
  12858. getElement: function (el) {
  12859. if (el == null) {
  12860. return null;
  12861. }
  12862. // here we pluck the first entry if el was a list of entries.
  12863. // this is not my favourite thing to do, but previous versions of
  12864. // jsplumb supported jquery selectors, and it is possible a selector
  12865. // will be passed in here.
  12866. el = typeof el === "string" ? el : el.length != null && el.enctype == null ? el[0] : el;
  12867. return typeof el === "string" ? document.getElementById(el) : el;
  12868. },
  12869. removeElement: function (element) {
  12870. _getDragManager(this).elementRemoved(element);
  12871. this.getEventManager().remove(element);
  12872. },
  12873. //
  12874. // this adapter supports a rudimentary animation function. no easing is supported. only
  12875. // left/top properties are supported. property delta args are expected to be in the form
  12876. //
  12877. // +=x.xxxx
  12878. //
  12879. // or
  12880. //
  12881. // -=x.xxxx
  12882. //
  12883. doAnimate: function (el, properties, options) {
  12884. options = options || {};
  12885. var o = this.getOffset(el),
  12886. ap = _animProps(o, properties),
  12887. ldist = ap[0] - o.left,
  12888. tdist = ap[1] - o.top,
  12889. d = options.duration || 250,
  12890. step = 15, steps = d / step,
  12891. linc = (step / d) * ldist,
  12892. tinc = (step / d) * tdist,
  12893. idx = 0,
  12894. _int = setInterval(function () {
  12895. _jp.setPosition(el, {
  12896. left: o.left + (linc * (idx + 1)),
  12897. top: o.top + (tinc * (idx + 1))
  12898. });
  12899. if (options.step != null) {
  12900. options.step(idx, Math.ceil(steps));
  12901. }
  12902. idx++;
  12903. if (idx >= steps) {
  12904. window.clearInterval(_int);
  12905. if (options.complete != null) {
  12906. options.complete();
  12907. }
  12908. }
  12909. }, step);
  12910. },
  12911. // DRAG/DROP
  12912. destroyDraggable: function (el, category) {
  12913. _getDragManager(this, category).destroyDraggable(el);
  12914. },
  12915. destroyDroppable: function (el, category) {
  12916. _getDragManager(this, category).destroyDroppable(el);
  12917. },
  12918. initDraggable: function (el, options, category) {
  12919. _getDragManager(this, category).draggable(el, options);
  12920. },
  12921. initDroppable: function (el, options, category) {
  12922. _getDragManager(this, category).droppable(el, options);
  12923. },
  12924. isAlreadyDraggable: function (el) {
  12925. return el._katavorioDrag != null;
  12926. },
  12927. isDragSupported: function (el, options) {
  12928. return true;
  12929. },
  12930. isDropSupported: function (el, options) {
  12931. return true;
  12932. },
  12933. isElementDraggable: function (el) {
  12934. el = _jp.getElement(el);
  12935. return el._katavorioDrag && el._katavorioDrag.isEnabled();
  12936. },
  12937. getDragObject: function (eventArgs) {
  12938. return eventArgs[0].drag.getDragElement();
  12939. },
  12940. getDragScope: function (el) {
  12941. return el._katavorioDrag && el._katavorioDrag.scopes.join(" ") || "";
  12942. },
  12943. getDropEvent: function (args) {
  12944. return args[0].e;
  12945. },
  12946. getUIPosition: function (eventArgs, zoom) {
  12947. // here the position reported to us by Katavorio is relative to the element's offsetParent. For top
  12948. // level nodes that is fine, but if we have a nested draggable then its offsetParent is actually
  12949. // not going to be the jsplumb container; it's going to be some child of that element. In that case
  12950. // we want to adjust the UI position to account for the offsetParent's position relative to the Container
  12951. // origin.
  12952. var el = eventArgs[0].el;
  12953. if (el.offsetParent == null) {
  12954. return null;
  12955. }
  12956. var finalPos = eventArgs[0].finalPos || eventArgs[0].pos;
  12957. var p = { left:finalPos[0], top:finalPos[1] };
  12958. if (el._katavorioDrag && el.offsetParent !== this.getContainer()) {
  12959. var oc = this.getOffset(el.offsetParent);
  12960. p.left += oc.left;
  12961. p.top += oc.top;
  12962. }
  12963. return p;
  12964. },
  12965. setDragFilter: function (el, filter, _exclude) {
  12966. if (el._katavorioDrag) {
  12967. el._katavorioDrag.setFilter(filter, _exclude);
  12968. }
  12969. },
  12970. setElementDraggable: function (el, draggable) {
  12971. el = _jp.getElement(el);
  12972. if (el._katavorioDrag) {
  12973. el._katavorioDrag.setEnabled(draggable);
  12974. }
  12975. },
  12976. setDragScope: function (el, scope) {
  12977. if (el._katavorioDrag) {
  12978. el._katavorioDrag.k.setDragScope(el, scope);
  12979. }
  12980. },
  12981. setDropScope:function(el, scope) {
  12982. if (el._katavorioDrop && el._katavorioDrop.length > 0) {
  12983. el._katavorioDrop[0].k.setDropScope(el, scope);
  12984. }
  12985. },
  12986. addToPosse:function(el, spec) {
  12987. var specs = Array.prototype.slice.call(arguments, 1);
  12988. var dm = _getDragManager(this);
  12989. _jp.each(el, function(_el) {
  12990. _el = [ _jp.getElement(_el) ];
  12991. _el.push.apply(_el, specs );
  12992. dm.addToPosse.apply(dm, _el);
  12993. });
  12994. },
  12995. setPosse:function(el, spec) {
  12996. var specs = Array.prototype.slice.call(arguments, 1);
  12997. var dm = _getDragManager(this);
  12998. _jp.each(el, function(_el) {
  12999. _el = [ _jp.getElement(_el) ];
  13000. _el.push.apply(_el, specs );
  13001. dm.setPosse.apply(dm, _el);
  13002. });
  13003. },
  13004. removeFromPosse:function(el, posseId) {
  13005. var specs = Array.prototype.slice.call(arguments, 1);
  13006. var dm = _getDragManager(this);
  13007. _jp.each(el, function(_el) {
  13008. _el = [ _jp.getElement(_el) ];
  13009. _el.push.apply(_el, specs );
  13010. dm.removeFromPosse.apply(dm, _el);
  13011. });
  13012. },
  13013. removeFromAllPosses:function(el) {
  13014. var dm = _getDragManager(this);
  13015. _jp.each(el, function(_el) { dm.removeFromAllPosses(_jp.getElement(_el)); });
  13016. },
  13017. setPosseState:function(el, posseId, state) {
  13018. var dm = _getDragManager(this);
  13019. _jp.each(el, function(_el) { dm.setPosseState(_jp.getElement(_el), posseId, state); });
  13020. },
  13021. dragEvents: {
  13022. 'start': 'start', 'stop': 'stop', 'drag': 'drag', 'step': 'step',
  13023. 'over': 'over', 'out': 'out', 'drop': 'drop', 'complete': 'complete',
  13024. 'beforeStart':'beforeStart'
  13025. },
  13026. animEvents: {
  13027. 'step': "step", 'complete': 'complete'
  13028. },
  13029. stopDrag: function (el) {
  13030. if (el._katavorioDrag) {
  13031. el._katavorioDrag.abort();
  13032. }
  13033. },
  13034. addToDragSelection: function (spec) {
  13035. _getDragManager(this).select(spec);
  13036. },
  13037. removeFromDragSelection: function (spec) {
  13038. _getDragManager(this).deselect(spec);
  13039. },
  13040. clearDragSelection: function () {
  13041. _getDragManager(this).deselectAll();
  13042. },
  13043. trigger: function (el, event, originalEvent, payload) {
  13044. this.getEventManager().trigger(el, event, originalEvent, payload);
  13045. },
  13046. doReset:function() {
  13047. // look for katavorio instances and reset each one if found.
  13048. for (var key in this) {
  13049. if (key.indexOf("_katavorio_") === 0) {
  13050. this[key].reset();
  13051. }
  13052. }
  13053. }
  13054. });
  13055. var ready = function (f) {
  13056. var _do = function () {
  13057. if (/complete|loaded|interactive/.test(document.readyState) && typeof(document.body) !== "undefined" && document.body != null) {
  13058. f();
  13059. }
  13060. else {
  13061. setTimeout(_do, 9);
  13062. }
  13063. };
  13064. _do();
  13065. };
  13066. ready(_jp.init);
  13067. }).call(typeof window !== 'undefined' ? window : this);