jsplumb2.js 593 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921
  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 = 50,
  1263. DEFAULT_GRID_Y = 50,
  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. },
  1294. _defaultScope = "katavorio-drag-scope",
  1295. _events = [ "stop", "start", "drag", "drop", "over", "out", "beforeStart" ],
  1296. _devNull = function() {},
  1297. _true = function() { return true; },
  1298. _foreach = function(l, fn, from) {
  1299. for (var i = 0; i < l.length; i++) {
  1300. if (l[i] != from)
  1301. fn(l[i]);
  1302. }
  1303. },
  1304. _setDroppablesActive = function(dd, val, andHover, drag) {
  1305. _foreach(dd, function(e) {
  1306. e.setActive(val);
  1307. if (val) e.updatePosition();
  1308. if (andHover) e.setHover(drag, val);
  1309. });
  1310. },
  1311. _each = function(obj, fn) {
  1312. if (obj == null) return;
  1313. obj = !_isString(obj) && (obj.tagName == null && obj.length != null) ? obj : [ obj ];
  1314. for (var i = 0; i < obj.length; i++)
  1315. fn.apply(obj[i], [ obj[i] ]);
  1316. },
  1317. _consume = function(e) {
  1318. if (e.stopPropagation) {
  1319. e.stopPropagation();
  1320. e.preventDefault();
  1321. }
  1322. else {
  1323. e.returnValue = false;
  1324. }
  1325. },
  1326. _defaultInputFilterSelector = "input,textarea,select,button,option",
  1327. //
  1328. // filters out events on all input elements, like textarea, checkbox, input, select.
  1329. _inputFilter = function(e, el, _katavorio) {
  1330. var t = e.srcElement || e.target;
  1331. return !matchesSelector(t, _katavorio.getInputFilterSelector(), el);
  1332. };
  1333. var Super = function(el, params, css, scope) {
  1334. this.params = params || {};
  1335. this.el = el;
  1336. this.params.addClass(this.el, this._class);
  1337. this.uuid = _uuid();
  1338. var enabled = true;
  1339. this.setEnabled = function(e) { enabled = e; };
  1340. this.isEnabled = function() { return enabled; };
  1341. this.toggleEnabled = function() { enabled = !enabled; };
  1342. this.setScope = function(scopes) {
  1343. this.scopes = scopes ? scopes.split(/\s+/) : [ scope ];
  1344. };
  1345. this.addScope = function(scopes) {
  1346. var m = {};
  1347. _each(this.scopes, function(s) { m[s] = true;});
  1348. _each(scopes ? scopes.split(/\s+/) : [], function(s) { m[s] = true;});
  1349. this.scopes = [];
  1350. for (var i in m) this.scopes.push(i);
  1351. };
  1352. this.removeScope = function(scopes) {
  1353. var m = {};
  1354. _each(this.scopes, function(s) { m[s] = true;});
  1355. _each(scopes ? scopes.split(/\s+/) : [], function(s) { delete m[s];});
  1356. this.scopes = [];
  1357. for (var i in m) this.scopes.push(i);
  1358. };
  1359. this.toggleScope = function(scopes) {
  1360. var m = {};
  1361. _each(this.scopes, function(s) { m[s] = true;});
  1362. _each(scopes ? scopes.split(/\s+/) : [], function(s) {
  1363. if (m[s]) delete m[s];
  1364. else m[s] = true;
  1365. });
  1366. this.scopes = [];
  1367. for (var i in m) this.scopes.push(i);
  1368. };
  1369. this.setScope(params.scope);
  1370. this.k = params.katavorio;
  1371. return params.katavorio;
  1372. };
  1373. var TRUE = function() { return true; };
  1374. var FALSE = function() { return false; };
  1375. var Drag = function(el, params, css, scope) {
  1376. this._class = css.draggable;
  1377. var k = Super.apply(this, arguments);
  1378. this.rightButtonCanDrag = this.params.rightButtonCanDrag;
  1379. var downAt = [0,0], posAtDown = null, pagePosAtDown = null, pageDelta = [0,0], moving = false,
  1380. consumeStartEvent = this.params.consumeStartEvent !== false,
  1381. dragEl = this.el,
  1382. clone = this.params.clone,
  1383. scroll = this.params.scroll,
  1384. _multipleDrop = params.multipleDrop !== false,
  1385. isConstrained = false,
  1386. useGhostProxy = params.ghostProxy === true ? TRUE : params.ghostProxy && typeof params.ghostProxy === "function" ? params.ghostProxy : FALSE,
  1387. ghostProxy = function(el) { return el.cloneNode(true); };
  1388. var snapThreshold = params.snapThreshold || 5,
  1389. _snap = function(pos, x, y, thresholdX, thresholdY) {
  1390. thresholdX = thresholdX || snapThreshold;
  1391. thresholdY = thresholdY || snapThreshold;
  1392. var _dx = Math.floor(pos[0] / x),
  1393. _dxl = x * _dx,
  1394. _dxt = _dxl + x,
  1395. _x = Math.abs(pos[0] - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos[0]) <= thresholdX ? _dxt : pos[0];
  1396. var _dy = Math.floor(pos[1] / y),
  1397. _dyl = y * _dy,
  1398. _dyt = _dyl + y,
  1399. _y = Math.abs(pos[1] - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos[1]) <= thresholdY ? _dyt : pos[1];
  1400. return [ _x, _y];
  1401. };
  1402. this.posses = [];
  1403. this.posseRoles = {};
  1404. this.toGrid = function(pos) {
  1405. if (this.params.grid == null) {
  1406. return pos;
  1407. }
  1408. else {
  1409. return _snap(pos, this.params.grid[0], this.params.grid[1]);
  1410. }
  1411. };
  1412. this.snap = function(x, y) {
  1413. if (dragEl == null) return;
  1414. x = x || (this.params.grid ? this.params.grid[0] : DEFAULT_GRID_X);
  1415. y = y || (this.params.grid ? this.params.grid[1] : DEFAULT_GRID_Y);
  1416. var p = this.params.getPosition(dragEl);
  1417. this.params.setPosition(dragEl, _snap(p, x, y, x, y));
  1418. };
  1419. this.setUseGhostProxy = function(val) {
  1420. useGhostProxy = val ? TRUE : FALSE;
  1421. };
  1422. var constrain;
  1423. var negativeFilter = function(pos) {
  1424. return (params.allowNegative === false) ? [ Math.max (0, pos[0]), Math.max(0, pos[1]) ] : pos;
  1425. };
  1426. var _setConstrain = function(value) {
  1427. constrain = typeof value === "function" ? value : value ? function(pos) {
  1428. return negativeFilter([
  1429. Math.max(0, Math.min(constrainRect.w - this.size[0], pos[0])),
  1430. Math.max(0, Math.min(constrainRect.h - this.size[1], pos[1]))
  1431. ]);
  1432. }.bind(this) : function(pos) { return negativeFilter(pos); };
  1433. }.bind(this);
  1434. _setConstrain(typeof this.params.constrain === "function" ? this.params.constrain : (this.params.constrain || this.params.containment));
  1435. /**
  1436. * Sets whether or not the Drag is constrained. A value of 'true' means constrain to parent bounds; a function
  1437. * will be executed and returns true if the position is allowed.
  1438. * @param value
  1439. */
  1440. this.setConstrain = function(value) {
  1441. _setConstrain(value);
  1442. };
  1443. var revertFunction;
  1444. /**
  1445. * Sets a function to call on drag stop, which, if it returns true, indicates that the given element should
  1446. * revert to its position before the previous drag.
  1447. * @param fn
  1448. */
  1449. this.setRevert = function(fn) {
  1450. revertFunction = fn;
  1451. };
  1452. var _assignId = function(obj) {
  1453. if (typeof obj == "function") {
  1454. obj._katavorioId = _uuid();
  1455. return obj._katavorioId;
  1456. } else {
  1457. return obj;
  1458. }
  1459. },
  1460. // a map of { spec -> [ fn, exclusion ] } entries.
  1461. _filters = {},
  1462. _testFilter = function(e) {
  1463. for (var key in _filters) {
  1464. var f = _filters[key];
  1465. var rv = f[0](e);
  1466. if (f[1]) rv = !rv;
  1467. if (!rv) return false;
  1468. }
  1469. return true;
  1470. },
  1471. _setFilter = this.setFilter = function(f, _exclude) {
  1472. if (f) {
  1473. var key = _assignId(f);
  1474. _filters[key] = [
  1475. function(e) {
  1476. var t = e.srcElement || e.target, m;
  1477. if (_isString(f)) {
  1478. m = matchesSelector(t, f, el);
  1479. }
  1480. else if (typeof f === "function") {
  1481. m = f(e, el);
  1482. }
  1483. return m;
  1484. },
  1485. _exclude !== false
  1486. ];
  1487. }
  1488. },
  1489. _addFilter = this.addFilter = _setFilter,
  1490. _removeFilter = this.removeFilter = function(f) {
  1491. var key = typeof f == "function" ? f._katavorioId : f;
  1492. delete _filters[key];
  1493. };
  1494. this.clearAllFilters = function() {
  1495. _filters = {};
  1496. };
  1497. this.canDrag = this.params.canDrag || _true;
  1498. var constrainRect,
  1499. matchingDroppables = [], intersectingDroppables = [];
  1500. this.downListener = function(e) {
  1501. var isNotRightClick = this.rightButtonCanDrag || (e.which !== 3 && e.button !== 2);
  1502. if (isNotRightClick && this.isEnabled() && this.canDrag()) {
  1503. var _f = _testFilter(e) && _inputFilter(e, this.el, this.k);
  1504. if (_f) {
  1505. if (!clone)
  1506. dragEl = this.el;
  1507. else {
  1508. dragEl = this.el.cloneNode(true);
  1509. dragEl.setAttribute("id", null);
  1510. dragEl.style.position = "absolute";
  1511. // the clone node is added to the body; getOffsetRect gives us a value
  1512. // relative to the body.
  1513. var b = getOffsetRect(this.el);
  1514. dragEl.style.left = b.left + "px";
  1515. dragEl.style.top = b.top + "px";
  1516. document.body.appendChild(dragEl);
  1517. }
  1518. consumeStartEvent && _consume(e);
  1519. downAt = _pl(e);
  1520. //
  1521. this.params.bind(document, "mousemove", this.moveListener);
  1522. this.params.bind(document, "mouseup", this.upListener);
  1523. k.markSelection(this);
  1524. k.markPosses(this);
  1525. this.params.addClass(document.body, css.noSelect);
  1526. _dispatch("beforeStart", {el:this.el, pos:posAtDown, e:e, drag:this});
  1527. }
  1528. else if (this.params.consumeFilteredEvents) {
  1529. _consume(e);
  1530. }
  1531. }
  1532. }.bind(this);
  1533. this.moveListener = function(e) {
  1534. if (downAt) {
  1535. if (!moving) {
  1536. var _continue = _dispatch("start", {el:this.el, pos:posAtDown, e:e, drag:this});
  1537. if (_continue !== false) {
  1538. if (!downAt) return;
  1539. this.mark(true);
  1540. moving = true;
  1541. }
  1542. }
  1543. // it is possible that the start event caused the drag to be aborted. So we check
  1544. // again that we are currently dragging.
  1545. if (downAt) {
  1546. intersectingDroppables.length = 0;
  1547. var pos = _pl(e), dx = pos[0] - downAt[0], dy = pos[1] - downAt[1],
  1548. z = this.params.ignoreZoom ? 1 : k.getZoom();
  1549. dx /= z;
  1550. dy /= z;
  1551. this.moveBy(dx, dy, e);
  1552. k.updateSelection(dx, dy, this);
  1553. k.updatePosses(dx, dy, this);
  1554. }
  1555. }
  1556. }.bind(this);
  1557. this.upListener = function(e) {
  1558. if (downAt) {
  1559. downAt = null;
  1560. this.params.unbind(document, "mousemove", this.moveListener);
  1561. this.params.unbind(document, "mouseup", this.upListener);
  1562. this.params.removeClass(document.body, css.noSelect);
  1563. this.unmark(e);
  1564. k.unmarkSelection(this, e);
  1565. k.unmarkPosses(this, e);
  1566. this.stop(e);
  1567. k.notifySelectionDragStop(this, e);
  1568. k.notifyPosseDragStop(this, e);
  1569. moving = false;
  1570. if (clone) {
  1571. dragEl && dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
  1572. dragEl = null;
  1573. }
  1574. intersectingDroppables.length = 0;
  1575. if (revertFunction && revertFunction(this.el, this.params.getPosition(this.el)) === true) {
  1576. this.params.setPosition(this.el, posAtDown);
  1577. _dispatch("revert", this.el);
  1578. }
  1579. }
  1580. }.bind(this);
  1581. this.getFilters = function() { return _filters; };
  1582. this.abort = function() {
  1583. if (downAt != null)
  1584. this.upListener();
  1585. };
  1586. this.getDragElement = function() {
  1587. return dragEl || this.el;
  1588. };
  1589. var listeners = {"start":[], "drag":[], "stop":[], "over":[], "out":[], "beforeStart":[], "revert":[] };
  1590. if (params.events.start) listeners.start.push(params.events.start);
  1591. if (params.events.beforeStart) listeners.beforeStart.push(params.events.beforeStart);
  1592. if (params.events.stop) listeners.stop.push(params.events.stop);
  1593. if (params.events.drag) listeners.drag.push(params.events.drag);
  1594. if (params.events.revert) listeners.revert.push(params.events.revert);
  1595. this.on = function(evt, fn) {
  1596. if (listeners[evt]) listeners[evt].push(fn);
  1597. };
  1598. this.off = function(evt, fn) {
  1599. if (listeners[evt]) {
  1600. var l = [];
  1601. for (var i = 0; i < listeners[evt].length; i++) {
  1602. if (listeners[evt][i] !== fn) l.push(listeners[evt][i]);
  1603. }
  1604. listeners[evt] = l;
  1605. }
  1606. };
  1607. var _dispatch = function(evt, value) {
  1608. if (listeners[evt]) {
  1609. for (var i = 0; i < listeners[evt].length; i++) {
  1610. try {
  1611. listeners[evt][i](value);
  1612. }
  1613. catch (e) { }
  1614. }
  1615. }
  1616. };
  1617. this.notifyStart = function(e) {
  1618. _dispatch("start", {el:this.el, pos:this.params.getPosition(dragEl), e:e, drag:this});
  1619. };
  1620. this.stop = function(e, force) {
  1621. if (force || moving) {
  1622. var positions = [],
  1623. sel = k.getSelection(),
  1624. dPos = this.params.getPosition(dragEl);
  1625. if (sel.length > 1) {
  1626. for (var i = 0; i < sel.length; i++) {
  1627. var p = this.params.getPosition(sel[i].el);
  1628. positions.push([ sel[i].el, { left: p[0], top: p[1] }, sel[i] ]);
  1629. }
  1630. }
  1631. else {
  1632. positions.push([ dragEl, {left:dPos[0], top:dPos[1]}, this ]);
  1633. }
  1634. _dispatch("stop", {
  1635. el: dragEl,
  1636. pos: ghostProxyOffsets || dPos,
  1637. finalPos:dPos,
  1638. e: e,
  1639. drag: this,
  1640. selection:positions
  1641. });
  1642. }
  1643. };
  1644. this.mark = function(andNotify) {
  1645. posAtDown = this.params.getPosition(dragEl);
  1646. pagePosAtDown = this.params.getPosition(dragEl, true);
  1647. pageDelta = [pagePosAtDown[0] - posAtDown[0], pagePosAtDown[1] - posAtDown[1]];
  1648. this.size = this.params.getSize(dragEl);
  1649. matchingDroppables = k.getMatchingDroppables(this);
  1650. _setDroppablesActive(matchingDroppables, true, false, this);
  1651. this.params.addClass(dragEl, this.params.dragClass || css.drag);
  1652. //if (this.params.constrain || this.params.containment) {
  1653. var cs = this.params.getSize(dragEl.parentNode);
  1654. constrainRect = { w:cs[0], h:cs[1] };
  1655. //}
  1656. if (andNotify) {
  1657. k.notifySelectionDragStart(this);
  1658. }
  1659. };
  1660. var ghostProxyOffsets;
  1661. this.unmark = function(e, doNotCheckDroppables) {
  1662. _setDroppablesActive(matchingDroppables, false, true, this);
  1663. if (isConstrained && useGhostProxy(this.el)) {
  1664. ghostProxyOffsets = [dragEl.offsetLeft, dragEl.offsetTop];
  1665. this.el.parentNode.removeChild(dragEl);
  1666. dragEl = this.el;
  1667. }
  1668. else {
  1669. ghostProxyOffsets = null;
  1670. }
  1671. this.params.removeClass(dragEl, this.params.dragClass || css.drag);
  1672. matchingDroppables.length = 0;
  1673. isConstrained = false;
  1674. if (!doNotCheckDroppables) {
  1675. if (intersectingDroppables.length > 0 && ghostProxyOffsets) {
  1676. params.setPosition(this.el, ghostProxyOffsets);
  1677. }
  1678. intersectingDroppables.sort(_rankSort);
  1679. for (var i = 0; i < intersectingDroppables.length; i++) {
  1680. var retVal = intersectingDroppables[i].drop(this, e);
  1681. if (retVal === true) break;
  1682. }
  1683. }
  1684. };
  1685. this.moveBy = function(dx, dy, e) {
  1686. intersectingDroppables.length = 0;
  1687. var desiredLoc = this.toGrid([posAtDown[0] + dx, posAtDown[1] + dy]),
  1688. cPos = constrain(desiredLoc, dragEl);
  1689. if (useGhostProxy(this.el)) {
  1690. if (desiredLoc[0] != cPos[0] || desiredLoc[1] != cPos[1]) {
  1691. if (!isConstrained) {
  1692. var gp = ghostProxy(this.el);
  1693. params.addClass(gp, _classes.ghostProxy);
  1694. this.el.parentNode.appendChild(gp);
  1695. dragEl = gp;
  1696. isConstrained = true;
  1697. }
  1698. cPos = desiredLoc;
  1699. }
  1700. else {
  1701. if (isConstrained) {
  1702. this.el.parentNode.removeChild(dragEl);
  1703. dragEl = this.el;
  1704. isConstrained = false;
  1705. }
  1706. }
  1707. }
  1708. var rect = { x:cPos[0], y:cPos[1], w:this.size[0], h:this.size[1]},
  1709. pageRect = { x:rect.x + pageDelta[0], y:rect.y + pageDelta[1], w:rect.w, h:rect.h},
  1710. focusDropElement = null;
  1711. this.params.setPosition(dragEl, cPos);
  1712. for (var i = 0; i < matchingDroppables.length; i++) {
  1713. var r2 = { x:matchingDroppables[i].pagePosition[0], y:matchingDroppables[i].pagePosition[1], w:matchingDroppables[i].size[0], h:matchingDroppables[i].size[1]};
  1714. if (this.params.intersects(pageRect, r2) && (_multipleDrop || focusDropElement == null || focusDropElement == matchingDroppables[i].el) && matchingDroppables[i].canDrop(this)) {
  1715. if (!focusDropElement) focusDropElement = matchingDroppables[i].el;
  1716. intersectingDroppables.push(matchingDroppables[i]);
  1717. matchingDroppables[i].setHover(this, true, e);
  1718. }
  1719. else if (matchingDroppables[i].isHover()) {
  1720. matchingDroppables[i].setHover(this, false, e);
  1721. }
  1722. }
  1723. _dispatch("drag", {el:this.el, pos:cPos, e:e, drag:this});
  1724. /* test to see if the parent needs to be scrolled (future)
  1725. if (scroll) {
  1726. var pnsl = dragEl.parentNode.scrollLeft, pnst = dragEl.parentNode.scrollTop;
  1727. console.log("scroll!", pnsl, pnst);
  1728. }*/
  1729. };
  1730. this.destroy = function() {
  1731. this.params.unbind(this.el, "mousedown", this.downListener);
  1732. this.params.unbind(document, "mousemove", this.moveListener);
  1733. this.params.unbind(document, "mouseup", this.upListener);
  1734. this.downListener = null;
  1735. this.upListener = null;
  1736. this.moveListener = null;
  1737. };
  1738. // init:register mousedown, and perhaps set a filter
  1739. this.params.bind(this.el, "mousedown", this.downListener);
  1740. // if handle provded, use that. otherwise, try to set a filter.
  1741. // note that a `handle` selector always results in filterExclude being set to false, ie.
  1742. // the selector defines the handle element(s).
  1743. if (this.params.handle)
  1744. _setFilter(this.params.handle, false);
  1745. else
  1746. _setFilter(this.params.filter, this.params.filterExclude);
  1747. };
  1748. var Drop = function(el, params, css, scope) {
  1749. this._class = css.droppable;
  1750. this.params = params || {};
  1751. this.rank = params.rank || 0;
  1752. this._activeClass = this.params.activeClass || css.active;
  1753. this._hoverClass = this.params.hoverClass || css.hover;
  1754. Super.apply(this, arguments);
  1755. var hover = false;
  1756. this.allowLoopback = this.params.allowLoopback !== false;
  1757. this.setActive = function(val) {
  1758. this.params[val ? "addClass" : "removeClass"](this.el, this._activeClass);
  1759. };
  1760. this.updatePosition = function() {
  1761. this.position = this.params.getPosition(this.el);
  1762. this.pagePosition = this.params.getPosition(this.el, true);
  1763. this.size = this.params.getSize(this.el);
  1764. };
  1765. this.canDrop = this.params.canDrop || function(drag) {
  1766. return true;
  1767. };
  1768. this.isHover = function() { return hover; };
  1769. this.setHover = function(drag, val, e) {
  1770. // if turning off hover but this was not the drag that caused the hover, ignore.
  1771. if (val || this.el._katavorioDragHover == null || this.el._katavorioDragHover == drag.el._katavorio) {
  1772. this.params[val ? "addClass" : "removeClass"](this.el, this._hoverClass);
  1773. //this.el._katavorioDragHover = val ? drag.el._katavorio : null;
  1774. this.el._katavorioDragHover = val ? drag.el._katavorio : null;
  1775. if (hover !== val)
  1776. this.params.events[val ? "over" : "out"]({el:this.el, e:e, drag:drag, drop:this});
  1777. hover = val;
  1778. }
  1779. };
  1780. this.drop = function(drag, event) {
  1781. return this.params.events["drop"]({ drag:drag, e:event, drop:this });
  1782. };
  1783. this.destroy = function() {
  1784. this._class = null;
  1785. this._activeClass = null;
  1786. this._hoverClass = null;
  1787. //this.params = null;
  1788. hover = null;
  1789. //this.el = null;
  1790. };
  1791. };
  1792. var _uuid = function() {
  1793. return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  1794. var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
  1795. return v.toString(16);
  1796. }));
  1797. };
  1798. var _rankSort = function(a,b) {
  1799. return a.rank < b.rank ? 1 : a.rank > b.rank ? -1 : 0;
  1800. };
  1801. var _gel = function(el) {
  1802. if (el == null) return null;
  1803. el = (typeof el === "string" || el.constructor == String) ? document.getElementById(el) : el;
  1804. if (el == null) return null;
  1805. el._katavorio = el._katavorio || _uuid();
  1806. return el;
  1807. };
  1808. root.Katavorio = function(katavorioParams) {
  1809. var _selection = [],
  1810. _selectionMap = {};
  1811. this._dragsByScope = {};
  1812. this._dropsByScope = {};
  1813. var _zoom = 1,
  1814. _reg = function(obj, map) {
  1815. _each(obj, function(_obj) {
  1816. for(var i = 0; i < _obj.scopes.length; i++) {
  1817. map[_obj.scopes[i]] = map[_obj.scopes[i]] || [];
  1818. map[_obj.scopes[i]].push(_obj);
  1819. }
  1820. });
  1821. },
  1822. _unreg = function(obj, map) {
  1823. var c = 0;
  1824. _each(obj, function(_obj) {
  1825. for(var i = 0; i < _obj.scopes.length; i++) {
  1826. if (map[_obj.scopes[i]]) {
  1827. var idx = katavorioParams.indexOf(map[_obj.scopes[i]], _obj);
  1828. if (idx != -1) {
  1829. map[_obj.scopes[i]].splice(idx, 1);
  1830. c++;
  1831. }
  1832. }
  1833. }
  1834. });
  1835. return c > 0 ;
  1836. },
  1837. _getMatchingDroppables = this.getMatchingDroppables = function(drag) {
  1838. var dd = [], _m = {};
  1839. for (var i = 0; i < drag.scopes.length; i++) {
  1840. var _dd = this._dropsByScope[drag.scopes[i]];
  1841. if (_dd) {
  1842. for (var j = 0; j < _dd.length; j++) {
  1843. if (_dd[j].canDrop(drag) && !_m[_dd[j].uuid] && (_dd[j].allowLoopback || _dd[j].el !== drag.el)) {
  1844. _m[_dd[j].uuid] = true;
  1845. dd.push(_dd[j]);
  1846. }
  1847. }
  1848. }
  1849. }
  1850. dd.sort(_rankSort);
  1851. return dd;
  1852. },
  1853. _prepareParams = function(p) {
  1854. p = p || {};
  1855. var _p = {
  1856. events:{}
  1857. }, i;
  1858. for (i in katavorioParams) _p[i] = katavorioParams[i];
  1859. for (i in p) _p[i] = p[i];
  1860. // events
  1861. for (i = 0; i < _events.length; i++) {
  1862. _p.events[_events[i]] = p[_events[i]] || _devNull;
  1863. }
  1864. _p.katavorio = this;
  1865. return _p;
  1866. }.bind(this),
  1867. _mistletoe = function(existingDrag, params) {
  1868. for (var i = 0; i < _events.length; i++) {
  1869. if (params[_events[i]]) {
  1870. existingDrag.on(_events[i], params[_events[i]]);
  1871. }
  1872. }
  1873. }.bind(this),
  1874. _css = {},
  1875. overrideCss = katavorioParams.css || {},
  1876. _scope = katavorioParams.scope || _defaultScope;
  1877. // prepare map of css classes based on defaults frst, then optional overrides
  1878. for (var i in _classes) _css[i] = _classes[i];
  1879. for (var i in overrideCss) _css[i] = overrideCss[i];
  1880. var inputFilterSelector = katavorioParams.inputFilterSelector || _defaultInputFilterSelector;
  1881. /**
  1882. * Gets the selector identifying which input elements to filter from drag events.
  1883. * @method getInputFilterSelector
  1884. * @return {String} Current input filter selector.
  1885. */
  1886. this.getInputFilterSelector = function() { return inputFilterSelector; };
  1887. /**
  1888. * Sets the selector identifying which input elements to filter from drag events.
  1889. * @method setInputFilterSelector
  1890. * @param {String} selector Input filter selector to set.
  1891. * @return {Katavorio} Current instance; method may be chained.
  1892. */
  1893. this.setInputFilterSelector = function(selector) {
  1894. inputFilterSelector = selector;
  1895. return this;
  1896. };
  1897. this.draggable = function(el, params) {
  1898. var o = [];
  1899. _each(el, function(_el) {
  1900. _el = _gel(_el);
  1901. if (_el != null) {
  1902. if (_el._katavorioDrag == null) {
  1903. var p = _prepareParams(params);
  1904. _el._katavorioDrag = new Drag(_el, p, _css, _scope);
  1905. _reg(_el._katavorioDrag, this._dragsByScope);
  1906. o.push(_el._katavorioDrag);
  1907. katavorioParams.addClass(_el, _css.draggable);
  1908. }
  1909. else {
  1910. _mistletoe(_el._katavorioDrag, params);
  1911. }
  1912. }
  1913. }.bind(this));
  1914. return o;
  1915. };
  1916. this.droppable = function(el, params) {
  1917. var o = [];
  1918. _each(el, function(_el) {
  1919. _el = _gel(_el);
  1920. if (_el != null) {
  1921. var drop = new Drop(_el, _prepareParams(params), _css, _scope);
  1922. _el._katavorioDrop = _el._katavorioDrop || [];
  1923. _el._katavorioDrop.push(drop);
  1924. _reg(drop, this._dropsByScope);
  1925. o.push(drop);
  1926. katavorioParams.addClass(_el, _css.droppable);
  1927. }
  1928. }.bind(this));
  1929. return o;
  1930. };
  1931. /**
  1932. * @name Katavorio#select
  1933. * @function
  1934. * @desc Adds an element to the current selection (for multiple node drag)
  1935. * @param {Element|String} DOM element - or id of the element - to add.
  1936. */
  1937. this.select = function(el) {
  1938. _each(el, function() {
  1939. var _el = _gel(this);
  1940. if (_el && _el._katavorioDrag) {
  1941. if (!_selectionMap[_el._katavorio]) {
  1942. _selection.push(_el._katavorioDrag);
  1943. _selectionMap[_el._katavorio] = [ _el, _selection.length - 1 ];
  1944. katavorioParams.addClass(_el, _css.selected);
  1945. }
  1946. }
  1947. });
  1948. return this;
  1949. };
  1950. /**
  1951. * @name Katavorio#deselect
  1952. * @function
  1953. * @desc Removes an element from the current selection (for multiple node drag)
  1954. * @param {Element|String} DOM element - or id of the element - to remove.
  1955. */
  1956. this.deselect = function(el) {
  1957. _each(el, function() {
  1958. var _el = _gel(this);
  1959. if (_el && _el._katavorio) {
  1960. var e = _selectionMap[_el._katavorio];
  1961. if (e) {
  1962. var _s = [];
  1963. for (var i = 0; i < _selection.length; i++)
  1964. if (_selection[i].el !== _el) _s.push(_selection[i]);
  1965. _selection = _s;
  1966. delete _selectionMap[_el._katavorio];
  1967. katavorioParams.removeClass(_el, _css.selected);
  1968. }
  1969. }
  1970. });
  1971. return this;
  1972. };
  1973. this.deselectAll = function() {
  1974. for (var i in _selectionMap) {
  1975. var d = _selectionMap[i];
  1976. katavorioParams.removeClass(d[0], _css.selected);
  1977. }
  1978. _selection.length = 0;
  1979. _selectionMap = {};
  1980. };
  1981. this.markSelection = function(drag) {
  1982. _foreach(_selection, function(e) { e.mark(); }, drag);
  1983. };
  1984. this.markPosses = function(drag) {
  1985. if (drag.posses) {
  1986. _each(drag.posses, function(p) {
  1987. if (drag.posseRoles[p] && _posses[p]) {
  1988. _foreach(_posses[p].members, function (d) {
  1989. d.mark();
  1990. }, drag);
  1991. }
  1992. })
  1993. }
  1994. };
  1995. this.unmarkSelection = function(drag, event) {
  1996. _foreach(_selection, function(e) { e.unmark(event); }, drag);
  1997. };
  1998. this.unmarkPosses = function(drag, event) {
  1999. if (drag.posses) {
  2000. _each(drag.posses, function(p) {
  2001. if (drag.posseRoles[p] && _posses[p]) {
  2002. _foreach(_posses[p].members, function (d) {
  2003. d.unmark(event, true);
  2004. }, drag);
  2005. }
  2006. });
  2007. }
  2008. };
  2009. this.getSelection = function() { return _selection.slice(0); };
  2010. this.updateSelection = function(dx, dy, drag) {
  2011. _foreach(_selection, function(e) { e.moveBy(dx, dy); }, drag);
  2012. };
  2013. var _posseAction = function(fn, drag) {
  2014. if (drag.posses) {
  2015. _each(drag.posses, function(p) {
  2016. if (drag.posseRoles[p] && _posses[p]) {
  2017. _foreach(_posses[p].members, function (e) {
  2018. fn(e);
  2019. }, drag);
  2020. }
  2021. });
  2022. }
  2023. };
  2024. this.updatePosses = function(dx, dy, drag) {
  2025. _posseAction(function(e) { e.moveBy(dx, dy); }, drag);
  2026. };
  2027. this.notifyPosseDragStop = function(drag, evt) {
  2028. _posseAction(function(e) { e.stop(evt, true); }, drag);
  2029. };
  2030. this.notifySelectionDragStop = function(drag, evt) {
  2031. _foreach(_selection, function(e) { e.stop(evt, true); }, drag);
  2032. };
  2033. this.notifySelectionDragStart = function(drag, evt) {
  2034. _foreach(_selection, function(e) { e.notifyStart(evt);}, drag);
  2035. };
  2036. this.setZoom = function(z) { _zoom = z; };
  2037. this.getZoom = function() { return _zoom; };
  2038. // does the work of changing scopes
  2039. var _scopeManip = function(kObj, scopes, map, fn) {
  2040. _each(kObj, function(_kObj) {
  2041. _unreg(_kObj, map); // deregister existing scopes
  2042. _kObj[fn](scopes); // set scopes
  2043. _reg(_kObj, map); // register new ones
  2044. });
  2045. };
  2046. _each([ "set", "add", "remove", "toggle"], function(v) {
  2047. this[v + "Scope"] = function(el, scopes) {
  2048. _scopeManip(el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
  2049. _scopeManip(el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
  2050. }.bind(this);
  2051. this[v + "DragScope"] = function(el, scopes) {
  2052. _scopeManip(el.constructor === Drag ? el : el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
  2053. }.bind(this);
  2054. this[v + "DropScope"] = function(el, scopes) {
  2055. _scopeManip(el.constructor === Drop ? el : el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
  2056. }.bind(this);
  2057. }.bind(this));
  2058. this.snapToGrid = function(x, y) {
  2059. for (var s in this._dragsByScope) {
  2060. _foreach(this._dragsByScope[s], function(d) { d.snap(x, y); });
  2061. }
  2062. };
  2063. this.getDragsForScope = function(s) { return this._dragsByScope[s]; };
  2064. this.getDropsForScope = function(s) { return this._dropsByScope[s]; };
  2065. var _destroy = function(el, type, map) {
  2066. el = _gel(el);
  2067. if (el[type]) {
  2068. // remove from selection, if present.
  2069. var selIdx = _selection.indexOf(el[type]);
  2070. if (selIdx >= 0) {
  2071. _selection.splice(selIdx, 1);
  2072. }
  2073. if (_unreg(el[type], map)) {
  2074. _each(el[type], function(kObj) { kObj.destroy() });
  2075. }
  2076. delete el[type];
  2077. }
  2078. };
  2079. this.elementRemoved = function(el) {
  2080. this.destroyDraggable(el);
  2081. this.destroyDroppable(el);
  2082. };
  2083. this.destroyDraggable = function(el) {
  2084. _destroy(el, "_katavorioDrag", this._dragsByScope);
  2085. };
  2086. this.destroyDroppable = function(el) {
  2087. _destroy(el, "_katavorioDrop", this._dropsByScope);
  2088. };
  2089. this.reset = function() {
  2090. this._dragsByScope = {};
  2091. this._dropsByScope = {};
  2092. _selection = [];
  2093. _selectionMap = {};
  2094. _posses = {};
  2095. };
  2096. // ----- groups
  2097. var _posses = {};
  2098. var _processOneSpec = function(el, _spec, dontAddExisting) {
  2099. var posseId = _isString(_spec) ? _spec : _spec.id;
  2100. var active = _isString(_spec) ? true : _spec.active !== false;
  2101. var posse = _posses[posseId] || (function() {
  2102. var g = {name:posseId, members:[]};
  2103. _posses[posseId] = g;
  2104. return g;
  2105. })();
  2106. _each(el, function(_el) {
  2107. if (_el._katavorioDrag) {
  2108. if (dontAddExisting && _el._katavorioDrag.posseRoles[posse.name] != null) return;
  2109. _suggest(posse.members, _el._katavorioDrag);
  2110. _suggest(_el._katavorioDrag.posses, posse.name);
  2111. _el._katavorioDrag.posseRoles[posse.name] = active;
  2112. }
  2113. });
  2114. return posse;
  2115. };
  2116. /**
  2117. * Add the given element to the posse with the given id, creating the group if it at first does not exist.
  2118. * @method addToPosse
  2119. * @param {Element} el Element to add.
  2120. * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
  2121. * the ID of a Posse to which the element should be added as an active participant, or an Object containing
  2122. * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
  2123. * true.
  2124. * @returns {Posse|Posse[]} The Posse(s) to which the element(s) was/were added.
  2125. */
  2126. this.addToPosse = function(el, spec) {
  2127. var posses = [];
  2128. for (var i = 1; i < arguments.length; i++) {
  2129. posses.push(_processOneSpec(el, arguments[i]));
  2130. }
  2131. return posses.length == 1 ? posses[0] : posses;
  2132. };
  2133. /**
  2134. * Sets the posse(s) for the element with the given id, creating those that do not yet exist, and removing from
  2135. * the element any current Posses that are not specified by this method call. This method will not change the
  2136. * active/passive state if it is given a posse in which the element is already a member.
  2137. * @method setPosse
  2138. * @param {Element} el Element to set posse(s) on.
  2139. * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
  2140. * the ID of a Posse to which the element should be added as an active participant, or an Object containing
  2141. * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
  2142. * true.
  2143. * @returns {Posse|Posse[]} The Posse(s) to which the element(s) now belongs.
  2144. */
  2145. this.setPosse = function(el, spec) {
  2146. var posses = [];
  2147. for (var i = 1; i < arguments.length; i++) {
  2148. posses.push(_processOneSpec(el, arguments[i], true).name);
  2149. }
  2150. _each(el, function(_el) {
  2151. if (_el._katavorioDrag) {
  2152. var diff = _difference(_el._katavorioDrag.posses, posses);
  2153. var p = [];
  2154. Array.prototype.push.apply(p, _el._katavorioDrag.posses);
  2155. for (var i = 0; i < diff.length; i++) {
  2156. this.removeFromPosse(_el, diff[i]);
  2157. }
  2158. }
  2159. }.bind(this));
  2160. return posses.length == 1 ? posses[0] : posses;
  2161. };
  2162. /**
  2163. * Remove the given element from the given posse(s).
  2164. * @method removeFromPosse
  2165. * @param {Element} el Element to remove.
  2166. * @param {String...} posseId Varargs parameter: one value for each posse to remove the element from.
  2167. */
  2168. this.removeFromPosse = function(el, posseId) {
  2169. if (arguments.length < 2) throw new TypeError("No posse id provided for remove operation");
  2170. for(var i = 1; i < arguments.length; i++) {
  2171. posseId = arguments[i];
  2172. _each(el, function (_el) {
  2173. if (_el._katavorioDrag && _el._katavorioDrag.posses) {
  2174. var d = _el._katavorioDrag;
  2175. _each(posseId, function (p) {
  2176. _vanquish(_posses[p].members, d);
  2177. _vanquish(d.posses, p);
  2178. delete d.posseRoles[p];
  2179. });
  2180. }
  2181. });
  2182. }
  2183. };
  2184. /**
  2185. * Remove the given element from all Posses to which it belongs.
  2186. * @method removeFromAllPosses
  2187. * @param {Element|Element[]} el Element to remove from Posses.
  2188. */
  2189. this.removeFromAllPosses = function(el) {
  2190. _each(el, function(_el) {
  2191. if (_el._katavorioDrag && _el._katavorioDrag.posses) {
  2192. var d = _el._katavorioDrag;
  2193. _each(d.posses, function(p) {
  2194. _vanquish(_posses[p].members, d);
  2195. });
  2196. d.posses.length = 0;
  2197. d.posseRoles = {};
  2198. }
  2199. });
  2200. };
  2201. /**
  2202. * Changes the participation state for the element in the Posse with the given ID.
  2203. * @param {Element|Element[]} el Element(s) to change state for.
  2204. * @param {String} posseId ID of the Posse to change element state for.
  2205. * @param {Boolean} state True to make active, false to make passive.
  2206. */
  2207. this.setPosseState = function(el, posseId, state) {
  2208. var posse = _posses[posseId];
  2209. if (posse) {
  2210. _each(el, function(_el) {
  2211. if (_el._katavorioDrag && _el._katavorioDrag.posses) {
  2212. _el._katavorioDrag.posseRoles[posse.name] = state;
  2213. }
  2214. });
  2215. }
  2216. };
  2217. };
  2218. root.Katavorio.version = "0.19.2";
  2219. if (typeof exports !== "undefined") {
  2220. exports.Katavorio = root.Katavorio;
  2221. }
  2222. }).call(typeof window !== 'undefined' ? window : this);
  2223. /*
  2224. * jsPlumb
  2225. *
  2226. * Title:jsPlumb 2.3.0
  2227. *
  2228. * Provides a way to visually connect elements on an HTML page, using SVG.
  2229. *
  2230. * This file contains utility functions that run in both browsers and headless.
  2231. *
  2232. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  2233. *
  2234. * http://jsplumbtoolkit.com
  2235. * http://github.com/sporritt/jsplumb
  2236. *
  2237. * Dual licensed under the MIT and GPL2 licenses.
  2238. */
  2239. ;
  2240. (function () {
  2241. var _isa = function (a) {
  2242. return Object.prototype.toString.call(a) === "[object Array]";
  2243. },
  2244. _isnum = function (n) {
  2245. return Object.prototype.toString.call(n) === "[object Number]";
  2246. },
  2247. _iss = function (s) {
  2248. return typeof s === "string";
  2249. },
  2250. _isb = function (s) {
  2251. return typeof s === "boolean";
  2252. },
  2253. _isnull = function (s) {
  2254. return s == null;
  2255. },
  2256. _iso = function (o) {
  2257. return o == null ? false : Object.prototype.toString.call(o) === "[object Object]";
  2258. },
  2259. _isd = function (o) {
  2260. return Object.prototype.toString.call(o) === "[object Date]";
  2261. },
  2262. _isf = function (o) {
  2263. return Object.prototype.toString.call(o) === "[object Function]";
  2264. },
  2265. _isNamedFunction = function(o) {
  2266. return _isf(o) && o.name != null && o.name.length > 0;
  2267. },
  2268. _ise = function (o) {
  2269. for (var i in o) {
  2270. if (o.hasOwnProperty(i)) return false;
  2271. }
  2272. return true;
  2273. };
  2274. var root = this;
  2275. root.jsPlumbUtil = {
  2276. isArray: _isa,
  2277. isString: _iss,
  2278. isBoolean: _isb,
  2279. isNull: _isnull,
  2280. isObject: _iso,
  2281. isDate: _isd,
  2282. isFunction: _isf,
  2283. isEmpty: _ise,
  2284. isNumber: _isnum,
  2285. clone: function (a) {
  2286. if (_iss(a)) return "" + a;
  2287. else if (_isb(a)) return !!a;
  2288. else if (_isd(a)) return new Date(a.getTime());
  2289. else if (_isf(a)) return a;
  2290. else if (_isa(a)) {
  2291. var b = [];
  2292. for (var i = 0; i < a.length; i++)
  2293. b.push(this.clone(a[i]));
  2294. return b;
  2295. }
  2296. else if (_iso(a)) {
  2297. var c = {};
  2298. for (var j in a)
  2299. c[j] = this.clone(a[j]);
  2300. return c;
  2301. }
  2302. else return a;
  2303. },
  2304. merge: function (a, b, collations) {
  2305. // first change the collations array - if present - into a lookup table, because its faster.
  2306. var cMap = {}, ar, i;
  2307. collations = collations || [];
  2308. for (i = 0; i < collations.length; i++)
  2309. cMap[collations[i]] = true;
  2310. var c = this.clone(a);
  2311. for (i in b) {
  2312. if (c[i] == null) {
  2313. c[i] = b[i];
  2314. }
  2315. else if (_iss(b[i]) || _isb(b[i])) {
  2316. if (!cMap[i]) {
  2317. c[i] = b[i]; // if we dont want to collate, just copy it in.
  2318. }
  2319. else {
  2320. ar = [];
  2321. // if c's object is also an array we can keep its values.
  2322. ar.push.apply(ar, _isa(c[i]) ? c[i] : [ c[i] ]);
  2323. ar.push.apply(ar, _isa(b[i]) ? b[i] : [ b[i] ]);
  2324. c[i] = ar;
  2325. }
  2326. }
  2327. else {
  2328. if (_isa(b[i])) {
  2329. ar = [];
  2330. // if c's object is also an array we can keep its values.
  2331. if (_isa(c[i])) ar.push.apply(ar, c[i]);
  2332. ar.push.apply(ar, b[i]);
  2333. c[i] = ar;
  2334. }
  2335. else if (_iso(b[i])) {
  2336. // overwite c's value with an object if it is not already one.
  2337. if (!_iso(c[i]))
  2338. c[i] = {};
  2339. for (var j in b[i]) {
  2340. c[i][j] = b[i][j];
  2341. }
  2342. }
  2343. }
  2344. }
  2345. return c;
  2346. },
  2347. replace: function (inObj, path, value) {
  2348. if (inObj == null) return;
  2349. var q = inObj, t = q;
  2350. path.replace(/([^\.])+/g, function (term, lc, pos, str) {
  2351. var array = term.match(/([^\[0-9]+){1}(\[)([0-9+])/),
  2352. last = pos + term.length >= str.length,
  2353. _getArray = function () {
  2354. return t[array[1]] || (function () {
  2355. t[array[1]] = [];
  2356. return t[array[1]];
  2357. })();
  2358. };
  2359. if (last) {
  2360. // set term = value on current t, creating term as array if necessary.
  2361. if (array)
  2362. _getArray()[array[3]] = value;
  2363. else
  2364. t[term] = value;
  2365. }
  2366. else {
  2367. // set to current t[term], creating t[term] if necessary.
  2368. if (array) {
  2369. var a = _getArray();
  2370. t = a[array[3]] || (function () {
  2371. a[array[3]] = {};
  2372. return a[array[3]];
  2373. })();
  2374. }
  2375. else
  2376. t = t[term] || (function () {
  2377. t[term] = {};
  2378. return t[term];
  2379. })();
  2380. }
  2381. });
  2382. return inObj;
  2383. },
  2384. //
  2385. // chain a list of functions, supplied by [ object, method name, args ], and return on the first
  2386. // one that returns the failValue. if none return the failValue, return the successValue.
  2387. //
  2388. functionChain: function (successValue, failValue, fns) {
  2389. for (var i = 0; i < fns.length; i++) {
  2390. var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]);
  2391. if (o === failValue) {
  2392. return o;
  2393. }
  2394. }
  2395. return successValue;
  2396. },
  2397. // take the given model and expand out any parameters.
  2398. // 'functionPrefix' is optional, and if present, helps jsplumb figure out what to do if a value is a Function.
  2399. // if you do not provide it, jsplumb will run the given values through any functions it finds, and use the function's
  2400. // output as the value in the result. if you do provide the prefix, only functions that are named and have this prefix
  2401. // will be executed; other functions will be passed as values to the output.
  2402. populate: function (model, values, functionPrefix) {
  2403. // for a string, see if it has parameter matches, and if so, try to make the substitutions.
  2404. var getValue = function (fromString) {
  2405. var matches = fromString.match(/(\${.*?})/g);
  2406. if (matches != null) {
  2407. for (var i = 0; i < matches.length; i++) {
  2408. var val = values[matches[i].substring(2, matches[i].length - 1)] || "";
  2409. if (val != null) {
  2410. fromString = fromString.replace(matches[i], val);
  2411. }
  2412. }
  2413. }
  2414. return fromString;
  2415. },
  2416. // process one entry.
  2417. _one = function (d) {
  2418. if (d != null) {
  2419. if (_iss(d)) {
  2420. return getValue(d);
  2421. }
  2422. else if (_isf(d) && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) {
  2423. return d(values);
  2424. }
  2425. else if (_isa(d)) {
  2426. var r = [];
  2427. for (var i = 0; i < d.length; i++)
  2428. r.push(_one(d[i]));
  2429. return r;
  2430. }
  2431. else if (_iso(d)) {
  2432. var s = {};
  2433. for (var j in d) {
  2434. s[j] = _one(d[j]);
  2435. }
  2436. return s;
  2437. }
  2438. else {
  2439. return d;
  2440. }
  2441. }
  2442. };
  2443. return _one(model);
  2444. },
  2445. findWithFunction: function (a, f) {
  2446. if (a)
  2447. for (var i = 0; i < a.length; i++) if (f(a[i])) return i;
  2448. return -1;
  2449. },
  2450. removeWithFunction: function (a, f) {
  2451. var idx = root.jsPlumbUtil.findWithFunction(a, f);
  2452. if (idx > -1) a.splice(idx, 1);
  2453. return idx != -1;
  2454. },
  2455. remove: function (l, v) {
  2456. var idx = l.indexOf(v);
  2457. if (idx > -1) l.splice(idx, 1);
  2458. return idx != -1;
  2459. },
  2460. // TODO support insert index
  2461. addWithFunction: function (list, item, hashFunction) {
  2462. if (root.jsPlumbUtil.findWithFunction(list, hashFunction) == -1) list.push(item);
  2463. },
  2464. addToList: function (map, key, value, insertAtStart) {
  2465. var l = map[key];
  2466. if (l == null) {
  2467. l = [];
  2468. map[key] = l;
  2469. }
  2470. l[insertAtStart ? "unshift" : "push"](value);
  2471. return l;
  2472. },
  2473. suggest : function(list, item, insertAtHead) {
  2474. if (list.indexOf(item) === -1) {
  2475. if (insertAtHead) {
  2476. list.unshift(item);
  2477. } else {
  2478. list.push(item);
  2479. }
  2480. return true;
  2481. }
  2482. return false;
  2483. },
  2484. //
  2485. // extends the given obj (which can be an array) with the given constructor function, prototype functions, and
  2486. // class members, any of which may be null.
  2487. //
  2488. extend: function (child, parent, _protoFn) {
  2489. var i;
  2490. parent = _isa(parent) ? parent : [ parent ];
  2491. for (i = 0; i < parent.length; i++) {
  2492. for (var j in parent[i].prototype) {
  2493. if (parent[i].prototype.hasOwnProperty(j)) {
  2494. child.prototype[j] = parent[i].prototype[j];
  2495. }
  2496. }
  2497. }
  2498. var _makeFn = function (name, protoFn) {
  2499. return function () {
  2500. for (i = 0; i < parent.length; i++) {
  2501. if (parent[i].prototype[name])
  2502. parent[i].prototype[name].apply(this, arguments);
  2503. }
  2504. return protoFn.apply(this, arguments);
  2505. };
  2506. };
  2507. var _oneSet = function (fns) {
  2508. for (var k in fns) {
  2509. child.prototype[k] = _makeFn(k, fns[k]);
  2510. }
  2511. };
  2512. if (arguments.length > 2) {
  2513. for (i = 2; i < arguments.length; i++)
  2514. _oneSet(arguments[i]);
  2515. }
  2516. return child;
  2517. },
  2518. uuid: function () {
  2519. return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2520. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  2521. return v.toString(16);
  2522. }));
  2523. },
  2524. logEnabled: true,
  2525. log: function () {
  2526. if (root.jsPlumbUtil.logEnabled && typeof console != "undefined") {
  2527. try {
  2528. var msg = arguments[arguments.length - 1];
  2529. console.log(msg);
  2530. }
  2531. catch (e) {
  2532. }
  2533. }
  2534. },
  2535. /**
  2536. * Wraps one function with another, creating a placeholder for the
  2537. * wrapped function if it was null. this is used to wrap the various
  2538. * drag/drop event functions - to allow jsPlumb to be notified of
  2539. * important lifecycle events without imposing itself on the user's
  2540. * drag/drop functionality.
  2541. * @method jsPlumbUtil.wrap
  2542. * @param {Function} wrappedFunction original function to wrap; may be null.
  2543. * @param {Function} newFunction function to wrap the original with.
  2544. * @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should
  2545. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  2546. * note that this is a simple comparison and only works for primitives right now.
  2547. */
  2548. wrap: function (wrappedFunction, newFunction, returnOnThisValue) {
  2549. wrappedFunction = wrappedFunction || function () {
  2550. };
  2551. newFunction = newFunction || function () {
  2552. };
  2553. return function () {
  2554. var r = null;
  2555. try {
  2556. r = newFunction.apply(this, arguments);
  2557. } catch (e) {
  2558. root.jsPlumbUtil.log("jsPlumb function failed : " + e);
  2559. }
  2560. if (returnOnThisValue == null || (r !== returnOnThisValue)) {
  2561. try {
  2562. r = wrappedFunction.apply(this, arguments);
  2563. } catch (e) {
  2564. root.jsPlumbUtil.log("wrapped function failed : " + e);
  2565. }
  2566. }
  2567. return r;
  2568. };
  2569. }
  2570. };
  2571. root.jsPlumbUtil.EventGenerator = function () {
  2572. var _listeners = {},
  2573. eventsSuspended = false,
  2574. // this is a list of events that should re-throw any errors that occur during their dispatch. it is current private.
  2575. eventsToDieOn = { "ready": true };
  2576. this.bind = function (event, listener, insertAtStart) {
  2577. var _one = function(evt) {
  2578. root.jsPlumbUtil.addToList(_listeners, evt, listener, insertAtStart);
  2579. listener.__jsPlumb = listener.__jsPlumb || {};
  2580. listener.__jsPlumb[root.jsPlumbUtil.uuid()] = evt;
  2581. };
  2582. if (typeof event === "string") _one(event);
  2583. else if (event.length != null) {
  2584. for (var i = 0; i < event.length; i++) {
  2585. _one(event[i]);
  2586. }
  2587. }
  2588. return this;
  2589. };
  2590. this.fire = function (event, value, originalEvent) {
  2591. if (!eventsSuspended && _listeners[event]) {
  2592. var l = _listeners[event].length, i = 0, _gone = false, ret = null;
  2593. if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) {
  2594. while (!_gone && i < l && ret !== false) {
  2595. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  2596. // method will have the whole call stack available in the debugger.
  2597. if (eventsToDieOn[event])
  2598. _listeners[event][i].apply(this, [ value, originalEvent]);
  2599. else {
  2600. try {
  2601. ret = _listeners[event][i].apply(this, [ value, originalEvent ]);
  2602. } catch (e) {
  2603. root.jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e);
  2604. }
  2605. }
  2606. i++;
  2607. if (_listeners == null || _listeners[event] == null)
  2608. _gone = true;
  2609. }
  2610. }
  2611. }
  2612. return this;
  2613. };
  2614. this.unbind = function (eventOrListener, listener) {
  2615. if (arguments.length === 0) {
  2616. _listeners = {};
  2617. }
  2618. else if (arguments.length === 1) {
  2619. if (typeof eventOrListener === "string")
  2620. delete _listeners[eventOrListener];
  2621. else if (eventOrListener.__jsPlumb) {
  2622. var evt;
  2623. for (var i in eventOrListener.__jsPlumb) {
  2624. evt = eventOrListener.__jsPlumb[i];
  2625. root.jsPlumbUtil.remove(_listeners[evt] || [], eventOrListener);
  2626. }
  2627. }
  2628. }
  2629. else if (arguments.length === 2) {
  2630. root.jsPlumbUtil.remove(_listeners[eventOrListener] || [], listener);
  2631. }
  2632. return this;
  2633. };
  2634. this.getListener = function (forEvent) {
  2635. return _listeners[forEvent];
  2636. };
  2637. this.setSuspendEvents = function (val) {
  2638. eventsSuspended = val;
  2639. };
  2640. this.isSuspendEvents = function () {
  2641. return eventsSuspended;
  2642. };
  2643. this.silently = function(fn) {
  2644. this.setSuspendEvents(true);
  2645. try {
  2646. fn();
  2647. }
  2648. catch (e) {
  2649. root.jsPlumbUtil.log("Cannot execute silent function " + e);
  2650. }
  2651. this.setSuspendEvents(false);
  2652. };
  2653. this.cleanupListeners = function () {
  2654. for (var i in _listeners) {
  2655. _listeners[i] = null;
  2656. }
  2657. };
  2658. };
  2659. root.jsPlumbUtil.EventGenerator.prototype = {
  2660. cleanup: function () {
  2661. this.cleanupListeners();
  2662. }
  2663. };
  2664. if (typeof exports !== "undefined") {
  2665. exports.jsPlumbUtil = root.jsPlumbUtil;
  2666. }
  2667. }).call(typeof window !== 'undefined' ? window : this);
  2668. /*
  2669. * jsPlumb
  2670. *
  2671. * Title:jsPlumb 2.3.0
  2672. *
  2673. * Provides a way to visually connect elements on an HTML page, using SVG.
  2674. *
  2675. * This file contains utility functions that run in browsers only.
  2676. *
  2677. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  2678. *
  2679. * http://jsplumbtoolkit.com
  2680. * http://github.com/sporritt/jsplumb
  2681. *
  2682. * Dual licensed under the MIT and GPL2 licenses.
  2683. */
  2684. ;(function() {
  2685. "use strict";
  2686. var root = this;
  2687. root.jsPlumbUtil.matchesSelector = function(el, selector, ctx) {
  2688. ctx = ctx || el.parentNode;
  2689. var possibles = ctx.querySelectorAll(selector);
  2690. for (var i = 0; i < possibles.length; i++) {
  2691. if (possibles[i] === el)
  2692. return true;
  2693. }
  2694. return false;
  2695. };
  2696. root.jsPlumbUtil.consume = function(e, doNotPreventDefault) {
  2697. if (e.stopPropagation)
  2698. e.stopPropagation();
  2699. else
  2700. e.returnValue = false;
  2701. if (!doNotPreventDefault && e.preventDefault)
  2702. e.preventDefault();
  2703. };
  2704. /*
  2705. * Function: sizeElement
  2706. * Helper to size and position an element. You would typically use
  2707. * this when writing your own Connector or Endpoint implementation.
  2708. *
  2709. * Parameters:
  2710. * x - [int] x position for the element origin
  2711. * y - [int] y position for the element origin
  2712. * w - [int] width of the element
  2713. * h - [int] height of the element
  2714. *
  2715. */
  2716. root.jsPlumbUtil.sizeElement = function(el, x, y, w, h) {
  2717. if (el) {
  2718. el.style.height = h + "px";
  2719. el.height = h;
  2720. el.style.width = w + "px";
  2721. el.width = w;
  2722. el.style.left = x + "px";
  2723. el.style.top = y + "px";
  2724. }
  2725. };
  2726. }).call(typeof window !== 'undefined' ? window : this);
  2727. /*
  2728. * jsPlumb
  2729. *
  2730. * Title:jsPlumb 2.3.0
  2731. *
  2732. * Provides a way to visually connect elements on an HTML page, using SVG.
  2733. *
  2734. * This file contains the core code.
  2735. *
  2736. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  2737. *
  2738. * http://jsplumbtoolkit.com
  2739. * http://github.com/sporritt/jsplumb
  2740. *
  2741. * Dual licensed under the MIT and GPL2 licenses.
  2742. */
  2743. (function () {
  2744. "use strict";
  2745. var root = this;
  2746. var connectorTypes = [], rendererTypes;
  2747. var _ju = root.jsPlumbUtil,
  2748. /**
  2749. * creates a timestamp, using milliseconds since 1970, but as a string.
  2750. */
  2751. _timestamp = function () {
  2752. return "" + (new Date()).getTime();
  2753. },
  2754. // helper method to update the hover style whenever it, or paintStyle, changes.
  2755. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  2756. // top.
  2757. _updateHoverStyle = function (component) {
  2758. if (component._jsPlumb.paintStyle && component._jsPlumb.hoverPaintStyle) {
  2759. var mergedHoverStyle = {};
  2760. jsPlumb.extend(mergedHoverStyle, component._jsPlumb.paintStyle);
  2761. jsPlumb.extend(mergedHoverStyle, component._jsPlumb.hoverPaintStyle);
  2762. delete component._jsPlumb.hoverPaintStyle;
  2763. // we want the fill of paintStyle to override a gradient, if possible.
  2764. if (mergedHoverStyle.gradient && component._jsPlumb.paintStyle.fill)
  2765. delete mergedHoverStyle.gradient;
  2766. component._jsPlumb.hoverPaintStyle = mergedHoverStyle;
  2767. }
  2768. },
  2769. events = ["tap", "dbltap", "click", "dblclick", "mouseover", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ],
  2770. eventFilters = { "mouseout": "mouseleave", "mouseexit": "mouseleave" },
  2771. _updateAttachedElements = function (component, state, timestamp, sourceElement) {
  2772. var affectedElements = component.getAttachedElements();
  2773. if (affectedElements) {
  2774. for (var i = 0, j = affectedElements.length; i < j; i++) {
  2775. if (!sourceElement || sourceElement != affectedElements[i])
  2776. affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements.
  2777. }
  2778. }
  2779. },
  2780. _splitType = function (t) {
  2781. return t == null ? null : t.split(" ");
  2782. },
  2783. _mapType = function(map, obj, typeId) {
  2784. for (var i in obj)
  2785. map[i] = typeId;
  2786. },
  2787. _each = function(fn, obj) {
  2788. obj = _ju.isArray(obj) || (obj.length != null && !_ju.isString(obj)) ? obj : [ obj ];
  2789. for (var i = 0; i < obj.length; i++) {
  2790. try {
  2791. fn.apply(obj[i], [ obj[i] ]);
  2792. }
  2793. catch (e) {
  2794. _ju.log(".each iteration failed : " + e);
  2795. }
  2796. }
  2797. },
  2798. _applyTypes = function (component, params, doNotRepaint) {
  2799. if (component.getDefaultType) {
  2800. var td = component.getTypeDescriptor(), map = {};
  2801. var defType = component.getDefaultType();
  2802. var o = _ju.merge({}, defType);
  2803. _mapType(map, defType, "__default");
  2804. for (var i = 0, j = component._jsPlumb.types.length; i < j; i++) {
  2805. var tid = component._jsPlumb.types[i];
  2806. if (tid !== "__default") {
  2807. var _t = component._jsPlumb.instance.getType(tid, td);
  2808. if (_t != null) {
  2809. o = _ju.merge(o, _t, [ "cssClass" ]);
  2810. _mapType(map, _t, tid);
  2811. }
  2812. }
  2813. }
  2814. if (params) {
  2815. o = _ju.populate(o, params, "_");
  2816. }
  2817. component.applyType(o, doNotRepaint, map);
  2818. if (!doNotRepaint) component.repaint();
  2819. }
  2820. },
  2821. // ------------------------------ BEGIN jsPlumbUIComponent --------------------------------------------
  2822. jsPlumbUIComponent = root.jsPlumbUIComponent = function (params) {
  2823. _ju.EventGenerator.apply(this, arguments);
  2824. var self = this,
  2825. a = arguments,
  2826. idPrefix = self.idPrefix,
  2827. id = idPrefix + (new Date()).getTime();
  2828. this._jsPlumb = {
  2829. instance: params._jsPlumb,
  2830. parameters: params.parameters || {},
  2831. paintStyle: null,
  2832. hoverPaintStyle: null,
  2833. paintStyleInUse: null,
  2834. hover: false,
  2835. beforeDetach: params.beforeDetach,
  2836. beforeDrop: params.beforeDrop,
  2837. overlayPlacements: [],
  2838. hoverClass: params.hoverClass || params._jsPlumb.Defaults.HoverClass,
  2839. types: [],
  2840. typeCache:{}
  2841. };
  2842. this.cacheTypeItem = function(key, item, typeId) {
  2843. this._jsPlumb.typeCache[typeId] = this._jsPlumb.typeCache[typeId] || {};
  2844. this._jsPlumb.typeCache[typeId][key] = item;
  2845. };
  2846. this.getCachedTypeItem = function(key, typeId) {
  2847. return this._jsPlumb.typeCache[typeId] ? this._jsPlumb.typeCache[typeId][key] : null;
  2848. };
  2849. this.getId = function () {
  2850. return id;
  2851. };
  2852. // ----------------------------- default type --------------------------------------------
  2853. var o = params.overlays || [], oo = {};
  2854. if (this.defaultOverlayKeys) {
  2855. for (var i = 0; i < this.defaultOverlayKeys.length; i++)
  2856. Array.prototype.push.apply(o, this._jsPlumb.instance.Defaults[this.defaultOverlayKeys[i]] || []);
  2857. for (i = 0; i < o.length; i++) {
  2858. // if a string, convert to object representation so that we can store the typeid on it.
  2859. // also assign an id.
  2860. var fo = jsPlumb.convertToFullOverlaySpec(o[i]);
  2861. oo[fo[1].id] = fo;
  2862. }
  2863. }
  2864. var _defaultType = {
  2865. overlays:oo,
  2866. parameters: params.parameters || {},
  2867. scope: params.scope || this._jsPlumb.instance.getDefaultScope()
  2868. };
  2869. this.getDefaultType = function() {
  2870. return _defaultType;
  2871. };
  2872. this.appendToDefaultType = function(obj) {
  2873. for (var i in obj) _defaultType[i] = obj[i];
  2874. };
  2875. // ----------------------------- end default type --------------------------------------------
  2876. // all components can generate events
  2877. if (params.events) {
  2878. for (i in params.events)
  2879. self.bind(i, params.events[i]);
  2880. }
  2881. // all components get this clone function.
  2882. // TODO issue 116 showed a problem with this - it seems 'a' that is in
  2883. // the clone function's scope is shared by all invocations of it, the classic
  2884. // JS closure problem. for now, jsPlumb does a version of this inline where
  2885. // it used to call clone. but it would be nice to find some time to look
  2886. // further at this.
  2887. this.clone = function () {
  2888. var o = Object.create(this.constructor.prototype);
  2889. this.constructor.apply(o, a);
  2890. return o;
  2891. }.bind(this);
  2892. // user can supply a beforeDetach callback, which will be executed before a detach
  2893. // is performed; returning false prevents the detach.
  2894. this.isDetachAllowed = function (connection) {
  2895. var r = true;
  2896. if (this._jsPlumb.beforeDetach) {
  2897. try {
  2898. r = this._jsPlumb.beforeDetach(connection);
  2899. }
  2900. catch (e) {
  2901. _ju.log("jsPlumb: beforeDetach callback failed", e);
  2902. }
  2903. }
  2904. return r;
  2905. };
  2906. // user can supply a beforeDrop callback, which will be executed before a dropped
  2907. // connection is confirmed. user can return false to reject connection.
  2908. this.isDropAllowed = function (sourceId, targetId, scope, connection, dropEndpoint, source, target) {
  2909. var r = this._jsPlumb.instance.checkCondition("beforeDrop", {
  2910. sourceId: sourceId,
  2911. targetId: targetId,
  2912. scope: scope,
  2913. connection: connection,
  2914. dropEndpoint: dropEndpoint,
  2915. source: source, target: target
  2916. });
  2917. if (this._jsPlumb.beforeDrop) {
  2918. try {
  2919. r = this._jsPlumb.beforeDrop({
  2920. sourceId: sourceId,
  2921. targetId: targetId,
  2922. scope: scope,
  2923. connection: connection,
  2924. dropEndpoint: dropEndpoint,
  2925. source: source, target: target
  2926. });
  2927. }
  2928. catch (e) {
  2929. _ju.log("jsPlumb: beforeDrop callback failed", e);
  2930. }
  2931. }
  2932. return r;
  2933. };
  2934. var domListeners = [];
  2935. // sets the component associated with listener events. for instance, an overlay delegates
  2936. // its events back to a connector. but if the connector is swapped on the underlying connection,
  2937. // then this component must be changed. This is called by setConnector in the Connection class.
  2938. this.setListenerComponent = function (c) {
  2939. for (var i = 0; i < domListeners.length; i++)
  2940. domListeners[i][3] = c;
  2941. };
  2942. };
  2943. var _removeTypeCssHelper = function (component, typeIndex) {
  2944. var typeId = component._jsPlumb.types[typeIndex],
  2945. type = component._jsPlumb.instance.getType(typeId, component.getTypeDescriptor());
  2946. if (type != null) {
  2947. if (type.cssClass && component.canvas)
  2948. component._jsPlumb.instance.removeClass(component.canvas, type.cssClass);
  2949. }
  2950. };
  2951. _ju.extend(root.jsPlumbUIComponent, _ju.EventGenerator, {
  2952. getParameter: function (name) {
  2953. return this._jsPlumb.parameters[name];
  2954. },
  2955. setParameter: function (name, value) {
  2956. this._jsPlumb.parameters[name] = value;
  2957. },
  2958. getParameters: function () {
  2959. return this._jsPlumb.parameters;
  2960. },
  2961. setParameters: function (p) {
  2962. this._jsPlumb.parameters = p;
  2963. },
  2964. getClass:function() {
  2965. return jsPlumb.getClass(this.canvas);
  2966. },
  2967. hasClass:function(clazz) {
  2968. return jsPlumb.hasClass(this.canvas, clazz);
  2969. },
  2970. addClass: function (clazz) {
  2971. jsPlumb.addClass(this.canvas, clazz);
  2972. },
  2973. removeClass: function (clazz) {
  2974. jsPlumb.removeClass(this.canvas, clazz);
  2975. },
  2976. updateClasses: function (classesToAdd, classesToRemove) {
  2977. jsPlumb.updateClasses(this.canvas, classesToAdd, classesToRemove);
  2978. },
  2979. setType: function (typeId, params, doNotRepaint) {
  2980. this.clearTypes();
  2981. this._jsPlumb.types = _splitType(typeId) || [];
  2982. _applyTypes(this, params, doNotRepaint);
  2983. },
  2984. getType: function () {
  2985. return this._jsPlumb.types;
  2986. },
  2987. reapplyTypes: function (params, doNotRepaint) {
  2988. _applyTypes(this, params, doNotRepaint);
  2989. },
  2990. hasType: function (typeId) {
  2991. return this._jsPlumb.types.indexOf(typeId) != -1;
  2992. },
  2993. addType: function (typeId, params, doNotRepaint) {
  2994. var t = _splitType(typeId), _cont = false;
  2995. if (t != null) {
  2996. for (var i = 0, j = t.length; i < j; i++) {
  2997. if (!this.hasType(t[i])) {
  2998. this._jsPlumb.types.push(t[i]);
  2999. _cont = true;
  3000. }
  3001. }
  3002. if (_cont) _applyTypes(this, params, doNotRepaint);
  3003. }
  3004. },
  3005. removeType: function (typeId, params, doNotRepaint) {
  3006. var t = _splitType(typeId), _cont = false, _one = function (tt) {
  3007. var idx = this._jsPlumb.types.indexOf(tt);
  3008. if (idx != -1) {
  3009. // remove css class if necessary
  3010. _removeTypeCssHelper(this, idx);
  3011. this._jsPlumb.types.splice(idx, 1);
  3012. return true;
  3013. }
  3014. return false;
  3015. }.bind(this);
  3016. if (t != null) {
  3017. for (var i = 0, j = t.length; i < j; i++) {
  3018. _cont = _one(t[i]) || _cont;
  3019. }
  3020. if (_cont) _applyTypes(this, params, doNotRepaint);
  3021. }
  3022. },
  3023. clearTypes: function (params, doNotRepaint) {
  3024. var i = this._jsPlumb.types.length;
  3025. for (var j = 0; j < i; j++) {
  3026. _removeTypeCssHelper(this, 0);
  3027. this._jsPlumb.types.splice(0, 1);
  3028. }
  3029. _applyTypes(this, params, doNotRepaint);
  3030. },
  3031. toggleType: function (typeId, params, doNotRepaint) {
  3032. var t = _splitType(typeId);
  3033. if (t != null) {
  3034. for (var i = 0, j = t.length; i < j; i++) {
  3035. var idx = this._jsPlumb.types.indexOf(t[i]);
  3036. if (idx != -1) {
  3037. _removeTypeCssHelper(this, idx);
  3038. this._jsPlumb.types.splice(idx, 1);
  3039. }
  3040. else
  3041. this._jsPlumb.types.push(t[i]);
  3042. }
  3043. _applyTypes(this, params, doNotRepaint);
  3044. }
  3045. },
  3046. applyType: function (t, doNotRepaint) {
  3047. this.setPaintStyle(t.paintStyle, doNotRepaint);
  3048. this.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint);
  3049. if (t.parameters) {
  3050. for (var i in t.parameters)
  3051. this.setParameter(i, t.parameters[i]);
  3052. }
  3053. this._jsPlumb.paintStyleInUse = this.getPaintStyle();
  3054. },
  3055. setPaintStyle: function (style, doNotRepaint) {
  3056. // this._jsPlumb.paintStyle = jsPlumb.extend({}, style);
  3057. // TODO figure out if we want components to clone paintStyle so as not to share it.
  3058. this._jsPlumb.paintStyle = style;
  3059. this._jsPlumb.paintStyleInUse = this._jsPlumb.paintStyle;
  3060. _updateHoverStyle(this);
  3061. if (!doNotRepaint) this.repaint();
  3062. },
  3063. getPaintStyle: function () {
  3064. return this._jsPlumb.paintStyle;
  3065. },
  3066. setHoverPaintStyle: function (style, doNotRepaint) {
  3067. //this._jsPlumb.hoverPaintStyle = jsPlumb.extend({}, style);
  3068. // TODO figure out if we want components to clone paintStyle so as not to share it.
  3069. this._jsPlumb.hoverPaintStyle = style;
  3070. _updateHoverStyle(this);
  3071. if (!doNotRepaint) this.repaint();
  3072. },
  3073. getHoverPaintStyle: function () {
  3074. return this._jsPlumb.hoverPaintStyle;
  3075. },
  3076. destroy: function (force) {
  3077. if (force || this.typeId == null) {
  3078. this.cleanupListeners(); // this is on EventGenerator
  3079. this.clone = null;
  3080. this._jsPlumb = null;
  3081. }
  3082. },
  3083. isHover: function () {
  3084. return this._jsPlumb.hover;
  3085. },
  3086. setHover: function (hover, ignoreAttachedElements, timestamp) {
  3087. // while dragging, we ignore these events. this keeps the UI from flashing and
  3088. // swishing and whatevering.
  3089. if (this._jsPlumb && !this._jsPlumb.instance.currentlyDragging && !this._jsPlumb.instance.isHoverSuspended()) {
  3090. this._jsPlumb.hover = hover;
  3091. if (this.canvas != null) {
  3092. if (this._jsPlumb.instance.hoverClass != null) {
  3093. var method = hover ? "addClass" : "removeClass";
  3094. this._jsPlumb.instance[method](this.canvas, this._jsPlumb.instance.hoverClass);
  3095. }
  3096. if (this._jsPlumb.hoverClass != null) {
  3097. this._jsPlumb.instance[method](this.canvas, this._jsPlumb.hoverClass);
  3098. }
  3099. }
  3100. if (this._jsPlumb.hoverPaintStyle != null) {
  3101. this._jsPlumb.paintStyleInUse = hover ? this._jsPlumb.hoverPaintStyle : this._jsPlumb.paintStyle;
  3102. if (!this._jsPlumb.instance.isSuspendDrawing()) {
  3103. timestamp = timestamp || _timestamp();
  3104. this.repaint({timestamp: timestamp, recalc: false});
  3105. }
  3106. }
  3107. // get the list of other affected elements, if supported by this component.
  3108. // for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  3109. if (this.getAttachedElements && !ignoreAttachedElements)
  3110. _updateAttachedElements(this, hover, _timestamp(), this);
  3111. }
  3112. }
  3113. });
  3114. // ------------------------------ END jsPlumbUIComponent --------------------------------------------
  3115. var _jsPlumbInstanceIndex = 0,
  3116. getInstanceIndex = function () {
  3117. var i = _jsPlumbInstanceIndex + 1;
  3118. _jsPlumbInstanceIndex++;
  3119. return i;
  3120. };
  3121. var jsPlumbInstance = root.jsPlumbInstance = function (_defaults) {
  3122. this.version = "2.4.2";
  3123. if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
  3124. this.logEnabled = this.Defaults.LogEnabled;
  3125. this._connectionTypes = {};
  3126. this._endpointTypes = {};
  3127. _ju.EventGenerator.apply(this);
  3128. var _currentInstance = this,
  3129. _instanceIndex = getInstanceIndex(),
  3130. _bb = _currentInstance.bind,
  3131. _initialDefaults = {},
  3132. _zoom = 1,
  3133. _info = function (el) {
  3134. if (el == null) return null;
  3135. else if (el.nodeType == 3 || el.nodeType == 8) {
  3136. return { el:el, text:true };
  3137. }
  3138. else {
  3139. var _el = _currentInstance.getElement(el);
  3140. return { el: _el, id: (_ju.isString(el) && _el == null) ? el : _getId(_el) };
  3141. }
  3142. };
  3143. this.getInstanceIndex = function () {
  3144. return _instanceIndex;
  3145. };
  3146. this.setZoom = function (z, repaintEverything) {
  3147. _zoom = z;
  3148. _currentInstance.fire("zoom", _zoom);
  3149. if (repaintEverything) _currentInstance.repaintEverything();
  3150. return true;
  3151. };
  3152. this.getZoom = function () {
  3153. return _zoom;
  3154. };
  3155. for (var i in this.Defaults)
  3156. _initialDefaults[i] = this.Defaults[i];
  3157. var _container, _containerDelegations = [];
  3158. this.unbindContainer = function() {
  3159. if (_container != null && _containerDelegations.length > 0) {
  3160. for (var i = 0; i < _containerDelegations.length; i++) {
  3161. _currentInstance.off(_container, _containerDelegations[i][0], _containerDelegations[i][1]);
  3162. }
  3163. }
  3164. };
  3165. this.setContainer = function (c) {
  3166. this.unbindContainer();
  3167. // get container as dom element.
  3168. c = this.getElement(c);
  3169. // move existing connections and endpoints, if any.
  3170. this.select().each(function (conn) {
  3171. conn.moveParent(c);
  3172. });
  3173. this.selectEndpoints().each(function (ep) {
  3174. ep.moveParent(c);
  3175. });
  3176. // set container.
  3177. var previousContainer = _container;
  3178. _container = c;
  3179. _containerDelegations.length = 0;
  3180. var eventAliases = {
  3181. "endpointclick":"endpointClick",
  3182. "endpointdblclick":"endpointDblClick"
  3183. };
  3184. var _oneDelegateHandler = function (id, e, componentType) {
  3185. var t = e.srcElement || e.target,
  3186. jp = (t && t.parentNode ? t.parentNode._jsPlumb : null) || (t ? t._jsPlumb : null) || (t && t.parentNode && t.parentNode.parentNode ? t.parentNode.parentNode._jsPlumb : null);
  3187. if (jp) {
  3188. jp.fire(id, jp, e);
  3189. var alias = componentType ? eventAliases[componentType + id] || id : id;
  3190. // jsplumb also fires every event coming from components/overlays. That's what the test for `jp.component` is for.
  3191. _currentInstance.fire(alias, jp.component || jp, e);
  3192. }
  3193. };
  3194. var _addOneDelegate = function(eventId, selector, fn) {
  3195. _containerDelegations.push([eventId, fn]);
  3196. _currentInstance.on(_container, eventId, selector, fn);
  3197. };
  3198. // delegate one event on the container to jsplumb elements. it might be possible to
  3199. // abstract this out: each of endpoint, connection and overlay could register themselves with
  3200. // jsplumb as "component types" or whatever, and provide a suitable selector. this would be
  3201. // done by the renderer (although admittedly from 2.0 onwards we're not supporting vml anymore)
  3202. var _oneDelegate = function (id) {
  3203. // connections.
  3204. _addOneDelegate(id, ".jtk-connector", function (e) {
  3205. _oneDelegateHandler(id, e);
  3206. });
  3207. // endpoints. note they can have an enclosing div, or not.
  3208. _addOneDelegate(id, ".jtk-endpoint", function (e) {
  3209. _oneDelegateHandler(id, e, "endpoint");
  3210. });
  3211. // overlays
  3212. _addOneDelegate(id, ".jtk-overlay", function (e) {
  3213. _oneDelegateHandler(id, e);
  3214. });
  3215. };
  3216. for (var i = 0; i < events.length; i++)
  3217. _oneDelegate(events[i]);
  3218. // managed elements
  3219. for (var elId in managedElements) {
  3220. var el = managedElements[elId].el;
  3221. if (el.parentNode === previousContainer) {
  3222. previousContainer.removeChild(el);
  3223. _container.appendChild(el);
  3224. }
  3225. }
  3226. };
  3227. this.getContainer = function () {
  3228. return _container;
  3229. };
  3230. this.bind = function (event, fn) {
  3231. if ("ready" === event && initialized) fn();
  3232. else _bb.apply(_currentInstance, [event, fn]);
  3233. };
  3234. _currentInstance.importDefaults = function (d) {
  3235. for (var i in d) {
  3236. _currentInstance.Defaults[i] = d[i];
  3237. }
  3238. if (d.Container)
  3239. _currentInstance.setContainer(d.Container);
  3240. return _currentInstance;
  3241. };
  3242. _currentInstance.restoreDefaults = function () {
  3243. _currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults);
  3244. return _currentInstance;
  3245. };
  3246. var log = null,
  3247. initialized = false,
  3248. // TODO remove from window scope
  3249. connections = [],
  3250. // map of element id -> endpoint lists. an element can have an arbitrary
  3251. // number of endpoints on it, and not all of them have to be connected
  3252. // to anything.
  3253. endpointsByElement = {},
  3254. endpointsByUUID = {},
  3255. managedElements = {},
  3256. offsets = {},
  3257. offsetTimestamps = {},
  3258. draggableStates = {},
  3259. connectionBeingDragged = false,
  3260. sizes = [],
  3261. _suspendDrawing = false,
  3262. _suspendedAt = null,
  3263. DEFAULT_SCOPE = this.Defaults.Scope,
  3264. _curIdStamp = 1,
  3265. _idstamp = function () {
  3266. return "" + _curIdStamp++;
  3267. },
  3268. //
  3269. // appends an element to some other element, which is calculated as follows:
  3270. //
  3271. // 1. if Container exists, use that element.
  3272. // 2. if the 'parent' parameter exists, use that.
  3273. // 3. otherwise just use the root element.
  3274. //
  3275. //
  3276. _appendElement = function (el, parent) {
  3277. if (_container)
  3278. _container.appendChild(el);
  3279. else if (!parent)
  3280. this.appendToRoot(el);
  3281. else
  3282. this.getElement(parent).appendChild(el);
  3283. }.bind(this),
  3284. //
  3285. // Draws an endpoint and its connections. this is the main entry point into drawing connections as well
  3286. // as endpoints, since jsPlumb is endpoint-centric under the hood.
  3287. //
  3288. // @param element element to draw (of type library specific element object)
  3289. // @param ui UI object from current library's event system. optional.
  3290. // @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  3291. // @param clearEdits defaults to false; indicates that mouse edits for connectors should be cleared
  3292. ///
  3293. _draw = function (element, ui, timestamp, clearEdits) {
  3294. if (!_suspendDrawing) {
  3295. var id = _getId(element),
  3296. repaintEls,
  3297. dm = _currentInstance.getDragManager();
  3298. if (dm) repaintEls = dm.getElementsForDraggable(id);
  3299. if (timestamp == null) timestamp = _timestamp();
  3300. // update the offset of everything _before_ we try to draw anything.
  3301. var o = _updateOffset({ elId: id, offset: ui, recalc: false, timestamp: timestamp });
  3302. if (repaintEls && o && o.o) {
  3303. for (var i in repaintEls) {
  3304. _updateOffset({
  3305. elId: repaintEls[i].id,
  3306. offset: {
  3307. left: o.o.left + repaintEls[i].offset.left,
  3308. top: o.o.top + repaintEls[i].offset.top
  3309. },
  3310. recalc: false,
  3311. timestamp: timestamp
  3312. });
  3313. }
  3314. }
  3315. _currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits);
  3316. if (repaintEls) {
  3317. for (var j in repaintEls) {
  3318. _currentInstance.anchorManager.redraw(repaintEls[j].id, ui, timestamp, repaintEls[j].offset, clearEdits, true);
  3319. }
  3320. }
  3321. }
  3322. },
  3323. //
  3324. // gets an Endpoint by uuid.
  3325. //
  3326. _getEndpoint = function (uuid) {
  3327. return endpointsByUUID[uuid];
  3328. },
  3329. /**
  3330. * inits a draggable if it's not already initialised.
  3331. * TODO: somehow abstract this to the adapter, because the concept of "draggable" has no
  3332. * place on the server.
  3333. */
  3334. _initDraggableIfNecessary = function (element, isDraggable, dragOptions, id, fireEvent) {
  3335. // move to DragManager?
  3336. if (!jsPlumb.headless) {
  3337. var _draggable = isDraggable == null ? false : isDraggable;
  3338. if (_draggable) {
  3339. if (jsPlumb.isDragSupported(element, _currentInstance)) {
  3340. var options = dragOptions || _currentInstance.Defaults.DragOptions;
  3341. options = jsPlumb.extend({}, options); // make a copy.
  3342. if (!jsPlumb.isAlreadyDraggable(element, _currentInstance)) {
  3343. var dragEvent = jsPlumb.dragEvents.drag,
  3344. stopEvent = jsPlumb.dragEvents.stop,
  3345. startEvent = jsPlumb.dragEvents.start,
  3346. _started = false;
  3347. _manage(id, element);
  3348. options[startEvent] = _ju.wrap(options[startEvent], function () {
  3349. _currentInstance.setHoverSuspended(true);
  3350. _currentInstance.select({source: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
  3351. _currentInstance.select({target: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
  3352. _currentInstance.setConnectionBeingDragged(true);
  3353. if (options.canDrag) return dragOptions.canDrag();
  3354. }, false);
  3355. options[dragEvent] = _ju.wrap(options[dragEvent], function () {
  3356. // TODO: here we could actually use getDragObject, and then compute it ourselves,
  3357. // since every adapter does the same thing. but i'm not sure why YUI's getDragObject
  3358. // differs from getUIPosition so much
  3359. var ui = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom());
  3360. if (ui != null) {
  3361. _draw(element, ui, null, true);
  3362. if (_started) _currentInstance.addClass(element, "jtk-dragged");
  3363. _started = true;
  3364. }
  3365. });
  3366. options[stopEvent] = _ju.wrap(options[stopEvent], function () {
  3367. var elements = arguments[0].selection, uip;
  3368. var _one = function (_e) {
  3369. if (_e[1] != null) {
  3370. // run the reported offset through the code that takes parent containers
  3371. // into account, to adjust if necessary (issue 554)
  3372. uip = _currentInstance.getUIPosition([{
  3373. el:_e[2].el,
  3374. pos:[_e[1].left, _e[1].top]
  3375. }]);
  3376. _draw(_e[2].el, uip);
  3377. }
  3378. _currentInstance.removeClass(_e[0], "jtk-dragged");
  3379. _currentInstance.select({source: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
  3380. _currentInstance.select({target: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
  3381. _currentInstance.getDragManager().dragEnded(_e[2].el);
  3382. };
  3383. for (var i = 0; i < elements.length; i++) {
  3384. _one(elements[i]);
  3385. }
  3386. _started = false;
  3387. _currentInstance.setHoverSuspended(false);
  3388. _currentInstance.setConnectionBeingDragged(false);
  3389. });
  3390. var elId = _getId(element); // need ID
  3391. draggableStates[elId] = true;
  3392. var draggable = draggableStates[elId];
  3393. options.disabled = draggable == null ? false : !draggable;
  3394. _currentInstance.initDraggable(element, options);
  3395. _currentInstance.getDragManager().register(element);
  3396. if (fireEvent) _currentInstance.fire("elementDraggable", {el:element, options:options});
  3397. }
  3398. else {
  3399. // already draggable. attach any start, drag or stop listeners to the current Drag.
  3400. if (dragOptions.force) {
  3401. _currentInstance.initDraggable(element, options);
  3402. }
  3403. }
  3404. }
  3405. }
  3406. }
  3407. },
  3408. _scopeMatch = function (e1, e2) {
  3409. var s1 = e1.scope.split(/\s/), s2 = e2.scope.split(/\s/);
  3410. for (var i = 0; i < s1.length; i++)
  3411. for (var j = 0; j < s2.length; j++)
  3412. if (s2[j] == s1[i]) return true;
  3413. return false;
  3414. },
  3415. /*
  3416. * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc.
  3417. */
  3418. _prepareConnectionParams = function (params, referenceParams) {
  3419. var _p = jsPlumb.extend({ }, params);
  3420. if (referenceParams) jsPlumb.extend(_p, referenceParams);
  3421. // hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively.
  3422. if (_p.source) {
  3423. if (_p.source.endpoint)
  3424. _p.sourceEndpoint = _p.source;
  3425. else
  3426. _p.source = _currentInstance.getElement(_p.source);
  3427. }
  3428. if (_p.target) {
  3429. if (_p.target.endpoint)
  3430. _p.targetEndpoint = _p.target;
  3431. else
  3432. _p.target = _currentInstance.getElement(_p.target);
  3433. }
  3434. // test for endpoint uuids to connect
  3435. if (params.uuids) {
  3436. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  3437. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  3438. }
  3439. // now ensure that if we do have Endpoints already, they're not full.
  3440. // source:
  3441. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  3442. _ju.log(_currentInstance, "could not add connection; source endpoint is full");
  3443. return;
  3444. }
  3445. // target:
  3446. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  3447. _ju.log(_currentInstance, "could not add connection; target endpoint is full");
  3448. return;
  3449. }
  3450. // if source endpoint mandates connection type and nothing specified in our params, use it.
  3451. if (!_p.type && _p.sourceEndpoint)
  3452. _p.type = _p.sourceEndpoint.connectionType;
  3453. // copy in any connectorOverlays that were specified on the source endpoint.
  3454. // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not.
  3455. if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) {
  3456. _p.overlays = _p.overlays || [];
  3457. for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) {
  3458. _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]);
  3459. }
  3460. }
  3461. // scope
  3462. if (_p.sourceEndpoint && _p.sourceEndpoint.scope) {
  3463. _p.scope = _p.sourceEndpoint.scope;
  3464. }
  3465. // pointer events
  3466. if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents)
  3467. _p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents;
  3468. var _mergeOverrides = function (def, values) {
  3469. var m = jsPlumb.extend({}, def);
  3470. for (var i in values) {
  3471. if (values[i]) m[i] = values[i];
  3472. }
  3473. return m;
  3474. };
  3475. var _addEndpoint = function (el, def, idx) {
  3476. return _currentInstance.addEndpoint(el, _mergeOverrides(def, {
  3477. anchor: _p.anchors ? _p.anchors[idx] : _p.anchor,
  3478. endpoint: _p.endpoints ? _p.endpoints[idx] : _p.endpoint,
  3479. paintStyle: _p.endpointStyles ? _p.endpointStyles[idx] : _p.endpointStyle,
  3480. hoverPaintStyle: _p.endpointHoverStyles ? _p.endpointHoverStyles[idx] : _p.endpointHoverStyle
  3481. }));
  3482. };
  3483. // check for makeSource/makeTarget specs.
  3484. var _oneElementDef = function (type, idx, defs, matchType) {
  3485. if (_p[type] && !_p[type].endpoint && !_p[type + "Endpoint"] && !_p.newConnection) {
  3486. var tid = _getId(_p[type]), tep = defs[tid];
  3487. tep = tep ? tep[matchType] : null;
  3488. if (tep) {
  3489. // if not enabled, return.
  3490. if (!tep.enabled) return false;
  3491. var newEndpoint = tep.endpoint != null && tep.endpoint._jsPlumb ? tep.endpoint : _addEndpoint(_p[type], tep.def, idx);
  3492. if (newEndpoint.isFull()) return false;
  3493. _p[type + "Endpoint"] = newEndpoint;
  3494. if (!_p.scope && tep.def.scope) _p.scope = tep.def.scope; // provide scope if not already provided and endpoint def has one.
  3495. newEndpoint.setDeleteOnEmpty(true);
  3496. if (tep.uniqueEndpoint) {
  3497. if (!tep.endpoint) {
  3498. tep.endpoint = newEndpoint;
  3499. newEndpoint.setDeleteOnEmpty(false);
  3500. }
  3501. else
  3502. newEndpoint.finalEndpoint = tep.endpoint;
  3503. }
  3504. }
  3505. }
  3506. };
  3507. if (_oneElementDef("source", 0, this.sourceEndpointDefinitions, _p.type || "default") === false) return;
  3508. if (_oneElementDef("target", 1, this.targetEndpointDefinitions, _p.type || "default") === false) return;
  3509. // last, ensure scopes match
  3510. if (_p.sourceEndpoint && _p.targetEndpoint)
  3511. if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) _p = null;
  3512. return _p;
  3513. }.bind(_currentInstance),
  3514. _newConnection = function (params) {
  3515. var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType();
  3516. params._jsPlumb = _currentInstance;
  3517. params.newConnection = _newConnection;
  3518. params.newEndpoint = _newEndpoint;
  3519. params.endpointsByUUID = endpointsByUUID;
  3520. params.endpointsByElement = endpointsByElement;
  3521. params.finaliseConnection = _finaliseConnection;
  3522. params.id = "con_" + _idstamp();
  3523. var con = new connectionFunc(params);
  3524. // if the connection is draggable, then maybe we need to tell the target endpoint to init the
  3525. // dragging code. it won't run again if it already configured to be draggable.
  3526. if (con.isDetachable()) {
  3527. con.endpoints[0].initDraggable("_jsPlumbSource");
  3528. con.endpoints[1].initDraggable("_jsPlumbTarget");
  3529. }
  3530. return con;
  3531. },
  3532. //
  3533. // adds the connection to the backing model, fires an event if necessary and then redraws
  3534. //
  3535. _finaliseConnection = _currentInstance.finaliseConnection = function (jpc, params, originalEvent, doInformAnchorManager) {
  3536. params = params || {};
  3537. // add to list of connections (by scope).
  3538. if (!jpc.suspendedEndpoint)
  3539. connections.push(jpc);
  3540. jpc.pending = null;
  3541. // turn off isTemporarySource on the source endpoint (only viable on first draw)
  3542. jpc.endpoints[0].isTemporarySource = false;
  3543. // always inform the anchor manager
  3544. // except that if jpc has a suspended endpoint it's not true to say the
  3545. // connection is new; it has just (possibly) moved. the question is whether
  3546. // to make that call here or in the anchor manager. i think perhaps here.
  3547. if (doInformAnchorManager !== false)
  3548. _currentInstance.anchorManager.newConnection(jpc);
  3549. // force a paint
  3550. _draw(jpc.source);
  3551. // fire an event
  3552. if (!params.doNotFireConnectionEvent && params.fireEvent !== false) {
  3553. var eventArgs = {
  3554. connection: jpc,
  3555. source: jpc.source, target: jpc.target,
  3556. sourceId: jpc.sourceId, targetId: jpc.targetId,
  3557. sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
  3558. };
  3559. _currentInstance.fire("connection", eventArgs, originalEvent);
  3560. }
  3561. },
  3562. /*
  3563. factory method to prepare a new endpoint. this should always be used instead of creating Endpoints
  3564. manually, since this method attaches event listeners and an id.
  3565. */
  3566. _newEndpoint = function (params, id) {
  3567. var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint;
  3568. var _p = jsPlumb.extend({}, params);
  3569. _p._jsPlumb = _currentInstance;
  3570. _p.newConnection = _newConnection;
  3571. _p.newEndpoint = _newEndpoint;
  3572. _p.endpointsByUUID = endpointsByUUID;
  3573. _p.endpointsByElement = endpointsByElement;
  3574. _p.fireDetachEvent = fireDetachEvent;
  3575. _p.elementId = id || _getId(_p.source);
  3576. var ep = new endpointFunc(_p);
  3577. ep.id = "ep_" + _idstamp();
  3578. _manage(_p.elementId, _p.source);
  3579. if (!jsPlumb.headless)
  3580. _currentInstance.getDragManager().endpointAdded(_p.source, id);
  3581. return ep;
  3582. },
  3583. /*
  3584. * performs the given function operation on all the connections found
  3585. * for the given element id; this means we find all the endpoints for
  3586. * the given element, and then for each endpoint find the connectors
  3587. * connected to it. then we pass each connection in to the given
  3588. * function.
  3589. */
  3590. _operation = function (elId, func, endpointFunc) {
  3591. var endpoints = endpointsByElement[elId];
  3592. if (endpoints && endpoints.length) {
  3593. for (var i = 0, ii = endpoints.length; i < ii; i++) {
  3594. for (var j = 0, jj = endpoints[i].connections.length; j < jj; j++) {
  3595. var retVal = func(endpoints[i].connections[j]);
  3596. // if the function passed in returns true, we exit.
  3597. // most functions return false.
  3598. if (retVal) return;
  3599. }
  3600. if (endpointFunc) endpointFunc(endpoints[i]);
  3601. }
  3602. }
  3603. },
  3604. _setDraggable = function (element, draggable) {
  3605. return jsPlumb.each(element, function (el) {
  3606. if (_currentInstance.isDragSupported(el)) {
  3607. draggableStates[_currentInstance.getAttribute(el, "id")] = draggable;
  3608. _currentInstance.setElementDraggable(el, draggable);
  3609. }
  3610. });
  3611. },
  3612. /*
  3613. * private method to do the business of hiding/showing.
  3614. *
  3615. * @param el
  3616. * either Id of the element in question or a library specific
  3617. * object for the element.
  3618. * @param state
  3619. * String specifying a value for the css 'display' property
  3620. * ('block' or 'none').
  3621. */
  3622. _setVisible = function (el, state, alsoChangeEndpoints) {
  3623. state = state === "block";
  3624. var endpointFunc = null;
  3625. if (alsoChangeEndpoints) {
  3626. endpointFunc = function (ep) {
  3627. ep.setVisible(state, true, true);
  3628. };
  3629. }
  3630. var info = _info(el);
  3631. _operation(info.id, function (jpc) {
  3632. if (state && alsoChangeEndpoints) {
  3633. // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
  3634. // this block will only set a connection to be visible if the other endpoint in the connection is also visible.
  3635. var oidx = jpc.sourceId === info.id ? 1 : 0;
  3636. if (jpc.endpoints[oidx].isVisible()) jpc.setVisible(true);
  3637. }
  3638. else // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
  3639. jpc.setVisible(state);
  3640. }, endpointFunc);
  3641. },
  3642. /*
  3643. * toggles the draggable state of the given element(s).
  3644. * el is either an id, or an element object, or a list of ids/element objects.
  3645. */
  3646. _toggleDraggable = function (el) {
  3647. var state;
  3648. jsPlumb.each(el, function (el) {
  3649. var elId = _currentInstance.getAttribute(el, "id");
  3650. state = draggableStates[elId] == null ? false : draggableStates[elId];
  3651. state = !state;
  3652. draggableStates[elId] = state;
  3653. _currentInstance.setDraggable(el, state);
  3654. return state;
  3655. }.bind(this));
  3656. return state;
  3657. },
  3658. /**
  3659. * private method to do the business of toggling hiding/showing.
  3660. */
  3661. _toggleVisible = function (elId, changeEndpoints) {
  3662. var endpointFunc = null;
  3663. if (changeEndpoints) {
  3664. endpointFunc = function (ep) {
  3665. var state = ep.isVisible();
  3666. ep.setVisible(!state);
  3667. };
  3668. }
  3669. _operation(elId, function (jpc) {
  3670. var state = jpc.isVisible();
  3671. jpc.setVisible(!state);
  3672. }, endpointFunc);
  3673. },
  3674. // TODO comparison performance
  3675. _getCachedData = function (elId) {
  3676. var o = offsets[elId];
  3677. if (!o)
  3678. return _updateOffset({elId: elId});
  3679. else
  3680. return {o: o, s: sizes[elId]};
  3681. },
  3682. /**
  3683. * gets an id for the given element, creating and setting one if
  3684. * necessary. the id is of the form
  3685. *
  3686. * jsPlumb_<instance index>_<index in instance>
  3687. *
  3688. * where "index in instance" is a monotonically increasing integer that starts at 0,
  3689. * for each instance. this method is used not only to assign ids to elements that do not
  3690. * have them but also to connections and endpoints.
  3691. */
  3692. _getId = function (element, uuid, doNotCreateIfNotFound) {
  3693. if (_ju.isString(element)) return element;
  3694. if (element == null) return null;
  3695. var id = _currentInstance.getAttribute(element, "id");
  3696. if (!id || id === "undefined") {
  3697. // check if fixed uuid parameter is given
  3698. if (arguments.length == 2 && arguments[1] !== undefined)
  3699. id = uuid;
  3700. else if (arguments.length == 1 || (arguments.length == 3 && !arguments[2]))
  3701. id = "jsPlumb_" + _instanceIndex + "_" + _idstamp();
  3702. if (!doNotCreateIfNotFound) _currentInstance.setAttribute(element, "id", id);
  3703. }
  3704. return id;
  3705. };
  3706. this.setConnectionBeingDragged = function (v) {
  3707. connectionBeingDragged = v;
  3708. };
  3709. this.isConnectionBeingDragged = function () {
  3710. return connectionBeingDragged;
  3711. };
  3712. /**
  3713. * Returns a map of all the elements this jsPlumbInstance is currently managing.
  3714. * @returns {Object} Map of [id-> {el, endpoint[], connection, position}] information.
  3715. */
  3716. this.getManagedElements = function() {
  3717. return managedElements;
  3718. };
  3719. this.connectorClass = "jtk-connector";
  3720. this.connectorOutlineClass = "jtk-connector-outline";
  3721. this.editableConnectorClass = "jtk-connector-editable";
  3722. this.connectedClass = "jtk-connected";
  3723. this.hoverClass = "jtk-hover";
  3724. this.endpointClass = "jtk-endpoint";
  3725. this.endpointConnectedClass = "jtk-endpoint-connected";
  3726. this.endpointFullClass = "jtk-endpoint-full";
  3727. this.endpointDropAllowedClass = "jtk-endpoint-drop-allowed";
  3728. this.endpointDropForbiddenClass = "jtk-endpoint-drop-forbidden";
  3729. this.overlayClass = "jtk-overlay";
  3730. this.draggingClass = "jtk-dragging";
  3731. this.elementDraggingClass = "jtk-element-dragging";
  3732. this.sourceElementDraggingClass = "jtk-source-element-dragging";
  3733. this.targetElementDraggingClass = "jtk-target-element-dragging";
  3734. this.endpointAnchorClassPrefix = "jtk-endpoint-anchor";
  3735. this.hoverSourceClass = "jtk-source-hover";
  3736. this.hoverTargetClass = "jtk-target-hover";
  3737. this.dragSelectClass = "jtk-drag-select";
  3738. this.Anchors = {};
  3739. this.Connectors = { "svg": {} };
  3740. this.Endpoints = { "svg": {} };
  3741. this.Overlays = { "svg": {} } ;
  3742. this.ConnectorRenderers = {};
  3743. this.SVG = "svg";
  3744. // --------------------------- jsPlumbInstance public API ---------------------------------------------------------
  3745. this.addEndpoint = function (el, params, referenceParams) {
  3746. referenceParams = referenceParams || {};
  3747. var p = jsPlumb.extend({}, referenceParams);
  3748. jsPlumb.extend(p, params);
  3749. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint;
  3750. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle;
  3751. var results = [],
  3752. inputs = (_ju.isArray(el) || (el.length != null && !_ju.isString(el))) ? el : [ el ];
  3753. for (var i = 0, j = inputs.length; i < j; i++) {
  3754. p.source = _currentInstance.getElement(inputs[i]);
  3755. _ensureContainer(p.source);
  3756. var id = _getId(p.source), e = _newEndpoint(p, id);
  3757. // ensure element is managed.
  3758. var myOffset = _manage(id, p.source).info.o;
  3759. _ju.addToList(endpointsByElement, id, e);
  3760. if (!_suspendDrawing) {
  3761. e.paint({
  3762. anchorLoc: e.anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: sizes[id], element: e, timestamp: _suspendedAt }),
  3763. timestamp: _suspendedAt
  3764. });
  3765. }
  3766. results.push(e);
  3767. }
  3768. return results.length == 1 ? results[0] : results;
  3769. };
  3770. this.addEndpoints = function (el, endpoints, referenceParams) {
  3771. var results = [];
  3772. for (var i = 0, j = endpoints.length; i < j; i++) {
  3773. var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
  3774. if (_ju.isArray(e))
  3775. Array.prototype.push.apply(results, e);
  3776. else results.push(e);
  3777. }
  3778. return results;
  3779. };
  3780. this.animate = function (el, properties, options) {
  3781. if (!this.animationSupported) return false;
  3782. options = options || {};
  3783. var del = _currentInstance.getElement(el),
  3784. id = _getId(del),
  3785. stepFunction = jsPlumb.animEvents.step,
  3786. completeFunction = jsPlumb.animEvents.complete;
  3787. options[stepFunction] = _ju.wrap(options[stepFunction], function () {
  3788. _currentInstance.revalidate(id);
  3789. });
  3790. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  3791. options[completeFunction] = _ju.wrap(options[completeFunction], function () {
  3792. _currentInstance.revalidate(id);
  3793. });
  3794. _currentInstance.doAnimate(del, properties, options);
  3795. };
  3796. /**
  3797. * checks for a listener for the given condition, executing it if found, passing in the given value.
  3798. * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since
  3799. * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition"
  3800. * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these
  3801. * condition events anyway.
  3802. */
  3803. this.checkCondition = function (conditionName, args) {
  3804. var l = _currentInstance.getListener(conditionName),
  3805. r = true;
  3806. if (l && l.length > 0) {
  3807. var values = Array.prototype.slice.call(arguments, 1);
  3808. try {
  3809. for (var i = 0, j = l.length; i < j; i++) {
  3810. r = r && l[i].apply(l[i], values);
  3811. }
  3812. }
  3813. catch (e) {
  3814. _ju.log(_currentInstance, "cannot check condition [" + conditionName + "]" + e);
  3815. }
  3816. }
  3817. return r;
  3818. };
  3819. this.connect = function (params, referenceParams) {
  3820. // prepare a final set of parameters to create connection with
  3821. var _p = _prepareConnectionParams(params, referenceParams), jpc;
  3822. // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams
  3823. // will return null (and log something) if either endpoint was full. what would be nicer is to
  3824. // create a dedicated 'error' object.
  3825. if (_p) {
  3826. if (_p.source == null && _p.sourceEndpoint == null) {
  3827. _ju.log("Cannot establish connection - source does not exist");
  3828. return;
  3829. }
  3830. if (_p.target == null && _p.targetEndpoint == null) {
  3831. _ju.log("Cannot establish connection - target does not exist");
  3832. return;
  3833. }
  3834. _ensureContainer(_p.source);
  3835. // create the connection. it is not yet registered
  3836. jpc = _newConnection(_p);
  3837. // now add it the model, fire an event, and redraw
  3838. _finaliseConnection(jpc, _p);
  3839. }
  3840. return jpc;
  3841. };
  3842. var stTypes = [
  3843. { el: "source", elId: "sourceId", epDefs: "sourceEndpointDefinitions" },
  3844. { el: "target", elId: "targetId", epDefs: "targetEndpointDefinitions" }
  3845. ];
  3846. var _set = function (c, el, idx, doNotRepaint) {
  3847. var ep, _st = stTypes[idx], cId = c[_st.elId], cEl = c[_st.el], sid, sep,
  3848. oldEndpoint = c.endpoints[idx];
  3849. var evtParams = {
  3850. index: idx,
  3851. originalSourceId: idx === 0 ? cId : c.sourceId,
  3852. newSourceId: c.sourceId,
  3853. originalTargetId: idx == 1 ? cId : c.targetId,
  3854. newTargetId: c.targetId,
  3855. connection: c
  3856. };
  3857. if (el.constructor == jsPlumb.Endpoint) {
  3858. ep = el;
  3859. ep.addConnection(c);
  3860. el = ep.element;
  3861. }
  3862. else {
  3863. sid = _getId(el);
  3864. sep = this[_st.epDefs][sid];
  3865. if (sid === c[_st.elId])
  3866. ep = null; // dont change source/target if the element is already the one given.
  3867. else if (sep) {
  3868. for (var t in sep) {
  3869. if (!sep[t].enabled) return;
  3870. ep = sep[t].endpoint != null && sep[t].endpoint._jsPlumb ? sep[t].endpoint : this.addEndpoint(el, sep[t].def);
  3871. if (sep[t].uniqueEndpoint) {
  3872. sep[t].endpoint = ep;
  3873. }
  3874. ep.addConnection(c);
  3875. }
  3876. }
  3877. else {
  3878. ep = c.makeEndpoint(idx === 0, el, sid);
  3879. }
  3880. }
  3881. if (ep != null) {
  3882. oldEndpoint.detachFromConnection(c);
  3883. c.endpoints[idx] = ep;
  3884. c[_st.el] = ep.element;
  3885. c[_st.elId] = ep.elementId;
  3886. evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId;
  3887. fireMoveEvent(evtParams);
  3888. if (!doNotRepaint) {
  3889. c.repaint();
  3890. }
  3891. }
  3892. evtParams.element = el;
  3893. return evtParams;
  3894. }.bind(this);
  3895. this.setSource = function (connection, el, doNotRepaint) {
  3896. var p = _set(connection, el, 0, doNotRepaint);
  3897. this.anchorManager.sourceChanged(p.originalSourceId, p.newSourceId, connection, p.el);
  3898. };
  3899. this.setTarget = function (connection, el, doNotRepaint) {
  3900. var p = _set(connection, el, 1, doNotRepaint);
  3901. this.anchorManager.updateOtherEndpoint(p.originalSourceId, p.originalTargetId, p.newTargetId, connection);
  3902. };
  3903. this.deleteEndpoint = function (object, dontUpdateHover, deleteAttachedObjects) {
  3904. var endpoint = (typeof object === "string") ? endpointsByUUID[object] : object;
  3905. if (endpoint) {
  3906. _currentInstance.deleteObject({ endpoint: endpoint, dontUpdateHover: dontUpdateHover, deleteAttachedObjects:deleteAttachedObjects });
  3907. }
  3908. return _currentInstance;
  3909. };
  3910. this.deleteEveryEndpoint = function () {
  3911. var _is = _currentInstance.setSuspendDrawing(true);
  3912. for (var id in endpointsByElement) {
  3913. var endpoints = endpointsByElement[id];
  3914. if (endpoints && endpoints.length) {
  3915. for (var i = 0, j = endpoints.length; i < j; i++) {
  3916. _currentInstance.deleteEndpoint(endpoints[i], true);
  3917. }
  3918. }
  3919. }
  3920. endpointsByElement = {};
  3921. managedElements = {};
  3922. endpointsByUUID = {};
  3923. offsets = {};
  3924. offsetTimestamps = {};
  3925. _currentInstance.anchorManager.reset();
  3926. var dm = _currentInstance.getDragManager();
  3927. if (dm) {
  3928. dm.reset();
  3929. }
  3930. if (!_is) {
  3931. _currentInstance.setSuspendDrawing(false);
  3932. }
  3933. return _currentInstance;
  3934. };
  3935. var fireDetachEvent = function (jpc, doFireEvent, originalEvent) {
  3936. // may have been given a connection, or in special cases, an object
  3937. var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
  3938. argIsConnection = jpc.constructor == connType,
  3939. params = argIsConnection ? {
  3940. connection: jpc,
  3941. source: jpc.source, target: jpc.target,
  3942. sourceId: jpc.sourceId, targetId: jpc.targetId,
  3943. sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
  3944. } : jpc;
  3945. if (doFireEvent) {
  3946. _currentInstance.fire("connectionDetached", params, originalEvent);
  3947. }
  3948. // always fire this. used by internal jsplumb stuff.
  3949. _currentInstance.fire("internal.connectionDetached", params, originalEvent);
  3950. _currentInstance.anchorManager.connectionDetached(params);
  3951. };
  3952. var fireMoveEvent = _currentInstance.fireMoveEvent = function (params, evt) {
  3953. _currentInstance.fire("connectionMoved", params, evt);
  3954. };
  3955. this.unregisterEndpoint = function (endpoint) {
  3956. if (endpoint._jsPlumb.uuid) {
  3957. endpointsByUUID[endpoint._jsPlumb.uuid] = null;
  3958. }
  3959. _currentInstance.anchorManager.deleteEndpoint(endpoint);
  3960. // TODO at least replace this with a removeWithFunction call.
  3961. for (var e in endpointsByElement) {
  3962. var endpoints = endpointsByElement[e];
  3963. if (endpoints) {
  3964. var newEndpoints = [];
  3965. for (var i = 0, j = endpoints.length; i < j; i++)
  3966. if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
  3967. endpointsByElement[e] = newEndpoints;
  3968. }
  3969. if (endpointsByElement[e].length < 1) {
  3970. delete endpointsByElement[e];
  3971. }
  3972. }
  3973. };
  3974. var IS_DETACH_ALLOWED = "isDetachAllowed";
  3975. var BEFORE_DETACH = "beforeDetach";
  3976. var CHECK_CONDITION = "checkCondition";
  3977. /**
  3978. * Deletes a Connection.
  3979. * @method deleteConnection
  3980. * @param connection Connection to delete
  3981. * @param {Object} [params] Optional delete parameters
  3982. * @param {Boolean} [params.doNotFireEvent=false] If true, a connection detached event will not be fired. Otherwise one will.
  3983. * @param {Boolean} [params.force=false] If true, the connection will be deleted even if a beforeDetach interceptor tries to stop the deletion.
  3984. * @returns {Boolean} True if the connection was deleted, false otherwise.
  3985. */
  3986. this.deleteConnection = function(connection, params) {
  3987. if (connection != null) {
  3988. params = params || {};
  3989. if (params.force || _ju.functionChain(true, false, [
  3990. [ connection.endpoints[0], IS_DETACH_ALLOWED, [ connection ] ],
  3991. [ connection.endpoints[1], IS_DETACH_ALLOWED, [ connection ] ],
  3992. [ connection, IS_DETACH_ALLOWED, [ connection ] ],
  3993. [ _currentInstance, CHECK_CONDITION, [ BEFORE_DETACH, connection ] ]
  3994. ])) {
  3995. connection.setHover(false);
  3996. fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent);
  3997. connection.endpoints[0].detachFromConnection(connection);
  3998. connection.endpoints[1].detachFromConnection(connection);
  3999. _ju.removeWithFunction(connections, function (_c) {
  4000. return connection.id == _c.id;
  4001. });
  4002. connection.cleanup();
  4003. connection.destroy();
  4004. return true;
  4005. }
  4006. }
  4007. return false;
  4008. };
  4009. /**
  4010. * Remove all Connections from all elements, but leaves Endpoints in place ((unless a connection is set to auto delete its Endpoints).
  4011. * @method deleteEveryConnection
  4012. * @param {Object} [params] optional params object for the call
  4013. * @param {Boolean} [params.fireEvent=true] Whether or not to fire detach events
  4014. * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
  4015. * @returns {Number} The number of connections that were deleted.
  4016. */
  4017. this.deleteEveryConnection = function (params) {
  4018. params = params || {};
  4019. var count = connections.length, deletedCount = 0;
  4020. _currentInstance.batch(function () {
  4021. for (var i = 0; i < count; i++) {
  4022. deletedCount += _currentInstance.deleteConnection(connections[0], params) ? 1 : 0;
  4023. }
  4024. });
  4025. return deletedCount;
  4026. };
  4027. /**
  4028. * Removes all an element's Connections.
  4029. * @method deleteConnectionsForElement
  4030. * @param {Object} el Either the id of the element, or a selector for the element.
  4031. * @param {Object} [params] Optional parameters.
  4032. * @param {Boolean} [params.fireEvent=true] Whether or not to fire the detach event.
  4033. * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
  4034. * @return {jsPlumbInstance} The current jsPlumb instance.
  4035. */
  4036. this.deleteConnectionsForElement = function (el, params) {
  4037. params = params || {};
  4038. el = _currentInstance.getElement(el);
  4039. var id = _getId(el), endpoints = endpointsByElement[id];
  4040. if (endpoints && endpoints.length) {
  4041. for (var i = 0, j = endpoints.length; i < j; i++) {
  4042. endpoints[i].deleteEveryConnection(params);
  4043. }
  4044. }
  4045. return _currentInstance;
  4046. };
  4047. /// not public. but of course its exposed. how to change this.
  4048. this.deleteObject = function (params) {
  4049. var result = {
  4050. endpoints: {},
  4051. connections: {},
  4052. endpointCount: 0,
  4053. connectionCount: 0
  4054. },
  4055. deleteAttachedObjects = params.deleteAttachedObjects !== false;
  4056. var unravelConnection = function (connection) {
  4057. if (connection != null && result.connections[connection.id] == null) {
  4058. if (!params.dontUpdateHover && connection._jsPlumb != null) connection.setHover(false);
  4059. result.connections[connection.id] = connection;
  4060. result.connectionCount++;
  4061. if (deleteAttachedObjects) {
  4062. for (var j = 0; j < connection.endpoints.length; j++) {
  4063. // if (connection.endpoints[j]._deleteOnDetach)
  4064. // unravelEndpoint(connection.endpoints[j]);
  4065. }
  4066. }
  4067. }
  4068. };
  4069. var unravelEndpoint = function (endpoint) {
  4070. if (endpoint != null && result.endpoints[endpoint.id] == null) {
  4071. if (!params.dontUpdateHover && endpoint._jsPlumb != null) endpoint.setHover(false);
  4072. result.endpoints[endpoint.id] = endpoint;
  4073. result.endpointCount++;
  4074. if (deleteAttachedObjects) {
  4075. for (var i = 0; i < endpoint.connections.length; i++) {
  4076. var c = endpoint.connections[i];
  4077. unravelConnection(c);
  4078. }
  4079. }
  4080. }
  4081. };
  4082. if (params.connection)
  4083. unravelConnection(params.connection);
  4084. else unravelEndpoint(params.endpoint);
  4085. // loop through connections
  4086. for (var i in result.connections) {
  4087. var c = result.connections[i];
  4088. if (c._jsPlumb) {
  4089. _ju.removeWithFunction(connections, function (_c) {
  4090. return c.id == _c.id;
  4091. });
  4092. fireDetachEvent(c, params.fireEvent === false ? false : !c.pending, params.originalEvent);
  4093. var doNotCleanup = params.deleteAttachedObjects == null ? null : !params.deleteAttachedObjects;
  4094. c.endpoints[0].detachFromConnection(c, null, doNotCleanup);
  4095. c.endpoints[1].detachFromConnection(c, null, doNotCleanup);
  4096. c.cleanup(true);
  4097. c.destroy(true);
  4098. }
  4099. }
  4100. // loop through endpoints
  4101. for (var j in result.endpoints) {
  4102. var e = result.endpoints[j];
  4103. if (e._jsPlumb) {
  4104. _currentInstance.unregisterEndpoint(e);
  4105. // FIRE some endpoint deleted event?
  4106. e.cleanup(true);
  4107. e.destroy(true);
  4108. }
  4109. }
  4110. return result;
  4111. };
  4112. this.draggable = function (el, options) {
  4113. var info;
  4114. _each(function(_el) {
  4115. info = _info(_el);
  4116. if (info.el) _initDraggableIfNecessary(info.el, true, options, info.id, true);
  4117. }, el);
  4118. return _currentInstance;
  4119. };
  4120. this.droppable = function(el, options) {
  4121. var info;
  4122. options = options || {};
  4123. options.allowLoopback = false;
  4124. _each(function(_el) {
  4125. info = _info(_el);
  4126. if (info.el) _currentInstance.initDroppable(info.el, options);
  4127. }, el);
  4128. return _currentInstance;
  4129. };
  4130. // helpers for select/selectEndpoints
  4131. var _setOperation = function (list, func, args, selector) {
  4132. for (var i = 0, j = list.length; i < j; i++) {
  4133. list[i][func].apply(list[i], args);
  4134. }
  4135. return selector(list);
  4136. },
  4137. _getOperation = function (list, func, args) {
  4138. var out = [];
  4139. for (var i = 0, j = list.length; i < j; i++) {
  4140. out.push([ list[i][func].apply(list[i], args), list[i] ]);
  4141. }
  4142. return out;
  4143. },
  4144. setter = function (list, func, selector) {
  4145. return function () {
  4146. return _setOperation(list, func, arguments, selector);
  4147. };
  4148. },
  4149. getter = function (list, func) {
  4150. return function () {
  4151. return _getOperation(list, func, arguments);
  4152. };
  4153. },
  4154. prepareList = function (input, doNotGetIds) {
  4155. var r = [];
  4156. if (input) {
  4157. if (typeof input == 'string') {
  4158. if (input === "*") return input;
  4159. r.push(input);
  4160. }
  4161. else {
  4162. if (doNotGetIds) r = input;
  4163. else {
  4164. if (input.length) {
  4165. for (var i = 0, j = input.length; i < j; i++)
  4166. r.push(_info(input[i]).id);
  4167. }
  4168. else
  4169. r.push(_info(input).id);
  4170. }
  4171. }
  4172. }
  4173. return r;
  4174. },
  4175. filterList = function (list, value, missingIsFalse) {
  4176. if (list === "*") return true;
  4177. return list.length > 0 ? list.indexOf(value) != -1 : !missingIsFalse;
  4178. };
  4179. // get some connections, specifying source/target/scope
  4180. this.getConnections = function (options, flat) {
  4181. if (!options) {
  4182. options = {};
  4183. } else if (options.constructor == String) {
  4184. options = { "scope": options };
  4185. }
  4186. var scope = options.scope || _currentInstance.getDefaultScope(),
  4187. scopes = prepareList(scope, true),
  4188. sources = prepareList(options.source),
  4189. targets = prepareList(options.target),
  4190. results = (!flat && scopes.length > 1) ? {} : [],
  4191. _addOne = function (scope, obj) {
  4192. if (!flat && scopes.length > 1) {
  4193. var ss = results[scope];
  4194. if (ss == null) {
  4195. ss = results[scope] = [];
  4196. }
  4197. ss.push(obj);
  4198. } else results.push(obj);
  4199. };
  4200. for (var j = 0, jj = connections.length; j < jj; j++) {
  4201. var c = connections[j],
  4202. sourceId = c.proxies && c.proxies[0] ? c.proxies[0].originalEp.elementId : c.sourceId,
  4203. targetId = c.proxies && c.proxies[1] ? c.proxies[1].originalEp.elementId : c.targetId;
  4204. if (filterList(scopes, c.scope) && filterList(sources, sourceId) && filterList(targets, targetId))
  4205. _addOne(c.scope, c);
  4206. }
  4207. return results;
  4208. };
  4209. var _curryEach = function (list, executor) {
  4210. return function (f) {
  4211. for (var i = 0, ii = list.length; i < ii; i++) {
  4212. f(list[i]);
  4213. }
  4214. return executor(list);
  4215. };
  4216. },
  4217. _curryGet = function (list) {
  4218. return function (idx) {
  4219. return list[idx];
  4220. };
  4221. };
  4222. var _makeCommonSelectHandler = function (list, executor) {
  4223. var out = {
  4224. length: list.length,
  4225. each: _curryEach(list, executor),
  4226. get: _curryGet(list)
  4227. },
  4228. setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay",
  4229. "removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle",
  4230. "setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible",
  4231. "repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ],
  4232. getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle",
  4233. "getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ],
  4234. i, ii;
  4235. for (i = 0, ii = setters.length; i < ii; i++)
  4236. out[setters[i]] = setter(list, setters[i], executor);
  4237. for (i = 0, ii = getters.length; i < ii; i++)
  4238. out[getters[i]] = getter(list, getters[i]);
  4239. return out;
  4240. };
  4241. var _makeConnectionSelectHandler = function (list) {
  4242. var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler);
  4243. return jsPlumb.extend(common, {
  4244. // setters
  4245. setDetachable: setter(list, "setDetachable", _makeConnectionSelectHandler),
  4246. setReattach: setter(list, "setReattach", _makeConnectionSelectHandler),
  4247. setConnector: setter(list, "setConnector", _makeConnectionSelectHandler),
  4248. delete: function () {
  4249. for (var i = 0, ii = list.length; i < ii; i++)
  4250. _currentInstance.deleteConnection(list[i]);
  4251. },
  4252. // getters
  4253. isDetachable: getter(list, "isDetachable"),
  4254. isReattach: getter(list, "isReattach")
  4255. });
  4256. };
  4257. var _makeEndpointSelectHandler = function (list) {
  4258. var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler);
  4259. return jsPlumb.extend(common, {
  4260. setEnabled: setter(list, "setEnabled", _makeEndpointSelectHandler),
  4261. setAnchor: setter(list, "setAnchor", _makeEndpointSelectHandler),
  4262. isEnabled: getter(list, "isEnabled"),
  4263. deleteEveryConnection: function () {
  4264. for (var i = 0, ii = list.length; i < ii; i++)
  4265. list[i].deleteEveryConnection();
  4266. },
  4267. "delete": function () {
  4268. for (var i = 0, ii = list.length; i < ii; i++)
  4269. _currentInstance.deleteEndpoint(list[i]);
  4270. }
  4271. });
  4272. };
  4273. this.select = function (params) {
  4274. params = params || {};
  4275. params.scope = params.scope || "*";
  4276. return _makeConnectionSelectHandler(params.connections || _currentInstance.getConnections(params, true));
  4277. };
  4278. this.selectEndpoints = function (params) {
  4279. params = params || {};
  4280. params.scope = params.scope || "*";
  4281. var noElementFilters = !params.element && !params.source && !params.target,
  4282. elements = noElementFilters ? "*" : prepareList(params.element),
  4283. sources = noElementFilters ? "*" : prepareList(params.source),
  4284. targets = noElementFilters ? "*" : prepareList(params.target),
  4285. scopes = prepareList(params.scope, true);
  4286. var ep = [];
  4287. for (var el in endpointsByElement) {
  4288. var either = filterList(elements, el, true),
  4289. source = filterList(sources, el, true),
  4290. sourceMatchExact = sources != "*",
  4291. target = filterList(targets, el, true),
  4292. targetMatchExact = targets != "*";
  4293. // 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.
  4294. if (either || source || target) {
  4295. inner:
  4296. for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) {
  4297. var _ep = endpointsByElement[el][i];
  4298. if (filterList(scopes, _ep.scope, true)) {
  4299. var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource),
  4300. noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget);
  4301. if (noMatchSource || noMatchTarget)
  4302. continue inner;
  4303. ep.push(_ep);
  4304. }
  4305. }
  4306. }
  4307. }
  4308. return _makeEndpointSelectHandler(ep);
  4309. };
  4310. // get all connections managed by the instance of jsplumb.
  4311. this.getAllConnections = function () {
  4312. return connections;
  4313. };
  4314. this.getDefaultScope = function () {
  4315. return DEFAULT_SCOPE;
  4316. };
  4317. // get an endpoint by uuid.
  4318. this.getEndpoint = _getEndpoint;
  4319. /**
  4320. * Gets the list of Endpoints for a given element.
  4321. * @method getEndpoints
  4322. * @param {String|Element|Selector} el The element to get endpoints for.
  4323. * @return {Endpoint[]} An array of Endpoints for the specified element.
  4324. */
  4325. this.getEndpoints = function (el) {
  4326. return endpointsByElement[_info(el).id] || [];
  4327. };
  4328. // gets the default endpoint type. used when subclassing. see wiki.
  4329. this.getDefaultEndpointType = function () {
  4330. return jsPlumb.Endpoint;
  4331. };
  4332. // gets the default connection type. used when subclassing. see wiki.
  4333. this.getDefaultConnectionType = function () {
  4334. return jsPlumb.Connection;
  4335. };
  4336. /*
  4337. * Gets an element's id, creating one if necessary. really only exposed
  4338. * for the lib-specific functionality to access; would be better to pass
  4339. * the current instance into the lib-specific code (even though this is
  4340. * a static call. i just don't want to expose it to the public API).
  4341. */
  4342. this.getId = _getId;
  4343. this.appendElement = _appendElement;
  4344. var _hoverSuspended = false;
  4345. this.isHoverSuspended = function () {
  4346. return _hoverSuspended;
  4347. };
  4348. this.setHoverSuspended = function (s) {
  4349. _hoverSuspended = s;
  4350. };
  4351. // set an element's connections to be hidden
  4352. this.hide = function (el, changeEndpoints) {
  4353. _setVisible(el, "none", changeEndpoints);
  4354. return _currentInstance;
  4355. };
  4356. // exposed for other objects to use to get a unique id.
  4357. this.idstamp = _idstamp;
  4358. this.connectorsInitialized = false;
  4359. this.registerConnectorType = function (connector, name) {
  4360. connectorTypes.push([connector, name]);
  4361. };
  4362. // ensure that, if the current container exists, it is a DOM element and not a selector.
  4363. // if it does not exist and `candidate` is supplied, the offset parent of that element will be set as the Container.
  4364. // this is used to do a better default behaviour for the case that the user has not set a container:
  4365. // addEndpoint, makeSource, makeTarget and connect all call this method with the offsetParent of the
  4366. // element in question (for connect it is the source element). So if no container is set, it is inferred
  4367. // to be the offsetParent of the first element the user tries to connect.
  4368. var _ensureContainer = function (candidate) {
  4369. if (!_container && candidate) {
  4370. var can = _currentInstance.getElement(candidate);
  4371. if (can.offsetParent) _currentInstance.setContainer(can.offsetParent);
  4372. }
  4373. };
  4374. var _getContainerFromDefaults = function () {
  4375. if (_currentInstance.Defaults.Container)
  4376. _currentInstance.setContainer(_currentInstance.Defaults.Container);
  4377. };
  4378. // check if a given element is managed or not. if not, add to our map. if drawing is not suspended then
  4379. // we'll also stash its dimensions; otherwise we'll do this in a lazy way through updateOffset.
  4380. var _manage = _currentInstance.manage = function (id, element, _transient) {
  4381. if (!managedElements[id]) {
  4382. managedElements[id] = {
  4383. el: element,
  4384. endpoints: [],
  4385. connections: []
  4386. };
  4387. managedElements[id].info = _updateOffset({ elId: id, timestamp: _suspendedAt });
  4388. if (!_transient) {
  4389. _currentInstance.fire("manageElement", { id:id, info:managedElements[id].info, el:element });
  4390. }
  4391. }
  4392. return managedElements[id];
  4393. };
  4394. var _unmanage = function(id) {
  4395. if (managedElements[id]) {
  4396. delete managedElements[id];
  4397. _currentInstance.fire("unmanageElement", id);
  4398. }
  4399. };
  4400. /**
  4401. * updates the offset and size for a given element, and stores the
  4402. * values. if 'offset' is not null we use that (it would have been
  4403. * passed in from a drag call) because it's faster; but if it is null,
  4404. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  4405. */
  4406. var _updateOffset = this.updateOffset = function (params) {
  4407. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId, s;
  4408. if (_suspendDrawing && !timestamp) timestamp = _suspendedAt;
  4409. if (!recalc) {
  4410. if (timestamp && timestamp === offsetTimestamps[elId]) {
  4411. return {o: params.offset || offsets[elId], s: sizes[elId]};
  4412. }
  4413. }
  4414. if (recalc || (!offset && offsets[elId] == null)) { // if forced repaint or no offset available, we recalculate.
  4415. // get the current size and offset, and store them
  4416. s = managedElements[elId] ? managedElements[elId].el : null;
  4417. if (s != null) {
  4418. sizes[elId] = _currentInstance.getSize(s);
  4419. offsets[elId] = _currentInstance.getOffset(s);
  4420. offsetTimestamps[elId] = timestamp;
  4421. }
  4422. } else {
  4423. offsets[elId] = offset || offsets[elId];
  4424. if (sizes[elId] == null) {
  4425. s = managedElements[elId].el;
  4426. if (s != null) sizes[elId] = _currentInstance.getSize(s);
  4427. }
  4428. offsetTimestamps[elId] = timestamp;
  4429. }
  4430. if (offsets[elId] && !offsets[elId].right) {
  4431. offsets[elId].right = offsets[elId].left + sizes[elId][0];
  4432. offsets[elId].bottom = offsets[elId].top + sizes[elId][1];
  4433. offsets[elId].width = sizes[elId][0];
  4434. offsets[elId].height = sizes[elId][1];
  4435. offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2);
  4436. offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2);
  4437. }
  4438. return {o: offsets[elId], s: sizes[elId]};
  4439. };
  4440. /**
  4441. * callback from the current library to tell us to prepare ourselves (attach
  4442. * mouse listeners etc; can't do that until the library has provided a bind method)
  4443. */
  4444. this.init = function () {
  4445. rendererTypes = root.jsPlumb.getRenderModes();
  4446. var _oneType = function (renderer, name, fn) {
  4447. root.jsPlumb.Connectors[renderer][name] = function () {
  4448. fn.apply(this, arguments);
  4449. root.jsPlumb.ConnectorRenderers[renderer].apply(this, arguments);
  4450. };
  4451. _ju.extend(root.jsPlumb.Connectors[renderer][name], [ fn, root.jsPlumb.ConnectorRenderers[renderer]]);
  4452. };
  4453. if (!root.jsPlumb.connectorsInitialized) {
  4454. for (var i = 0; i < connectorTypes.length; i++) {
  4455. for (var j = 0; j < rendererTypes.length; j++) {
  4456. _oneType(rendererTypes[j], connectorTypes[i][1], connectorTypes[i][0]);
  4457. }
  4458. }
  4459. root.jsPlumb.connectorsInitialized = true;
  4460. }
  4461. if (!initialized) {
  4462. _getContainerFromDefaults();
  4463. _currentInstance.anchorManager = new root.jsPlumb.AnchorManager({jsPlumbInstance: _currentInstance});
  4464. initialized = true;
  4465. _currentInstance.fire("ready", _currentInstance);
  4466. }
  4467. }.bind(this);
  4468. this.log = log;
  4469. this.jsPlumbUIComponent = jsPlumbUIComponent;
  4470. /*
  4471. * Creates an anchor with the given params.
  4472. *
  4473. *
  4474. * Returns: The newly created Anchor.
  4475. * Throws: an error if a named anchor was not found.
  4476. */
  4477. this.makeAnchor = function () {
  4478. var pp, _a = function (t, p) {
  4479. if (root.jsPlumb.Anchors[t]) return new root.jsPlumb.Anchors[t](p);
  4480. if (!_currentInstance.Defaults.DoNotThrowErrors)
  4481. throw { msg: "jsPlumb: unknown anchor type '" + t + "'" };
  4482. };
  4483. if (arguments.length === 0) return null;
  4484. var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null;
  4485. // if it appears to be an anchor already...
  4486. if (specimen.compute && specimen.getOrientation) return specimen; //TODO hazy here about whether it should be added or is already added somehow.
  4487. // is it the name of an anchor type?
  4488. else if (typeof specimen == "string") {
  4489. newAnchor = _a(arguments[0], {elementId: elementId, jsPlumbInstance: _currentInstance});
  4490. }
  4491. // is it an array? it will be one of:
  4492. // an array of [spec, params] - this defines a single anchor, which may be dynamic, but has parameters.
  4493. // an array of arrays - this defines some dynamic anchors
  4494. // an array of numbers - this defines a single anchor.
  4495. else if (_ju.isArray(specimen)) {
  4496. if (_ju.isArray(specimen[0]) || _ju.isString(specimen[0])) {
  4497. // if [spec, params] format
  4498. if (specimen.length == 2 && _ju.isObject(specimen[1])) {
  4499. // if first arg is a string, its a named anchor with params
  4500. if (_ju.isString(specimen[0])) {
  4501. pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance}, specimen[1]);
  4502. newAnchor = _a(specimen[0], pp);
  4503. }
  4504. // otherwise first arg is array, second is params. we treat as a dynamic anchor, which is fine
  4505. // even if the first arg has only one entry. you could argue all anchors should be implicitly dynamic in fact.
  4506. else {
  4507. pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance, anchors: specimen[0]}, specimen[1]);
  4508. newAnchor = new root.jsPlumb.DynamicAnchor(pp);
  4509. }
  4510. }
  4511. else
  4512. newAnchor = new jsPlumb.DynamicAnchor({anchors: specimen, selector: null, elementId: elementId, jsPlumbInstance: _currentInstance});
  4513. }
  4514. else {
  4515. var anchorParams = {
  4516. x: specimen[0], y: specimen[1],
  4517. orientation: (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0, 0],
  4518. offsets: (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ],
  4519. elementId: elementId,
  4520. jsPlumbInstance: _currentInstance,
  4521. cssClass: specimen.length == 7 ? specimen[6] : null
  4522. };
  4523. newAnchor = new root.jsPlumb.Anchor(anchorParams);
  4524. newAnchor.clone = function () {
  4525. return new root.jsPlumb.Anchor(anchorParams);
  4526. };
  4527. }
  4528. }
  4529. if (!newAnchor.id) newAnchor.id = "anchor_" + _idstamp();
  4530. return newAnchor;
  4531. };
  4532. /**
  4533. * makes a list of anchors from the given list of types or coords, eg
  4534. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  4535. */
  4536. this.makeAnchors = function (types, elementId, jsPlumbInstance) {
  4537. var r = [];
  4538. for (var i = 0, ii = types.length; i < ii; i++) {
  4539. if (typeof types[i] == "string")
  4540. r.push(root.jsPlumb.Anchors[types[i]]({elementId: elementId, jsPlumbInstance: jsPlumbInstance}));
  4541. else if (_ju.isArray(types[i]))
  4542. r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance));
  4543. }
  4544. return r;
  4545. };
  4546. /**
  4547. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  4548. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  4549. * not need to provide this - i think).
  4550. */
  4551. this.makeDynamicAnchor = function (anchors, anchorSelector) {
  4552. return new root.jsPlumb.DynamicAnchor({anchors: anchors, selector: anchorSelector, elementId: null, jsPlumbInstance: _currentInstance});
  4553. };
  4554. // --------------------- makeSource/makeTarget ----------------------------------------------
  4555. this.targetEndpointDefinitions = {};
  4556. this.sourceEndpointDefinitions = {};
  4557. var selectorFilter = function (evt, _el, selector, _instance, negate) {
  4558. var t = evt.target || evt.srcElement, ok = false,
  4559. sel = _instance.getSelector(_el, selector);
  4560. for (var j = 0; j < sel.length; j++) {
  4561. if (sel[j] == t) {
  4562. ok = true;
  4563. break;
  4564. }
  4565. }
  4566. return negate ? !ok : ok;
  4567. };
  4568. var _makeElementDropHandler = function (elInfo, p, dropOptions, isSource, isTarget) {
  4569. var proxyComponent = new jsPlumbUIComponent(p);
  4570. var _drop = p._jsPlumb.EndpointDropHandler({
  4571. jsPlumb: _currentInstance,
  4572. enabled: function () {
  4573. return elInfo.def.enabled;
  4574. },
  4575. isFull: function () {
  4576. var targetCount = _currentInstance.select({target: elInfo.id}).length;
  4577. return elInfo.def.maxConnections > 0 && targetCount >= elInfo.def.maxConnections;
  4578. },
  4579. element: elInfo.el,
  4580. elementId: elInfo.id,
  4581. isSource: isSource,
  4582. isTarget: isTarget,
  4583. addClass: function (clazz) {
  4584. _currentInstance.addClass(elInfo.el, clazz);
  4585. },
  4586. removeClass: function (clazz) {
  4587. _currentInstance.removeClass(elInfo.el, clazz);
  4588. },
  4589. onDrop: function (jpc) {
  4590. var source = jpc.endpoints[0];
  4591. source.anchor.locked = false;
  4592. },
  4593. isDropAllowed: function () {
  4594. return proxyComponent.isDropAllowed.apply(proxyComponent, arguments);
  4595. },
  4596. isRedrop:function(jpc) {
  4597. return (jpc.suspendedElement != null && jpc.suspendedEndpoint != null && jpc.suspendedEndpoint.element === elInfo.el);
  4598. },
  4599. getEndpoint: function (jpc) {
  4600. // make a new Endpoint for the target, or get it from the cache if uniqueEndpoint
  4601. // is set. if its a redrop the new endpoint will be immediately cleaned up.
  4602. var newEndpoint = elInfo.def.endpoint;
  4603. // if no cached endpoint, or there was one but it has been cleaned up
  4604. // (ie. detached), create a new one
  4605. if (newEndpoint == null || newEndpoint._jsPlumb == null) {
  4606. var eps = _currentInstance.deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true);
  4607. var pp = eps.endpoints ? root.jsPlumb.extend(p, {
  4608. endpoint:elInfo.def.def.endpoint || eps.endpoints[1]
  4609. }) :p;
  4610. if (eps.anchors) {
  4611. pp = root.jsPlumb.extend(pp, {
  4612. anchor:elInfo.def.def.anchor || eps.anchors[1]
  4613. });
  4614. }
  4615. newEndpoint = _currentInstance.addEndpoint(elInfo.el, pp);
  4616. newEndpoint._mtNew = true;
  4617. }
  4618. if (p.uniqueEndpoint) {
  4619. elInfo.def.endpoint = newEndpoint;
  4620. }
  4621. newEndpoint.setDeleteOnEmpty(true);
  4622. // if connection is detachable, init the new endpoint to be draggable, to support that happening.
  4623. if (jpc.isDetachable())
  4624. newEndpoint.initDraggable();
  4625. // if the anchor has a 'positionFinder' set, then delegate to that function to find
  4626. // out where to locate the anchor.
  4627. if (newEndpoint.anchor.positionFinder != null) {
  4628. var dropPosition = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()),
  4629. elPosition = _currentInstance.getOffset(elInfo.el),
  4630. elSize = _currentInstance.getSize(elInfo.el),
  4631. ap = dropPosition == null ? [0,0] : newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams);
  4632. newEndpoint.anchor.x = ap[0];
  4633. newEndpoint.anchor.y = ap[1];
  4634. // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to
  4635. // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation
  4636. // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be
  4637. // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which
  4638. // the target is furthest away from the source.
  4639. }
  4640. return newEndpoint;
  4641. },
  4642. maybeCleanup: function (ep) {
  4643. if (ep._mtNew && ep.connections.length === 0) {
  4644. _currentInstance.deleteObject({endpoint: ep});
  4645. }
  4646. else
  4647. delete ep._mtNew;
  4648. }
  4649. });
  4650. // wrap drop events as needed and initialise droppable
  4651. var dropEvent = root.jsPlumb.dragEvents.drop;
  4652. dropOptions.scope = dropOptions.scope || (p.scope || _currentInstance.Defaults.Scope);
  4653. dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], _drop, true);
  4654. // if target, return true from the over event. this will cause katavorio to stop setting drops to hover
  4655. // if multipleDrop is set to false.
  4656. if (isTarget) {
  4657. dropOptions[root.jsPlumb.dragEvents.over] = function () { return true; };
  4658. }
  4659. // vanilla jsplumb only
  4660. if (p.allowLoopback === false) {
  4661. dropOptions.canDrop = function (_drag) {
  4662. var de = _drag.getDragElement()._jsPlumbRelatedElement;
  4663. return de != elInfo.el;
  4664. };
  4665. }
  4666. _currentInstance.initDroppable(elInfo.el, dropOptions, "internal");
  4667. return _drop;
  4668. };
  4669. // see API docs
  4670. this.makeTarget = function (el, params, referenceParams) {
  4671. // put jsplumb ref into params without altering the params passed in
  4672. var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
  4673. root.jsPlumb.extend(p, params);
  4674. var maxConnections = p.maxConnections || -1,
  4675. _doOne = function (el) {
  4676. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  4677. // and use the endpoint definition if found.
  4678. // decode the info for this element (id and element)
  4679. var elInfo = _info(el),
  4680. elid = elInfo.id,
  4681. dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}),
  4682. type = p.connectionType || "default";
  4683. this.targetEndpointDefinitions[elid] = this.targetEndpointDefinitions[elid] || {};
  4684. _ensureContainer(elid);
  4685. // if this is a group and the user has not mandated a rank, set to -1 so that Nodes takes
  4686. // precedence.
  4687. if (elInfo.el._isJsPlumbGroup && dropOptions.rank == null) {
  4688. dropOptions.rank = -1;
  4689. }
  4690. // store the definition
  4691. var _def = {
  4692. def: root.jsPlumb.extend({}, p),
  4693. uniqueEndpoint: p.uniqueEndpoint,
  4694. maxConnections: maxConnections,
  4695. enabled: true
  4696. };
  4697. elInfo.def = _def;
  4698. this.targetEndpointDefinitions[elid][type] = _def;
  4699. _makeElementDropHandler(elInfo, p, dropOptions, p.isSource === true, true);
  4700. // stash the definition on the drop
  4701. elInfo.el._katavorioDrop[elInfo.el._katavorioDrop.length - 1].targetDef = _def;
  4702. }.bind(this);
  4703. // make an array if only given one element
  4704. var inputs = el.length && el.constructor != String ? el : [ el ];
  4705. // register each one in the list.
  4706. for (var i = 0, ii = inputs.length; i < ii; i++) {
  4707. _doOne(inputs[i]);
  4708. }
  4709. return this;
  4710. };
  4711. // see api docs
  4712. this.unmakeTarget = function (el, doNotClearArrays) {
  4713. var info = _info(el);
  4714. _currentInstance.destroyDroppable(info.el, "internal");
  4715. if (!doNotClearArrays) {
  4716. delete this.targetEndpointDefinitions[info.id];
  4717. }
  4718. return this;
  4719. };
  4720. // see api docs
  4721. this.makeSource = function (el, params, referenceParams) {
  4722. var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
  4723. root.jsPlumb.extend(p, params);
  4724. var type = p.connectionType || "default";
  4725. var aae = _currentInstance.deriveEndpointAndAnchorSpec(type);
  4726. p.endpoint = p.endpoint || aae.endpoints[0];
  4727. p.anchor = p.anchor || aae.anchors[0];
  4728. var maxConnections = p.maxConnections || -1,
  4729. onMaxConnections = p.onMaxConnections,
  4730. _doOne = function (elInfo) {
  4731. // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
  4732. // and use the endpoint definition if found.
  4733. var elid = elInfo.id,
  4734. _del = this.getElement(elInfo.el);
  4735. this.sourceEndpointDefinitions[elid] = this.sourceEndpointDefinitions[elid] || {};
  4736. _ensureContainer(elid);
  4737. var _def = {
  4738. def:root.jsPlumb.extend({}, p),
  4739. uniqueEndpoint: p.uniqueEndpoint,
  4740. maxConnections: maxConnections,
  4741. enabled: true
  4742. };
  4743. this.sourceEndpointDefinitions[elid][type] = _def;
  4744. elInfo.def = _def;
  4745. var stopEvent = root.jsPlumb.dragEvents.stop,
  4746. dragEvent = root.jsPlumb.dragEvents.drag,
  4747. dragOptions = root.jsPlumb.extend({ }, p.dragOptions || {}),
  4748. existingDrag = dragOptions.drag,
  4749. existingStop = dragOptions.stop,
  4750. ep = null,
  4751. endpointAddedButNoDragYet = false;
  4752. // set scope if its not set in dragOptions but was passed in in params
  4753. dragOptions.scope = dragOptions.scope || p.scope;
  4754. dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], function () {
  4755. if (existingDrag) existingDrag.apply(this, arguments);
  4756. endpointAddedButNoDragYet = false;
  4757. });
  4758. dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], function () {
  4759. if (existingStop) existingStop.apply(this, arguments);
  4760. this.currentlyDragging = false;
  4761. if (ep._jsPlumb != null) { // if not cleaned up...
  4762. // reset the anchor to the anchor that was initially provided. the one we were using to drag
  4763. // the connection was just a placeholder that was located at the place the user pressed the
  4764. // mouse button to initiate the drag.
  4765. var anchorDef = p.anchor || this.Defaults.Anchor,
  4766. oldAnchor = ep.anchor,
  4767. oldConnection = ep.connections[0];
  4768. var newAnchor = this.makeAnchor(anchorDef, elid, this),
  4769. _el = ep.element;
  4770. // if the anchor has a 'positionFinder' set, then delegate to that function to find
  4771. // out where to locate the anchor. issue 117.
  4772. if (newAnchor.positionFinder != null) {
  4773. var elPosition = _currentInstance.getOffset(_el),
  4774. elSize = this.getSize(_el),
  4775. dropPosition = { left: elPosition.left + (oldAnchor.x * elSize[0]), top: elPosition.top + (oldAnchor.y * elSize[1]) },
  4776. ap = newAnchor.positionFinder(dropPosition, elPosition, elSize, newAnchor.constructorParams);
  4777. newAnchor.x = ap[0];
  4778. newAnchor.y = ap[1];
  4779. }
  4780. ep.setAnchor(newAnchor, true);
  4781. ep.repaint();
  4782. this.repaint(ep.elementId);
  4783. if (oldConnection != null) this.repaint(oldConnection.targetId);
  4784. }
  4785. }.bind(this));
  4786. // when the user presses the mouse, add an Endpoint, if we are enabled.
  4787. var mouseDownListener = function (e) {
  4788. // on right mouse button, abort.
  4789. if (e.which === 3 || e.button === 2) return;
  4790. // TODO store def on element.
  4791. var def = this.sourceEndpointDefinitions[elid][type];
  4792. // if disabled, return.
  4793. if (!def.enabled) return;
  4794. elid = this.getId(this.getElement(elInfo.el)); // elid might have changed since this method was called to configure the element.
  4795. // if a filter was given, run it, and return if it says no.
  4796. if (p.filter) {
  4797. var r = _ju.isString(p.filter) ? selectorFilter(e, elInfo.el, p.filter, this, p.filterExclude) : p.filter(e, elInfo.el);
  4798. if (r === false) return;
  4799. }
  4800. // if maxConnections reached
  4801. var sourceCount = this.select({source: elid}).length;
  4802. if (def.maxConnections >= 0 && (sourceCount >= def.maxConnections)) {
  4803. if (onMaxConnections) {
  4804. onMaxConnections({
  4805. element: elInfo.el,
  4806. maxConnections: maxConnections
  4807. }, e);
  4808. }
  4809. return false;
  4810. }
  4811. // find the position on the element at which the mouse was pressed; this is where the endpoint
  4812. // will be located.
  4813. var elxy = root.jsPlumb.getPositionOnElement(e, _del, _zoom);
  4814. // we need to override the anchor in here, and force 'isSource', but we don't want to mess with
  4815. // the params passed in, because after a connection is established we're going to reset the endpoint
  4816. // to have the anchor we were given.
  4817. var tempEndpointParams = {};
  4818. root.jsPlumb.extend(tempEndpointParams, p);
  4819. tempEndpointParams.isTemporarySource = true;
  4820. tempEndpointParams.anchor = [ elxy[0], elxy[1] , 0, 0];
  4821. tempEndpointParams.dragOptions = dragOptions;
  4822. if (def.def.scope) tempEndpointParams.scope = def.def.scope;
  4823. ep = this.addEndpoint(elid, tempEndpointParams);
  4824. endpointAddedButNoDragYet = true;
  4825. ep.setDeleteOnEmpty(true);
  4826. // if unique endpoint and it's already been created, push it onto the endpoint we create. at the end
  4827. // of a successful connection we'll switch to that endpoint.
  4828. // TODO this is the same code as the programmatic endpoints create on line 1050 ish
  4829. if (def.uniqueEndpoint) {
  4830. if (!def.endpoint) {
  4831. def.endpoint = ep;
  4832. ep.setDeleteOnEmpty(false);
  4833. }
  4834. else
  4835. ep.finalEndpoint = def.endpoint;
  4836. }
  4837. var _delTempEndpoint = function () {
  4838. // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools
  4839. // it is fired even if dragging has occurred, in which case we would blow away a perfectly
  4840. // legitimate endpoint, were it not for this check. the flag is set after adding an
  4841. // endpoint and cleared in a drag listener we set in the dragOptions above.
  4842. _currentInstance.off(ep.canvas, "mouseup", _delTempEndpoint);
  4843. _currentInstance.off(elInfo.el, "mouseup", _delTempEndpoint);
  4844. if (endpointAddedButNoDragYet) {
  4845. endpointAddedButNoDragYet = false;
  4846. _currentInstance.deleteEndpoint(ep);
  4847. }
  4848. };
  4849. _currentInstance.on(ep.canvas, "mouseup", _delTempEndpoint);
  4850. _currentInstance.on(elInfo.el, "mouseup", _delTempEndpoint);
  4851. // optionally check for attributes to extract from the source element
  4852. var payload = {};
  4853. if (def.def.extract) {
  4854. for (var att in def.def.extract) {
  4855. var v = (e.srcElement || e.target).getAttribute(att);
  4856. if (v) {
  4857. payload[def.def.extract[att]] = v;
  4858. }
  4859. }
  4860. }
  4861. // and then trigger its mousedown event, which will kick off a drag, which will start dragging
  4862. // a new connection from this endpoint.
  4863. _currentInstance.trigger(ep.canvas, "mousedown", e, payload);
  4864. _ju.consume(e);
  4865. }.bind(this);
  4866. this.on(elInfo.el, "mousedown", mouseDownListener);
  4867. _def.trigger = mouseDownListener;
  4868. // if a filter was provided, set it as a dragFilter on the element,
  4869. // to prevent the element drag function from kicking in when we want to
  4870. // drag a new connection
  4871. if (p.filter && (_ju.isString(p.filter) || _ju.isFunction(p.filter))) {
  4872. _currentInstance.setDragFilter(elInfo.el, p.filter);
  4873. }
  4874. var dropOptions = root.jsPlumb.extend({}, p.dropOptions || {});
  4875. _makeElementDropHandler(elInfo, p, dropOptions, true, p.isTarget === true);
  4876. }.bind(this);
  4877. var inputs = el.length && el.constructor != String ? el : [ el ];
  4878. for (var i = 0, ii = inputs.length; i < ii; i++) {
  4879. _doOne(_info(inputs[i]));
  4880. }
  4881. return this;
  4882. };
  4883. // see api docs
  4884. this.unmakeSource = function (el, connectionType, doNotClearArrays) {
  4885. var info = _info(el);
  4886. _currentInstance.destroyDroppable(info.el, "internal");
  4887. var eldefs = this.sourceEndpointDefinitions[info.id];
  4888. if (eldefs) {
  4889. for (var def in eldefs) {
  4890. if (connectionType == null || connectionType === def) {
  4891. var mouseDownListener = eldefs[def].trigger;
  4892. if (mouseDownListener)
  4893. _currentInstance.off(info.el, "mousedown", mouseDownListener);
  4894. if (!doNotClearArrays) {
  4895. delete this.sourceEndpointDefinitions[info.id][def];
  4896. }
  4897. }
  4898. }
  4899. }
  4900. return this;
  4901. };
  4902. // see api docs
  4903. this.unmakeEverySource = function () {
  4904. for (var i in this.sourceEndpointDefinitions)
  4905. _currentInstance.unmakeSource(i, null, true);
  4906. this.sourceEndpointDefinitions = {};
  4907. return this;
  4908. };
  4909. var _getScope = function (el, types, connectionType) {
  4910. types = _ju.isArray(types) ? types : [ types ];
  4911. var id = _getId(el);
  4912. connectionType = connectionType || "default";
  4913. for (var i = 0; i < types.length; i++) {
  4914. var eldefs = this[types[i]][id];
  4915. if (eldefs && eldefs[connectionType]) return eldefs[connectionType].def.scope || this.Defaults.Scope;
  4916. }
  4917. }.bind(this);
  4918. var _setScope = function (el, scope, types, connectionType) {
  4919. types = _ju.isArray(types) ? types : [ types ];
  4920. var id = _getId(el);
  4921. connectionType = connectionType || "default";
  4922. for (var i = 0; i < types.length; i++) {
  4923. var eldefs = this[types[i]][id];
  4924. if (eldefs && eldefs[connectionType]) {
  4925. eldefs[connectionType].def.scope = scope;
  4926. }
  4927. }
  4928. }.bind(this);
  4929. this.getScope = function (el, scope) {
  4930. return _getScope(el, [ "sourceEndpointDefinitions", "targetEndpointDefinitions" ]);
  4931. };
  4932. this.getSourceScope = function (el) {
  4933. return _getScope(el, "sourceEndpointDefinitions");
  4934. };
  4935. this.getTargetScope = function (el) {
  4936. return _getScope(el, "targetEndpointDefinitions");
  4937. };
  4938. this.setScope = function (el, scope, connectionType) {
  4939. this.setSourceScope(el, scope, connectionType);
  4940. this.setTargetScope(el, scope, connectionType);
  4941. };
  4942. this.setSourceScope = function (el, scope, connectionType) {
  4943. _setScope(el, scope, "sourceEndpointDefinitions", connectionType);
  4944. // we get the source scope during the mousedown event, but we also want to set this.
  4945. this.setDragScope(el, scope);
  4946. };
  4947. this.setTargetScope = function (el, scope, connectionType) {
  4948. _setScope(el, scope, "targetEndpointDefinitions", connectionType);
  4949. this.setDropScope(el, scope);
  4950. };
  4951. // see api docs
  4952. this.unmakeEveryTarget = function () {
  4953. for (var i in this.targetEndpointDefinitions)
  4954. _currentInstance.unmakeTarget(i, true);
  4955. this.targetEndpointDefinitions = {};
  4956. return this;
  4957. };
  4958. // does the work of setting a source enabled or disabled.
  4959. var _setEnabled = function (type, el, state, toggle, connectionType) {
  4960. var a = type == "source" ? this.sourceEndpointDefinitions : this.targetEndpointDefinitions,
  4961. originalState, info, newState;
  4962. connectionType = connectionType || "default";
  4963. // a selector or an array
  4964. if (el.length && !_ju.isString(el)) {
  4965. originalState = [];
  4966. for (var i = 0, ii = el.length; i < ii; i++) {
  4967. info = _info(el[i]);
  4968. if (a[info.id] && a[info.id][connectionType]) {
  4969. originalState[i] = a[info.id][connectionType].enabled;
  4970. newState = toggle ? !originalState[i] : state;
  4971. a[info.id][connectionType].enabled = newState;
  4972. _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
  4973. }
  4974. }
  4975. }
  4976. // otherwise a DOM element or a String ID.
  4977. else {
  4978. info = _info(el);
  4979. var id = info.id;
  4980. if (a[id] && a[id][connectionType]) {
  4981. originalState = a[id][connectionType].enabled;
  4982. newState = toggle ? !originalState : state;
  4983. a[id][connectionType].enabled = newState;
  4984. _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
  4985. }
  4986. }
  4987. return originalState;
  4988. }.bind(this);
  4989. var _first = function (el, fn) {
  4990. if (_ju.isString(el) || !el.length)
  4991. return fn.apply(this, [ el ]);
  4992. else if (el.length)
  4993. return fn.apply(this, [ el[0] ]);
  4994. }.bind(this);
  4995. this.toggleSourceEnabled = function (el, connectionType) {
  4996. _setEnabled("source", el, null, true, connectionType);
  4997. return this.isSourceEnabled(el, connectionType);
  4998. };
  4999. this.setSourceEnabled = function (el, state, connectionType) {
  5000. return _setEnabled("source", el, state, null, connectionType);
  5001. };
  5002. this.isSource = function (el, connectionType) {
  5003. connectionType = connectionType || "default";
  5004. return _first(el, function (_el) {
  5005. var eldefs = this.sourceEndpointDefinitions[_info(_el).id];
  5006. return eldefs != null && eldefs[connectionType] != null;
  5007. }.bind(this));
  5008. };
  5009. this.isSourceEnabled = function (el, connectionType) {
  5010. connectionType = connectionType || "default";
  5011. return _first(el, function (_el) {
  5012. var sep = this.sourceEndpointDefinitions[_info(_el).id];
  5013. return sep && sep[connectionType] && sep[connectionType].enabled === true;
  5014. }.bind(this));
  5015. };
  5016. this.toggleTargetEnabled = function (el, connectionType) {
  5017. _setEnabled("target", el, null, true, connectionType);
  5018. return this.isTargetEnabled(el, connectionType);
  5019. };
  5020. this.isTarget = function (el, connectionType) {
  5021. connectionType = connectionType || "default";
  5022. return _first(el, function (_el) {
  5023. var eldefs = this.targetEndpointDefinitions[_info(_el).id];
  5024. return eldefs != null && eldefs[connectionType] != null;
  5025. }.bind(this));
  5026. };
  5027. this.isTargetEnabled = function (el, connectionType) {
  5028. connectionType = connectionType || "default";
  5029. return _first(el, function (_el) {
  5030. var tep = this.targetEndpointDefinitions[_info(_el).id];
  5031. return tep && tep[connectionType] && tep[connectionType].enabled === true;
  5032. }.bind(this));
  5033. };
  5034. this.setTargetEnabled = function (el, state, connectionType) {
  5035. return _setEnabled("target", el, state, null, connectionType);
  5036. };
  5037. // --------------------- end makeSource/makeTarget ----------------------------------------------
  5038. this.ready = function (fn) {
  5039. _currentInstance.bind("ready", fn);
  5040. };
  5041. var _elEach = function(el, fn) {
  5042. // support both lists...
  5043. if (typeof el == 'object' && el.length)
  5044. for (var i = 0, ii = el.length; i < ii; i++) {
  5045. fn(el[i]);
  5046. }
  5047. else // ...and single strings or elements.
  5048. fn(el);
  5049. return _currentInstance;
  5050. };
  5051. // repaint some element's endpoints and connections
  5052. this.repaint = function (el, ui, timestamp) {
  5053. return _elEach(el, function(_el) {
  5054. _draw(_el, ui, timestamp);
  5055. });
  5056. };
  5057. this.revalidate = function (el, timestamp, isIdAlready) {
  5058. return _elEach(el, function(_el) {
  5059. var elId = isIdAlready ? _el : _currentInstance.getId(_el);
  5060. _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp:timestamp });
  5061. var dm = _currentInstance.getDragManager();
  5062. if (dm) {
  5063. dm.updateOffsets(elId);
  5064. }
  5065. _currentInstance.repaint(_el);
  5066. });
  5067. };
  5068. // repaint every endpoint and connection.
  5069. this.repaintEverything = function () {
  5070. // TODO this timestamp causes continuous anchors to not repaint properly.
  5071. // fix this. do not just take out the timestamp. it runs a lot faster with
  5072. // the timestamp included.
  5073. var timestamp = _timestamp(), elId;
  5074. for (elId in endpointsByElement) {
  5075. _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp: timestamp });
  5076. }
  5077. for (elId in endpointsByElement) {
  5078. _draw(elId, null, timestamp);
  5079. }
  5080. return this;
  5081. };
  5082. this.removeAllEndpoints = function (el, recurse, affectedElements) {
  5083. affectedElements = affectedElements || [];
  5084. var _one = function (_el) {
  5085. var info = _info(_el),
  5086. ebe = endpointsByElement[info.id],
  5087. i, ii;
  5088. if (ebe) {
  5089. affectedElements.push(info);
  5090. for (i = 0, ii = ebe.length; i < ii; i++)
  5091. _currentInstance.deleteEndpoint(ebe[i], false);
  5092. }
  5093. delete endpointsByElement[info.id];
  5094. if (recurse) {
  5095. if (info.el && info.el.nodeType != 3 && info.el.nodeType != 8) {
  5096. for (i = 0, ii = info.el.childNodes.length; i < ii; i++) {
  5097. _one(info.el.childNodes[i]);
  5098. }
  5099. }
  5100. }
  5101. };
  5102. _one(el);
  5103. return this;
  5104. };
  5105. var _doRemove = function(info, affectedElements) {
  5106. _currentInstance.removeAllEndpoints(info.id, true, affectedElements);
  5107. var dm = _currentInstance.getDragManager();
  5108. var _one = function(_info) {
  5109. if (dm) {
  5110. dm.elementRemoved(_info.id);
  5111. }
  5112. _currentInstance.anchorManager.clearFor(_info.id);
  5113. _currentInstance.anchorManager.removeFloatingConnection(_info.id);
  5114. if (_currentInstance.isSource(_info.el)) _currentInstance.unmakeSource(_info.el);
  5115. if (_currentInstance.isTarget(_info.el)) _currentInstance.unmakeTarget(_info.el);
  5116. _currentInstance.destroyDraggable(_info.el);
  5117. _currentInstance.destroyDroppable(_info.el);
  5118. delete _currentInstance.floatingConnections[_info.id];
  5119. delete managedElements[_info.id];
  5120. delete offsets[_info.id];
  5121. if (_info.el) {
  5122. _currentInstance.removeElement(_info.el);
  5123. _info.el._jsPlumb = null;
  5124. }
  5125. };
  5126. // remove all affected child elements
  5127. for (var ae = 1; ae < affectedElements.length; ae++) {
  5128. _one(affectedElements[ae]);
  5129. }
  5130. // and always remove the requested one from the dom.
  5131. _one(info);
  5132. };
  5133. /**
  5134. * Remove the given element, including cleaning up all endpoints registered for it.
  5135. * This is exposed in the public API but also used internally by jsPlumb when removing the
  5136. * element associated with a connection drag.
  5137. */
  5138. this.remove = function (el, doNotRepaint) {
  5139. var info = _info(el), affectedElements = [];
  5140. if (info.text) {
  5141. info.el.parentNode.removeChild(info.el);
  5142. }
  5143. else if (info.id) {
  5144. _currentInstance.batch(function () {
  5145. _doRemove(info, affectedElements);
  5146. }, doNotRepaint === false);
  5147. }
  5148. return _currentInstance;
  5149. };
  5150. this.empty = function (el, doNotRepaint) {
  5151. var affectedElements = [];
  5152. var _one = function(el, dontRemoveFocus) {
  5153. var info = _info(el);
  5154. if (info.text) {
  5155. info.el.parentNode.removeChild(info.el);
  5156. }
  5157. else if (info.el) {
  5158. while(info.el.childNodes.length > 0) {
  5159. _one(info.el.childNodes[0]);
  5160. }
  5161. if (!dontRemoveFocus) _doRemove(info, affectedElements);
  5162. }
  5163. };
  5164. _currentInstance.batch(function() {
  5165. _one(el, true);
  5166. }, doNotRepaint === false);
  5167. return _currentInstance;
  5168. };
  5169. this.reset = function () {
  5170. _currentInstance.silently(function() {
  5171. _hoverSuspended = false;
  5172. _currentInstance.removeAllGroups();
  5173. _currentInstance.removeGroupManager();
  5174. _currentInstance.deleteEveryEndpoint();
  5175. _currentInstance.unbind();
  5176. this.targetEndpointDefinitions = {};
  5177. this.sourceEndpointDefinitions = {};
  5178. connections.length = 0;
  5179. if (this.doReset) this.doReset();
  5180. }.bind(this));
  5181. };
  5182. var _clearObject = function (obj) {
  5183. if (obj.canvas && obj.canvas.parentNode)
  5184. obj.canvas.parentNode.removeChild(obj.canvas);
  5185. obj.cleanup();
  5186. obj.destroy();
  5187. };
  5188. this.clear = function () {
  5189. _currentInstance.select().each(_clearObject);
  5190. _currentInstance.selectEndpoints().each(_clearObject);
  5191. endpointsByElement = {};
  5192. endpointsByUUID = {};
  5193. };
  5194. this.setDefaultScope = function (scope) {
  5195. DEFAULT_SCOPE = scope;
  5196. return _currentInstance;
  5197. };
  5198. // sets whether or not some element should be currently draggable.
  5199. this.setDraggable = _setDraggable;
  5200. this.deriveEndpointAndAnchorSpec = function(type, dontPrependDefault) {
  5201. var bits = ((dontPrependDefault ? "" : "default ") + type).split(/[\s]/), eps = null, ep = null, a = null, as = null;
  5202. for (var i = 0; i < bits.length; i++) {
  5203. var _t = _currentInstance.getType(bits[i], "connection");
  5204. if (_t) {
  5205. if (_t.endpoints) eps = _t.endpoints;
  5206. if (_t.endpoint) ep = _t.endpoint;
  5207. if (_t.anchors) as = _t.anchors;
  5208. if (_t.anchor) a = _t.anchor;
  5209. }
  5210. }
  5211. return { endpoints: eps ? eps : [ ep, ep ], anchors: as ? as : [a, a ]};
  5212. };
  5213. // sets the id of some element, changing whatever we need to to keep track.
  5214. this.setId = function (el, newId, doNotSetAttribute) {
  5215. //
  5216. var id;
  5217. if (_ju.isString(el)) {
  5218. id = el;
  5219. }
  5220. else {
  5221. el = this.getElement(el);
  5222. id = this.getId(el);
  5223. }
  5224. var sConns = this.getConnections({source: id, scope: '*'}, true),
  5225. tConns = this.getConnections({target: id, scope: '*'}, true);
  5226. newId = "" + newId;
  5227. if (!doNotSetAttribute) {
  5228. el = this.getElement(id);
  5229. this.setAttribute(el, "id", newId);
  5230. }
  5231. else
  5232. el = this.getElement(newId);
  5233. endpointsByElement[newId] = endpointsByElement[id] || [];
  5234. for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) {
  5235. endpointsByElement[newId][i].setElementId(newId);
  5236. endpointsByElement[newId][i].setReferenceElement(el);
  5237. }
  5238. delete endpointsByElement[id];
  5239. this.sourceEndpointDefinitions[newId] = this.sourceEndpointDefinitions[id];
  5240. delete this.sourceEndpointDefinitions[id];
  5241. this.targetEndpointDefinitions[newId] = this.targetEndpointDefinitions[id];
  5242. delete this.targetEndpointDefinitions[id];
  5243. this.anchorManager.changeId(id, newId);
  5244. var dm = this.getDragManager();
  5245. if (dm) {
  5246. dm.changeId(id, newId);
  5247. }
  5248. managedElements[newId] = managedElements[id];
  5249. delete managedElements[id];
  5250. var _conns = function (list, epIdx, type) {
  5251. for (var i = 0, ii = list.length; i < ii; i++) {
  5252. list[i].endpoints[epIdx].setElementId(newId);
  5253. list[i].endpoints[epIdx].setReferenceElement(el);
  5254. list[i][type + "Id"] = newId;
  5255. list[i][type] = el;
  5256. }
  5257. };
  5258. _conns(sConns, 0, "source");
  5259. _conns(tConns, 1, "target");
  5260. this.repaint(newId);
  5261. };
  5262. this.setDebugLog = function (debugLog) {
  5263. log = debugLog;
  5264. };
  5265. this.setSuspendDrawing = function (val, repaintAfterwards) {
  5266. var curVal = _suspendDrawing;
  5267. _suspendDrawing = val;
  5268. if (val) _suspendedAt = new Date().getTime(); else _suspendedAt = null;
  5269. if (repaintAfterwards) this.repaintEverything();
  5270. return curVal;
  5271. };
  5272. // returns whether or not drawing is currently suspended.
  5273. this.isSuspendDrawing = function () {
  5274. return _suspendDrawing;
  5275. };
  5276. // return timestamp for when drawing was suspended.
  5277. this.getSuspendedAt = function () {
  5278. return _suspendedAt;
  5279. };
  5280. this.batch = function (fn, doNotRepaintAfterwards) {
  5281. var _wasSuspended = this.isSuspendDrawing();
  5282. if (!_wasSuspended)
  5283. this.setSuspendDrawing(true);
  5284. try {
  5285. fn();
  5286. }
  5287. catch (e) {
  5288. _ju.log("Function run while suspended failed", e);
  5289. }
  5290. if (!_wasSuspended)
  5291. this.setSuspendDrawing(false, !doNotRepaintAfterwards);
  5292. };
  5293. this.doWhileSuspended = this.batch;
  5294. this.getCachedData = _getCachedData;
  5295. this.timestamp = _timestamp;
  5296. this.show = function (el, changeEndpoints) {
  5297. _setVisible(el, "block", changeEndpoints);
  5298. return _currentInstance;
  5299. };
  5300. // TODO: update this method to return the current state.
  5301. this.toggleVisible = _toggleVisible;
  5302. this.toggleDraggable = _toggleDraggable;
  5303. this.addListener = this.bind;
  5304. };
  5305. _ju.extend(root.jsPlumbInstance, _ju.EventGenerator, {
  5306. setAttribute: function (el, a, v) {
  5307. this.setAttribute(el, a, v);
  5308. },
  5309. getAttribute: function (el, a) {
  5310. return this.getAttribute(root.jsPlumb.getElement(el), a);
  5311. },
  5312. convertToFullOverlaySpec: function(spec) {
  5313. if (_ju.isString(spec)) {
  5314. spec = [ spec, { } ];
  5315. }
  5316. spec[1].id = spec[1].id || _ju.uuid();
  5317. return spec;
  5318. },
  5319. registerConnectionType: function (id, type) {
  5320. this._connectionTypes[id] = root.jsPlumb.extend({}, type);
  5321. if (type.overlays) {
  5322. var to = {};
  5323. for (var i = 0; i < type.overlays.length; i++) {
  5324. // if a string, convert to object representation so that we can store the typeid on it.
  5325. // also assign an id.
  5326. var fo = this.convertToFullOverlaySpec(type.overlays[i]);
  5327. to[fo[1].id] = fo;
  5328. }
  5329. this._connectionTypes[id].overlays = to;
  5330. }
  5331. },
  5332. registerConnectionTypes: function (types) {
  5333. for (var i in types)
  5334. this.registerConnectionType(i, types[i]);
  5335. },
  5336. registerEndpointType: function (id, type) {
  5337. this._endpointTypes[id] = root.jsPlumb.extend({}, type);
  5338. if (type.overlays) {
  5339. var to = {};
  5340. for (var i = 0; i < type.overlays.length; i++) {
  5341. // if a string, convert to object representation so that we can store the typeid on it.
  5342. // also assign an id.
  5343. var fo = this.convertToFullOverlaySpec(type.overlays[i]);
  5344. to[fo[1].id] = fo;
  5345. }
  5346. this._endpointTypes[id].overlays = to;
  5347. }
  5348. },
  5349. registerEndpointTypes: function (types) {
  5350. for (var i in types)
  5351. //this._endpointTypes[i] = jsPlumb.extend({}, types[i]);
  5352. this.registerEndpointType(i, types[i]);
  5353. },
  5354. getType: function (id, typeDescriptor) {
  5355. return typeDescriptor === "connection" ? this._connectionTypes[id] : this._endpointTypes[id];
  5356. },
  5357. setIdChanged: function (oldId, newId) {
  5358. this.setId(oldId, newId, true);
  5359. },
  5360. // set parent: change the parent for some node and update all the registrations we need to.
  5361. setParent: function (el, newParent) {
  5362. var _dom = this.getElement(el),
  5363. _id = this.getId(_dom),
  5364. _pdom = this.getElement(newParent),
  5365. _pid = this.getId(_pdom),
  5366. dm = this.getDragManager();
  5367. _dom.parentNode.removeChild(_dom);
  5368. _pdom.appendChild(_dom);
  5369. if (dm) {
  5370. dm.setParent(_dom, _id, _pdom, _pid);
  5371. }
  5372. },
  5373. extend: function (o1, o2, names) {
  5374. var i;
  5375. if (names) {
  5376. for (i = 0; i < names.length; i++)
  5377. o1[names[i]] = o2[names[i]];
  5378. }
  5379. else
  5380. for (i in o2) o1[i] = o2[i];
  5381. return o1;
  5382. },
  5383. floatingConnections: {},
  5384. getFloatingAnchorIndex: function (jpc) {
  5385. return jpc.endpoints[0].isFloating() ? 0 : jpc.endpoints[1].isFloating() ? 1 : -1;
  5386. }
  5387. });
  5388. jsPlumbInstance.prototype.Defaults = {
  5389. Anchor: "Bottom",
  5390. Anchors: [ null, null ],
  5391. ConnectionsDetachable: true,
  5392. ConnectionOverlays: [ ],
  5393. Connector: "Bezier",
  5394. Container: null,
  5395. DoNotThrowErrors: false,
  5396. DragOptions: { },
  5397. DropOptions: { },
  5398. Endpoint: "Dot",
  5399. EndpointOverlays: [ ],
  5400. Endpoints: [ null, null ],
  5401. EndpointStyle: { fill: "#456" },
  5402. EndpointStyles: [ null, null ],
  5403. EndpointHoverStyle: null,
  5404. EndpointHoverStyles: [ null, null ],
  5405. HoverPaintStyle: null,
  5406. LabelStyle: { color: "black" },
  5407. LogEnabled: false,
  5408. Overlays: [ ],
  5409. MaxConnections: 1,
  5410. PaintStyle: { "stroke-width": 4, stroke: "#456" },
  5411. ReattachConnections: false,
  5412. RenderMode: "svg",
  5413. Scope: "jsPlumb_DefaultScope"
  5414. };
  5415. // --------------------- static instance + module registration -------------------------------------------
  5416. // create static instance and assign to window if window exists.
  5417. var jsPlumb = new jsPlumbInstance();
  5418. // register on 'root' (lets us run on server or browser)
  5419. root.jsPlumb = jsPlumb;
  5420. // add 'getInstance' method to static instance
  5421. jsPlumb.getInstance = function (_defaults, overrideFns) {
  5422. var j = new jsPlumbInstance(_defaults);
  5423. if (overrideFns) {
  5424. for (var ovf in overrideFns) {
  5425. j[ovf] = overrideFns[ovf];
  5426. }
  5427. }
  5428. j.init();
  5429. return j;
  5430. };
  5431. jsPlumb.each = function (spec, fn) {
  5432. if (spec == null) return;
  5433. if (typeof spec === "string")
  5434. fn(jsPlumb.getElement(spec));
  5435. else if (spec.length != null) {
  5436. for (var i = 0; i < spec.length; i++)
  5437. fn(jsPlumb.getElement(spec[i]));
  5438. }
  5439. else
  5440. fn(spec); // assume it's an element.
  5441. };
  5442. // CommonJS
  5443. if (typeof exports !== 'undefined') {
  5444. exports.jsPlumb = jsPlumb;
  5445. }
  5446. // --------------------- end static instance + AMD registration -------------------------------------------
  5447. }).call(typeof window !== 'undefined' ? window : this);
  5448. /*
  5449. * jsPlumb
  5450. *
  5451. * Title:jsPlumb 2.3.0
  5452. *
  5453. * Provides a way to visually connect elements on an HTML page, using SVG.
  5454. *
  5455. * This file contains the base functionality for DOM type adapters.
  5456. *
  5457. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  5458. *
  5459. * http://jsplumbtoolkit.com
  5460. * http://github.com/sporritt/jsplumb
  5461. *
  5462. * Dual licensed under the MIT and GPL2 licenses.
  5463. */
  5464. ;
  5465. (function () {
  5466. var root = this, _ju = root.jsPlumbUtil;
  5467. var _genLoc = function (prefix, e) {
  5468. if (e == null) return [ 0, 0 ];
  5469. var ts = _touches(e), t = _getTouch(ts, 0);
  5470. return [t[prefix + "X"], t[prefix + "Y"]];
  5471. },
  5472. _pageLocation = _genLoc.bind(this, "page"),
  5473. _screenLocation = _genLoc.bind(this, "screen"),
  5474. _clientLocation = _genLoc.bind(this, "client"),
  5475. _getTouch = function (touches, idx) {
  5476. return touches.item ? touches.item(idx) : touches[idx];
  5477. },
  5478. _touches = function (e) {
  5479. return e.touches && e.touches.length > 0 ? e.touches :
  5480. e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
  5481. e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
  5482. [ e ];
  5483. };
  5484. /**
  5485. Manages dragging for some instance of jsPlumb.
  5486. TODO instead of this being accessed directly, it should subscribe to events on the jsPlumb instance: every method
  5487. in here is called directly by jsPlumb. But what should happen is that we have unpublished events that this listens
  5488. to. The only trick is getting one of these instantiated with every jsPlumb instance: it needs to have a hook somehow.
  5489. Basically the general idea is to pull ALL the drag code out (prototype method registrations plus this) into a
  5490. dedicated drag script), that does not necessarily need to be included.
  5491. */
  5492. var DragManager = function (_currentInstance) {
  5493. var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {},
  5494. // elementids mapped to the draggable to which they belong.
  5495. _draggablesForElements = {};
  5496. /**
  5497. register some element as draggable. right now the drag init stuff is done elsewhere, and it is
  5498. possible that will continue to be the case.
  5499. */
  5500. this.register = function (el) {
  5501. var id = _currentInstance.getId(el),
  5502. parentOffset = _currentInstance.getOffset(el);
  5503. if (!_draggables[id]) {
  5504. _draggables[id] = el;
  5505. _dlist.push(el);
  5506. _delements[id] = {};
  5507. }
  5508. // look for child elements that have endpoints and register them against this draggable.
  5509. var _oneLevel = function (p) {
  5510. if (p) {
  5511. for (var i = 0; i < p.childNodes.length; i++) {
  5512. if (p.childNodes[i].nodeType != 3 && p.childNodes[i].nodeType != 8) {
  5513. var cEl = jsPlumb.getElement(p.childNodes[i]),
  5514. cid = _currentInstance.getId(p.childNodes[i], null, true);
  5515. if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) {
  5516. var cOff = _currentInstance.getOffset(cEl);
  5517. _delements[id][cid] = {
  5518. id: cid,
  5519. offset: {
  5520. left: cOff.left - parentOffset.left,
  5521. top: cOff.top - parentOffset.top
  5522. }
  5523. };
  5524. _draggablesForElements[cid] = id;
  5525. }
  5526. _oneLevel(p.childNodes[i]);
  5527. }
  5528. }
  5529. }
  5530. };
  5531. _oneLevel(el);
  5532. };
  5533. // refresh the offsets for child elements of this element.
  5534. this.updateOffsets = function (elId, childOffsetOverrides) {
  5535. if (elId != null) {
  5536. childOffsetOverrides = childOffsetOverrides || {};
  5537. var domEl = jsPlumb.getElement(elId),
  5538. id = _currentInstance.getId(domEl),
  5539. children = _delements[id],
  5540. parentOffset = _currentInstance.getOffset(domEl);
  5541. if (children) {
  5542. for (var i in children) {
  5543. if (children.hasOwnProperty(i)) {
  5544. var cel = jsPlumb.getElement(i),
  5545. cOff = childOffsetOverrides[i] || _currentInstance.getOffset(cel);
  5546. // do not update if we have a value already and we'd just be writing 0,0
  5547. if (cel.offsetParent == null && _delements[id][i] != null) continue;
  5548. _delements[id][i] = {
  5549. id: i,
  5550. offset: {
  5551. left: cOff.left - parentOffset.left,
  5552. top: cOff.top - parentOffset.top
  5553. }
  5554. };
  5555. _draggablesForElements[i] = id;
  5556. }
  5557. }
  5558. }
  5559. }
  5560. };
  5561. /**
  5562. notification that an endpoint was added to the given el. we go up from that el's parent
  5563. node, looking for a parent that has been registered as a draggable. if we find one, we add this
  5564. el to that parent's list of elements to update on drag (if it is not there already)
  5565. */
  5566. this.endpointAdded = function (el, id) {
  5567. id = id || _currentInstance.getId(el);
  5568. var b = document.body,
  5569. p = el.parentNode;
  5570. _elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1;
  5571. while (p != null && p != b) {
  5572. var pid = _currentInstance.getId(p, null, true);
  5573. if (pid && _draggables[pid]) {
  5574. var pLoc = _currentInstance.getOffset(p);
  5575. if (_delements[pid][id] == null) {
  5576. var cLoc = _currentInstance.getOffset(el);
  5577. _delements[pid][id] = {
  5578. id: id,
  5579. offset: {
  5580. left: cLoc.left - pLoc.left,
  5581. top: cLoc.top - pLoc.top
  5582. }
  5583. };
  5584. _draggablesForElements[id] = pid;
  5585. }
  5586. break;
  5587. }
  5588. p = p.parentNode;
  5589. }
  5590. };
  5591. this.endpointDeleted = function (endpoint) {
  5592. if (_elementsWithEndpoints[endpoint.elementId]) {
  5593. _elementsWithEndpoints[endpoint.elementId]--;
  5594. if (_elementsWithEndpoints[endpoint.elementId] <= 0) {
  5595. for (var i in _delements) {
  5596. if (_delements.hasOwnProperty(i) && _delements[i]) {
  5597. delete _delements[i][endpoint.elementId];
  5598. delete _draggablesForElements[endpoint.elementId];
  5599. }
  5600. }
  5601. }
  5602. }
  5603. };
  5604. this.changeId = function (oldId, newId) {
  5605. _delements[newId] = _delements[oldId];
  5606. _delements[oldId] = {};
  5607. _draggablesForElements[newId] = _draggablesForElements[oldId];
  5608. _draggablesForElements[oldId] = null;
  5609. };
  5610. this.getElementsForDraggable = function (id) {
  5611. return _delements[id];
  5612. };
  5613. this.elementRemoved = function (elementId) {
  5614. var elId = _draggablesForElements[elementId];
  5615. if (elId) {
  5616. delete _delements[elId][elementId];
  5617. delete _draggablesForElements[elementId];
  5618. }
  5619. };
  5620. this.reset = function () {
  5621. _draggables = {};
  5622. _dlist = [];
  5623. _delements = {};
  5624. _elementsWithEndpoints = {};
  5625. };
  5626. //
  5627. // notification drag ended. We check automatically if need to update some
  5628. // ancestor's offsets.
  5629. //
  5630. this.dragEnded = function (el) {
  5631. if (el.offsetParent != null) {
  5632. var id = _currentInstance.getId(el),
  5633. ancestor = _draggablesForElements[id];
  5634. if (ancestor) this.updateOffsets(ancestor);
  5635. }
  5636. };
  5637. this.setParent = function (el, elId, p, pId, currentChildLocation) {
  5638. var current = _draggablesForElements[elId];
  5639. if (!_delements[pId]) {
  5640. _delements[pId] = {};
  5641. }
  5642. var pLoc = _currentInstance.getOffset(p),
  5643. cLoc = currentChildLocation || _currentInstance.getOffset(el);
  5644. if (current && _delements[current]) {
  5645. delete _delements[current][elId];
  5646. }
  5647. _delements[pId][elId] = {
  5648. id:elId,
  5649. offset : {
  5650. left: cLoc.left - pLoc.left,
  5651. top: cLoc.top - pLoc.top
  5652. }
  5653. };
  5654. _draggablesForElements[elId] = pId;
  5655. };
  5656. this.clearParent = function(el, elId) {
  5657. var current = _draggablesForElements[elId];
  5658. if (current) {
  5659. delete _delements[current][elId];
  5660. delete _draggablesForElements[elId];
  5661. }
  5662. };
  5663. this.revalidateParent = function(el, elId, childOffset) {
  5664. var current = _draggablesForElements[elId];
  5665. if (current) {
  5666. var co = {};
  5667. co[elId] = childOffset;
  5668. this.updateOffsets(current, co);
  5669. _currentInstance.revalidate(current);
  5670. }
  5671. };
  5672. this.getDragAncestor = function (el) {
  5673. var de = jsPlumb.getElement(el),
  5674. id = _currentInstance.getId(de),
  5675. aid = _draggablesForElements[id];
  5676. if (aid)
  5677. return jsPlumb.getElement(aid);
  5678. else
  5679. return null;
  5680. };
  5681. };
  5682. var trim = function (str) {
  5683. return str == null ? null : (str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
  5684. },
  5685. _setClassName = function (el, cn) {
  5686. cn = trim(cn);
  5687. if (typeof el.className.baseVal != "undefined") // SVG
  5688. el.className.baseVal = cn;
  5689. else
  5690. el.className = cn;
  5691. },
  5692. _getClassName = function (el) {
  5693. return (typeof el.className.baseVal == "undefined") ? el.className : el.className.baseVal;
  5694. },
  5695. _classManip = function (el, classesToAdd, classesToRemove) {
  5696. classesToAdd = classesToAdd == null ? [] : _ju.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/);
  5697. classesToRemove = classesToRemove == null ? [] : _ju.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/);
  5698. var className = _getClassName(el),
  5699. curClasses = className.split(/\s+/);
  5700. var _oneSet = function (add, classes) {
  5701. for (var i = 0; i < classes.length; i++) {
  5702. if (add) {
  5703. if (curClasses.indexOf(classes[i]) == -1)
  5704. curClasses.push(classes[i]);
  5705. }
  5706. else {
  5707. var idx = curClasses.indexOf(classes[i]);
  5708. if (idx != -1)
  5709. curClasses.splice(idx, 1);
  5710. }
  5711. }
  5712. };
  5713. _oneSet(true, classesToAdd);
  5714. _oneSet(false, classesToRemove);
  5715. _setClassName(el, curClasses.join(" "));
  5716. };
  5717. root.jsPlumb.extend(root.jsPlumbInstance.prototype, {
  5718. headless: false,
  5719. pageLocation: _pageLocation,
  5720. screenLocation: _screenLocation,
  5721. clientLocation: _clientLocation,
  5722. getDragManager:function() {
  5723. if (this.dragManager == null)
  5724. this.dragManager = new DragManager(this);
  5725. return this.dragManager;
  5726. },
  5727. recalculateOffsets:function(elId) {
  5728. this.getDragManager().updateOffsets(elId);
  5729. },
  5730. createElement:function(tag, style, clazz, atts) {
  5731. return this.createElementNS(null, tag, style, clazz, atts);
  5732. },
  5733. createElementNS:function(ns, tag, style, clazz, atts) {
  5734. var e = ns == null ? document.createElement(tag) : document.createElementNS(ns, tag);
  5735. var i;
  5736. style = style || {};
  5737. for (i in style)
  5738. e.style[i] = style[i];
  5739. if (clazz)
  5740. e.className = clazz;
  5741. atts = atts || {};
  5742. for (i in atts)
  5743. e.setAttribute(i, "" + atts[i]);
  5744. return e;
  5745. },
  5746. getAttribute: function (el, attName) {
  5747. return el.getAttribute != null ? el.getAttribute(attName) : null;
  5748. },
  5749. setAttribute: function (el, a, v) {
  5750. if (el.setAttribute != null) el.setAttribute(a, v);
  5751. },
  5752. setAttributes: function (el, atts) {
  5753. for (var i in atts)
  5754. if (atts.hasOwnProperty(i)) el.setAttribute(i, atts[i]);
  5755. },
  5756. appendToRoot: function (node) {
  5757. document.body.appendChild(node);
  5758. },
  5759. getRenderModes: function () {
  5760. return [ "svg" ];
  5761. },
  5762. getClass:_getClassName,
  5763. addClass: function (el, clazz) {
  5764. jsPlumb.each(el, function (e) {
  5765. _classManip(e, clazz);
  5766. });
  5767. },
  5768. hasClass: function (el, clazz) {
  5769. el = jsPlumb.getElement(el);
  5770. if (el.classList) return el.classList.contains(clazz);
  5771. else {
  5772. return _getClassName(el).indexOf(clazz) != -1;
  5773. }
  5774. },
  5775. removeClass: function (el, clazz) {
  5776. jsPlumb.each(el, function (e) {
  5777. _classManip(e, null, clazz);
  5778. });
  5779. },
  5780. updateClasses: function (el, toAdd, toRemove) {
  5781. jsPlumb.each(el, function (e) {
  5782. _classManip(e, toAdd, toRemove);
  5783. });
  5784. },
  5785. setClass: function (el, clazz) {
  5786. jsPlumb.each(el, function (e) {
  5787. _setClassName(e, clazz);
  5788. });
  5789. },
  5790. setPosition: function (el, p) {
  5791. el.style.left = p.left + "px";
  5792. el.style.top = p.top + "px";
  5793. },
  5794. getPosition: function (el) {
  5795. var _one = function (prop) {
  5796. var v = el.style[prop];
  5797. return v ? v.substring(0, v.length - 2) : 0;
  5798. };
  5799. return {
  5800. left: _one("left"),
  5801. top: _one("top")
  5802. };
  5803. },
  5804. getStyle:function(el, prop) {
  5805. if (typeof window.getComputedStyle !== 'undefined') {
  5806. return getComputedStyle(el, null).getPropertyValue(prop);
  5807. } else {
  5808. return el.currentStyle[prop];
  5809. }
  5810. },
  5811. getSelector: function (ctx, spec) {
  5812. var sel = null;
  5813. if (arguments.length == 1) {
  5814. sel = ctx.nodeType != null ? ctx : document.querySelectorAll(ctx);
  5815. }
  5816. else
  5817. sel = ctx.querySelectorAll(spec);
  5818. return sel;
  5819. },
  5820. getOffset:function(el, relativeToRoot, container) {
  5821. el = jsPlumb.getElement(el);
  5822. container = container || this.getContainer();
  5823. var out = {
  5824. left: el.offsetLeft,
  5825. top: el.offsetTop
  5826. },
  5827. op = (relativeToRoot || (container != null && (el != container && el.offsetParent != container))) ? el.offsetParent : null,
  5828. _maybeAdjustScroll = function(offsetParent) {
  5829. if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) {
  5830. out.left -= offsetParent.scrollLeft;
  5831. out.top -= offsetParent.scrollTop;
  5832. }
  5833. }.bind(this);
  5834. while (op != null) {
  5835. out.left += op.offsetLeft;
  5836. out.top += op.offsetTop;
  5837. _maybeAdjustScroll(op);
  5838. op = relativeToRoot ? op.offsetParent :
  5839. op.offsetParent == container ? null : op.offsetParent;
  5840. }
  5841. // if container is scrolled and the element (or its offset parent) is not absolute or fixed, adjust accordingly.
  5842. if (container != null && !relativeToRoot && (container.scrollTop > 0 || container.scrollLeft > 0)) {
  5843. var pp = el.offsetParent != null ? this.getStyle(el.offsetParent, "position") : "static",
  5844. p = this.getStyle(el, "position");
  5845. if (p !== "absolute" && p !== "fixed" && pp !== "absolute" && pp != "fixed") {
  5846. out.left -= container.scrollLeft;
  5847. out.top -= container.scrollTop;
  5848. }
  5849. }
  5850. return out;
  5851. },
  5852. //
  5853. // return x+y proportion of the given element's size corresponding to the location of the given event.
  5854. //
  5855. getPositionOnElement: function (evt, el, zoom) {
  5856. var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 },
  5857. body = document.body,
  5858. docElem = document.documentElement,
  5859. scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
  5860. scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
  5861. clientTop = docElem.clientTop || body.clientTop || 0,
  5862. clientLeft = docElem.clientLeft || body.clientLeft || 0,
  5863. pst = 0,
  5864. psl = 0,
  5865. top = box.top + scrollTop - clientTop + (pst * zoom),
  5866. left = box.left + scrollLeft - clientLeft + (psl * zoom),
  5867. cl = jsPlumb.pageLocation(evt),
  5868. w = box.width || (el.offsetWidth * zoom),
  5869. h = box.height || (el.offsetHeight * zoom),
  5870. x = (cl[0] - left) / w,
  5871. y = (cl[1] - top) / h;
  5872. return [ x, y ];
  5873. },
  5874. /**
  5875. * Gets the absolute position of some element as read from the left/top properties in its style.
  5876. * @method getAbsolutePosition
  5877. * @param {Element} el The element to retrieve the absolute coordinates from. **Note** this is a DOM element, not a selector from the underlying library.
  5878. * @return {Number[]} [left, top] pixel values.
  5879. */
  5880. getAbsolutePosition: function (el) {
  5881. var _one = function (s) {
  5882. var ss = el.style[s];
  5883. if (ss) return parseFloat(ss.substring(0, ss.length - 2));
  5884. };
  5885. return [ _one("left"), _one("top") ];
  5886. },
  5887. /**
  5888. * Sets the absolute position of some element by setting the left/top properties in its style.
  5889. * @method setAbsolutePosition
  5890. * @param {Element} el The element to set the absolute coordinates on. **Note** this is a DOM element, not a selector from the underlying library.
  5891. * @param {Number[]} xy x and y coordinates
  5892. * @param {Number[]} [animateFrom] Optional previous xy to animate from.
  5893. * @param {Object} [animateOptions] Options for the animation.
  5894. */
  5895. setAbsolutePosition: function (el, xy, animateFrom, animateOptions) {
  5896. if (animateFrom) {
  5897. this.animate(el, {
  5898. left: "+=" + (xy[0] - animateFrom[0]),
  5899. top: "+=" + (xy[1] - animateFrom[1])
  5900. }, animateOptions);
  5901. }
  5902. else {
  5903. el.style.left = xy[0] + "px";
  5904. el.style.top = xy[1] + "px";
  5905. }
  5906. },
  5907. /**
  5908. * gets the size for the element, in an array : [ width, height ].
  5909. */
  5910. getSize: function (el) {
  5911. return [ el.offsetWidth, el.offsetHeight ];
  5912. },
  5913. getWidth: function (el) {
  5914. return el.offsetWidth;
  5915. },
  5916. getHeight: function (el) {
  5917. return el.offsetHeight;
  5918. },
  5919. getRenderMode : function() { return "svg"; }
  5920. });
  5921. }).call(typeof window !== 'undefined' ? window : this);
  5922. /*
  5923. * jsPlumb
  5924. *
  5925. * Title:jsPlumb 2.3.0
  5926. *
  5927. * Provides a way to visually connect elements on an HTML page, using SVG.
  5928. *
  5929. * This file contains code for components that support overlays.
  5930. *
  5931. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  5932. *
  5933. * http://jsplumbtoolkit.com
  5934. * http://github.com/sporritt/jsplumb
  5935. *
  5936. * Dual licensed under the MIT and GPL2 licenses.
  5937. */
  5938. ;(function() {
  5939. "use strict";
  5940. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  5941. // ------------------------------ BEGIN OverlayCapablejsPlumbUIComponent --------------------------------------------
  5942. var _internalLabelOverlayId = "__label",
  5943. // this is a shortcut helper method to let people add a label as
  5944. // overlay.
  5945. _makeLabelOverlay = function (component, params) {
  5946. var _params = {
  5947. cssClass: params.cssClass,
  5948. labelStyle: component.labelStyle,
  5949. id: _internalLabelOverlayId,
  5950. component: component,
  5951. _jsPlumb: component._jsPlumb.instance // TODO not necessary, since the instance can be accessed through the component.
  5952. },
  5953. mergedParams = _jp.extend(_params, params);
  5954. return new _jp.Overlays[component._jsPlumb.instance.getRenderMode()].Label(mergedParams);
  5955. },
  5956. _processOverlay = function (component, o) {
  5957. var _newOverlay = null;
  5958. if (_ju.isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  5959. // there's also a three arg version:
  5960. // ["Arrow", { width:50 }, {location:0.7}]
  5961. // which merges the 3rd arg into the 2nd.
  5962. var type = o[0],
  5963. // make a copy of the object so as not to mess up anyone else's reference...
  5964. p = _jp.extend({component: component, _jsPlumb: component._jsPlumb.instance}, o[1]);
  5965. if (o.length == 3) _jp.extend(p, o[2]);
  5966. _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][type](p);
  5967. } else if (o.constructor == String) {
  5968. _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][o]({component: component, _jsPlumb: component._jsPlumb.instance});
  5969. } else {
  5970. _newOverlay = o;
  5971. }
  5972. _newOverlay.id = _newOverlay.id || _ju.uuid();
  5973. component.cacheTypeItem("overlay", _newOverlay, _newOverlay.id);
  5974. //component._jsPlumb.overlays.push(_newOverlay);
  5975. component._jsPlumb.overlays[_newOverlay.id] = _newOverlay;
  5976. return _newOverlay;
  5977. };
  5978. _jp.OverlayCapableJsPlumbUIComponent = function (params) {
  5979. root.jsPlumbUIComponent.apply(this, arguments);
  5980. this._jsPlumb.overlays = {};
  5981. this._jsPlumb.overlayPositions = {};
  5982. if (params.label) {
  5983. this.getDefaultType().overlays[_internalLabelOverlayId] = ["Label", {
  5984. label: params.label,
  5985. location: params.labelLocation || this.defaultLabelLocation || 0.5,
  5986. labelStyle: params.labelStyle || this._jsPlumb.instance.Defaults.LabelStyle,
  5987. id:_internalLabelOverlayId
  5988. }];
  5989. }
  5990. this.setListenerComponent = function (c) {
  5991. if (this._jsPlumb) {
  5992. for (var i in this._jsPlumb.overlays)
  5993. this._jsPlumb.overlays[i].setListenerComponent(c);
  5994. }
  5995. };
  5996. };
  5997. _jp.OverlayCapableJsPlumbUIComponent.applyType = function (component, t) {
  5998. if (t.overlays) {
  5999. // loop through the ones in the type. if already present on the component,
  6000. // dont remove or re-add.
  6001. var keep = {}, i;
  6002. for (i in t.overlays) {
  6003. var existing = component._jsPlumb.overlays[t.overlays[i][1].id];
  6004. if (existing) {
  6005. // maybe update from data, if there were parameterised values for instance.
  6006. existing.updateFrom(t.overlays[i][1]);
  6007. keep[t.overlays[i][1].id] = true;
  6008. }
  6009. else {
  6010. var c = component.getCachedTypeItem("overlay", t.overlays[i][1].id);
  6011. if (c != null) {
  6012. c.reattach(component._jsPlumb.instance);
  6013. c.setVisible(true);
  6014. // maybe update from data, if there were parameterised values for instance.
  6015. c.updateFrom(t.overlays[i][1]);
  6016. component._jsPlumb.overlays[c.id] = c;
  6017. }
  6018. else {
  6019. c = component.addOverlay(t.overlays[i], true);
  6020. }
  6021. keep[c.id] = true;
  6022. }
  6023. }
  6024. // now loop through the full overlays and remove those that we dont want to keep
  6025. for (i in component._jsPlumb.overlays) {
  6026. if (keep[component._jsPlumb.overlays[i].id] == null)
  6027. component.removeOverlay(component._jsPlumb.overlays[i].id, true); // remove overlay but dont clean it up.
  6028. // that would remove event listeners etc; overlays are never discarded by the types stuff, they are
  6029. // just detached/reattached.
  6030. }
  6031. }
  6032. };
  6033. _ju.extend(_jp.OverlayCapableJsPlumbUIComponent, root.jsPlumbUIComponent, {
  6034. setHover: function (hover, ignoreAttachedElements) {
  6035. if (this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
  6036. for (var i in this._jsPlumb.overlays) {
  6037. this._jsPlumb.overlays[i][hover ? "addClass" : "removeClass"](this._jsPlumb.instance.hoverClass);
  6038. }
  6039. }
  6040. },
  6041. addOverlay: function (overlay, doNotRepaint) {
  6042. var o = _processOverlay(this, overlay);
  6043. if (!doNotRepaint) this.repaint();
  6044. return o;
  6045. },
  6046. getOverlay: function (id) {
  6047. return this._jsPlumb.overlays[id];
  6048. },
  6049. getOverlays: function () {
  6050. return this._jsPlumb.overlays;
  6051. },
  6052. hideOverlay: function (id) {
  6053. var o = this.getOverlay(id);
  6054. if (o) o.hide();
  6055. },
  6056. hideOverlays: function () {
  6057. for (var i in this._jsPlumb.overlays)
  6058. this._jsPlumb.overlays[i].hide();
  6059. },
  6060. showOverlay: function (id) {
  6061. var o = this.getOverlay(id);
  6062. if (o) o.show();
  6063. },
  6064. showOverlays: function () {
  6065. for (var i in this._jsPlumb.overlays)
  6066. this._jsPlumb.overlays[i].show();
  6067. },
  6068. removeAllOverlays: function (doNotRepaint) {
  6069. for (var i in this._jsPlumb.overlays) {
  6070. if (this._jsPlumb.overlays[i].cleanup) this._jsPlumb.overlays[i].cleanup();
  6071. }
  6072. this._jsPlumb.overlays = {};
  6073. this._jsPlumb.overlayPositions = null;
  6074. if (!doNotRepaint)
  6075. this.repaint();
  6076. },
  6077. removeOverlay: function (overlayId, dontCleanup) {
  6078. var o = this._jsPlumb.overlays[overlayId];
  6079. if (o) {
  6080. o.setVisible(false);
  6081. if (!dontCleanup && o.cleanup) o.cleanup();
  6082. delete this._jsPlumb.overlays[overlayId];
  6083. if (this._jsPlumb.overlayPositions)
  6084. delete this._jsPlumb.overlayPositions[overlayId];
  6085. }
  6086. },
  6087. removeOverlays: function () {
  6088. for (var i = 0, j = arguments.length; i < j; i++)
  6089. this.removeOverlay(arguments[i]);
  6090. },
  6091. moveParent: function (newParent) {
  6092. if (this.bgCanvas) {
  6093. this.bgCanvas.parentNode.removeChild(this.bgCanvas);
  6094. newParent.appendChild(this.bgCanvas);
  6095. }
  6096. if (this.canvas && this.canvas.parentNode) {
  6097. this.canvas.parentNode.removeChild(this.canvas);
  6098. newParent.appendChild(this.canvas);
  6099. for (var i in this._jsPlumb.overlays) {
  6100. if (this._jsPlumb.overlays[i].isAppendedAtTopLevel) {
  6101. var el = this._jsPlumb.overlays[i].getElement();
  6102. el.parentNode.removeChild(el);
  6103. newParent.appendChild(el);
  6104. }
  6105. }
  6106. }
  6107. },
  6108. getLabel: function () {
  6109. var lo = this.getOverlay(_internalLabelOverlayId);
  6110. return lo != null ? lo.getLabel() : null;
  6111. },
  6112. getLabelOverlay: function () {
  6113. return this.getOverlay(_internalLabelOverlayId);
  6114. },
  6115. setLabel: function (l) {
  6116. var lo = this.getOverlay(_internalLabelOverlayId);
  6117. if (!lo) {
  6118. var params = l.constructor == String || l.constructor == Function ? { label: l } : l;
  6119. lo = _makeLabelOverlay(this, params);
  6120. this._jsPlumb.overlays[_internalLabelOverlayId] = lo;
  6121. }
  6122. else {
  6123. if (l.constructor == String || l.constructor == Function) lo.setLabel(l);
  6124. else {
  6125. if (l.label) lo.setLabel(l.label);
  6126. if (l.location) lo.setLocation(l.location);
  6127. }
  6128. }
  6129. if (!this._jsPlumb.instance.isSuspendDrawing())
  6130. this.repaint();
  6131. },
  6132. cleanup: function (force) {
  6133. for (var i in this._jsPlumb.overlays) {
  6134. this._jsPlumb.overlays[i].cleanup(force);
  6135. this._jsPlumb.overlays[i].destroy(force);
  6136. }
  6137. if (force) {
  6138. this._jsPlumb.overlays = {};
  6139. this._jsPlumb.overlayPositions = null;
  6140. }
  6141. },
  6142. setVisible: function (v) {
  6143. this[v ? "showOverlays" : "hideOverlays"]();
  6144. },
  6145. setAbsoluteOverlayPosition: function (overlay, xy) {
  6146. this._jsPlumb.overlayPositions[overlay.id] = xy;
  6147. },
  6148. getAbsoluteOverlayPosition: function (overlay) {
  6149. return this._jsPlumb.overlayPositions ? this._jsPlumb.overlayPositions[overlay.id] : null;
  6150. },
  6151. _clazzManip:function(action, clazz, dontUpdateOverlays) {
  6152. if (!dontUpdateOverlays) {
  6153. for (var i in this._jsPlumb.overlays) {
  6154. this._jsPlumb.overlays[i][action + "Class"](clazz);
  6155. }
  6156. }
  6157. },
  6158. addClass:function(clazz, dontUpdateOverlays) {
  6159. this._clazzManip("add", clazz, dontUpdateOverlays)
  6160. },
  6161. removeClass:function(clazz, dontUpdateOverlays) {
  6162. this._clazzManip("remove", clazz, dontUpdateOverlays)
  6163. }
  6164. });
  6165. // ------------------------------ END OverlayCapablejsPlumbUIComponent --------------------------------------------
  6166. }).call(typeof window !== 'undefined' ? window : this);
  6167. /*
  6168. * jsPlumb
  6169. *
  6170. * Title:jsPlumb 2.3.0
  6171. *
  6172. * Provides a way to visually connect elements on an HTML page, using SVG.
  6173. *
  6174. * This file contains the code for Endpoints.
  6175. *
  6176. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  6177. *
  6178. * http://jsplumbtoolkit.com
  6179. * http://github.com/sporritt/jsplumb
  6180. *
  6181. * Dual licensed under the MIT and GPL2 licenses.
  6182. */
  6183. (function () {
  6184. "use strict";
  6185. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  6186. // create the drag handler for a connection
  6187. var _makeConnectionDragHandler = function (endpoint, placeholder, _jsPlumb) {
  6188. var stopped = false;
  6189. return {
  6190. drag: function () {
  6191. if (stopped) {
  6192. stopped = false;
  6193. return true;
  6194. }
  6195. if (placeholder.element) {
  6196. var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom());
  6197. if (_ui != null) jsPlumb.setPosition(placeholder.element, _ui);
  6198. _jsPlumb.repaint(placeholder.element, _ui);
  6199. // always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint
  6200. // to be repainted, so static anchors need to be told (or the endpoint gets dragged around)
  6201. endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint})});
  6202. }
  6203. },
  6204. stopDrag: function () {
  6205. stopped = true;
  6206. }
  6207. };
  6208. };
  6209. // creates a placeholder div for dragging purposes, adds it, and pre-computes its offset.
  6210. var _makeDraggablePlaceholder = function (placeholder, _jsPlumb, ipco, ips) {
  6211. var n = jsPlumb.createElement("div", { position : "absolute" });
  6212. _jsPlumb.appendElement(n);
  6213. var id = _jsPlumb.getId(n);
  6214. jsPlumb.setPosition(n, ipco);
  6215. n.style.width = ips[0] + "px";
  6216. n.style.height = ips[1] + "px";
  6217. _jsPlumb.manage(id, n, true); // TRANSIENT MANAGE
  6218. // create and assign an id, and initialize the offset.
  6219. placeholder.id = id;
  6220. placeholder.element = n;
  6221. };
  6222. // create a floating endpoint (for drag connections)
  6223. var _makeFloatingEndpoint = function (paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint, scope) {
  6224. var floatingAnchor = new _jp.FloatingAnchor({ reference: referenceAnchor, referenceCanvas: referenceCanvas, jsPlumbInstance: _jsPlumb });
  6225. //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
  6226. // adding the floating endpoint as a droppable. that makes more sense anyway!
  6227. // TRANSIENT MANAGE
  6228. return _newEndpoint({
  6229. paintStyle: paintStyle,
  6230. endpoint: endpoint,
  6231. anchor: floatingAnchor,
  6232. source: sourceElement,
  6233. scope: scope
  6234. });
  6235. };
  6236. var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays",
  6237. "connector", "connectionType", "connectorClass", "connectorHoverClass" ];
  6238. // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
  6239. // or no connection to it is found, we return the first connection in our list.
  6240. var findConnectionToUseForDynamicAnchor = function (ep, elementWithPrecedence) {
  6241. var idx = 0;
  6242. if (elementWithPrecedence != null) {
  6243. for (var i = 0; i < ep.connections.length; i++) {
  6244. if (ep.connections[i].sourceId == elementWithPrecedence || ep.connections[i].targetId == elementWithPrecedence) {
  6245. idx = i;
  6246. break;
  6247. }
  6248. }
  6249. }
  6250. return ep.connections[idx];
  6251. };
  6252. _jp.Endpoint = function (params) {
  6253. var _jsPlumb = params._jsPlumb,
  6254. _newConnection = params.newConnection,
  6255. _newEndpoint = params.newEndpoint;
  6256. this.idPrefix = "_jsplumb_e_";
  6257. this.defaultLabelLocation = [ 0.5, 0.5 ];
  6258. this.defaultOverlayKeys = ["Overlays", "EndpointOverlays"];
  6259. _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
  6260. // TYPE
  6261. this.appendToDefaultType({
  6262. connectionType:params.connectionType,
  6263. maxConnections: params.maxConnections == null ? this._jsPlumb.instance.Defaults.MaxConnections : params.maxConnections, // maximum number of connections this endpoint can be the source of.,
  6264. paintStyle: params.endpointStyle || params.paintStyle || params.style || this._jsPlumb.instance.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle,
  6265. hoverPaintStyle: params.endpointHoverStyle || params.hoverPaintStyle || this._jsPlumb.instance.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle,
  6266. connectorStyle: params.connectorStyle,
  6267. connectorHoverStyle: params.connectorHoverStyle,
  6268. connectorClass: params.connectorClass,
  6269. connectorHoverClass: params.connectorHoverClass,
  6270. connectorOverlays: params.connectorOverlays,
  6271. connector: params.connector,
  6272. connectorTooltip: params.connectorTooltip
  6273. });
  6274. // END TYPE
  6275. this._jsPlumb.enabled = !(params.enabled === false);
  6276. this._jsPlumb.visible = true;
  6277. this.element = _jp.getElement(params.source);
  6278. this._jsPlumb.uuid = params.uuid;
  6279. this._jsPlumb.floatingEndpoint = null;
  6280. var inPlaceCopy = null;
  6281. if (this._jsPlumb.uuid) params.endpointsByUUID[this._jsPlumb.uuid] = this;
  6282. this.elementId = params.elementId;
  6283. this.dragProxy = params.dragProxy;
  6284. this._jsPlumb.connectionCost = params.connectionCost;
  6285. this._jsPlumb.connectionsDirected = params.connectionsDirected;
  6286. this._jsPlumb.currentAnchorClass = "";
  6287. this._jsPlumb.events = {};
  6288. var deleteOnEmpty = params.deleteOnEmpty === true;
  6289. this.setDeleteOnEmpty = function(d) { deleteOnEmpty = d; };
  6290. var _updateAnchorClass = function () {
  6291. // stash old, get new
  6292. var oldAnchorClass = _jsPlumb.endpointAnchorClassPrefix + "-" + this._jsPlumb.currentAnchorClass;
  6293. this._jsPlumb.currentAnchorClass = this.anchor.getCssClass();
  6294. var anchorClass = _jsPlumb.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
  6295. this.removeClass(oldAnchorClass);
  6296. this.addClass(anchorClass);
  6297. // add and remove at the same time to reduce the number of reflows.
  6298. _jp.updateClasses(this.element, anchorClass, oldAnchorClass);
  6299. }.bind(this);
  6300. this.prepareAnchor = function(anchorParams) {
  6301. var a = this._jsPlumb.instance.makeAnchor(anchorParams, this.elementId, _jsPlumb);
  6302. a.bind("anchorChanged", function (currentAnchor) {
  6303. this.fire("anchorChanged", {endpoint: this, anchor: currentAnchor});
  6304. _updateAnchorClass();
  6305. }.bind(this));
  6306. return a;
  6307. };
  6308. this.setPreparedAnchor = function(anchor, doNotRepaint) {
  6309. this._jsPlumb.instance.continuousAnchorFactory.clear(this.elementId);
  6310. this.anchor = anchor;
  6311. _updateAnchorClass();
  6312. if (!doNotRepaint)
  6313. this._jsPlumb.instance.repaint(this.elementId);
  6314. return this;
  6315. };
  6316. this.setAnchor = function (anchorParams, doNotRepaint) {
  6317. var a = this.prepareAnchor(anchorParams);
  6318. this.setPreparedAnchor(a, doNotRepaint);
  6319. return this;
  6320. };
  6321. var internalHover = function (state) {
  6322. if (this.connections.length > 0) {
  6323. for (var i = 0; i < this.connections.length; i++)
  6324. this.connections[i].setHover(state, false);
  6325. }
  6326. else
  6327. this.setHover(state);
  6328. }.bind(this);
  6329. this.bind("mouseover", function () {
  6330. internalHover(true);
  6331. });
  6332. this.bind("mouseout", function () {
  6333. internalHover(false);
  6334. });
  6335. // ANCHOR MANAGER
  6336. 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.
  6337. this._jsPlumb.instance.anchorManager.add(this, this.elementId);
  6338. this.prepareEndpoint = function(ep, typeId) {
  6339. var _e = function (t, p) {
  6340. var rm = _jsPlumb.getRenderMode();
  6341. if (_jp.Endpoints[rm][t]) return new _jp.Endpoints[rm][t](p);
  6342. if (!_jsPlumb.Defaults.DoNotThrowErrors)
  6343. throw { msg: "jsPlumb: unknown endpoint type '" + t + "'" };
  6344. };
  6345. var endpointArgs = {
  6346. _jsPlumb: this._jsPlumb.instance,
  6347. cssClass: params.cssClass,
  6348. container: params.container,
  6349. tooltip: params.tooltip,
  6350. connectorTooltip: params.connectorTooltip,
  6351. endpoint: this
  6352. };
  6353. var endpoint;
  6354. if (_ju.isString(ep))
  6355. endpoint = _e(ep, endpointArgs);
  6356. else if (_ju.isArray(ep)) {
  6357. endpointArgs = _ju.merge(ep[1], endpointArgs);
  6358. endpoint = _e(ep[0], endpointArgs);
  6359. }
  6360. else {
  6361. endpoint = ep.clone();
  6362. }
  6363. // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
  6364. // and the clone is left in its place while the original one goes off on a magical journey.
  6365. // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by
  6366. // the whole world.
  6367. //var argsForClone = jsPlumb.extend({}, endpointArgs);
  6368. endpoint.clone = function () {
  6369. // TODO this, and the code above, can be refactored to be more dry.
  6370. if (_ju.isString(ep))
  6371. return _e(ep, endpointArgs);
  6372. else if (_ju.isArray(ep)) {
  6373. endpointArgs = _ju.merge(ep[1], endpointArgs);
  6374. return _e(ep[0], endpointArgs);
  6375. }
  6376. }.bind(this);
  6377. endpoint.typeId = typeId;
  6378. return endpoint;
  6379. };
  6380. this.setEndpoint = function(ep, doNotRepaint) {
  6381. var _ep = this.prepareEndpoint(ep);
  6382. this.setPreparedEndpoint(_ep, true);
  6383. };
  6384. this.setPreparedEndpoint = function (ep, doNotRepaint) {
  6385. if (this.endpoint != null) {
  6386. this.endpoint.cleanup();
  6387. this.endpoint.destroy();
  6388. }
  6389. this.endpoint = ep;
  6390. this.type = this.endpoint.type;
  6391. this.canvas = this.endpoint.canvas;
  6392. };
  6393. _jp.extend(this, params, typeParameters);
  6394. this.isSource = params.isSource || false;
  6395. this.isTemporarySource = params.isTemporarySource || false;
  6396. this.isTarget = params.isTarget || false;
  6397. this.connections = params.connections || [];
  6398. this.connectorPointerEvents = params["connector-pointer-events"];
  6399. this.scope = params.scope || _jsPlumb.getDefaultScope();
  6400. this.timestamp = null;
  6401. this.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections;
  6402. this.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable;
  6403. if (params.connectionsDetachable === false || params.detachable === false)
  6404. this.connectionsDetachable = false;
  6405. this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false;
  6406. if (params.onMaxConnections)
  6407. this.bind("maxConnections", params.onMaxConnections);
  6408. //
  6409. // add a connection. not part of public API.
  6410. //
  6411. this.addConnection = function (connection) {
  6412. this.connections.push(connection);
  6413. this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
  6414. this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
  6415. };
  6416. this.detachFromConnection = function (connection, idx, doNotCleanup) {
  6417. idx = idx == null ? this.connections.indexOf(connection) : idx;
  6418. if (idx >= 0) {
  6419. this.connections.splice(idx, 1);
  6420. this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
  6421. this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
  6422. }
  6423. //if ((this._forceDeleteOnDetach || (!doNotCleanup && this._deleteOnDetach)) && this.connections.length === 0) {
  6424. if (!doNotCleanup && deleteOnEmpty && this.connections.length === 0) {
  6425. _jsPlumb.deleteObject({
  6426. endpoint: this,
  6427. fireEvent: false,
  6428. deleteAttachedObjects: doNotCleanup !== true
  6429. });
  6430. }
  6431. };
  6432. this.deleteEveryConnection = function(params) {
  6433. var c = this.connections.length;
  6434. for (var i = 0; i < c; i++) {
  6435. _jsPlumb.deleteConnection(this.connections[0], params);
  6436. }
  6437. };
  6438. //this.detach = function (connection, ignoreTarget, forceDetach, fireEvent, originalEvent, endpointBeingDeleted, connectionIndex) {
  6439. // this.detach = function (params) {
  6440. // var connectionIndex = params.connectionIndex,
  6441. // connection = params.connection,
  6442. // ignoreTarget = params.ignoreTarget,
  6443. // fireEvent = params.fireEvent,
  6444. // originalEvent = params.originalEvent,
  6445. // endpointBeingDeleted = params.endpointBeingDeleted,
  6446. // forceDetach = params.forceDetach;
  6447. //
  6448. // var idx = connectionIndex == null ? this.connections.indexOf(connection) : connectionIndex,
  6449. // actuallyDetached = false;
  6450. // fireEvent = (fireEvent !== false);
  6451. //
  6452. // if (idx >= 0) {
  6453. //
  6454. // if (forceDetach || connection._forceDetach || (connection.isDetachable() && connection.isDetachAllowed(connection) && this.isDetachAllowed(connection) && _jsPlumb.checkCondition("beforeDetach", connection, endpointBeingDeleted) )) {
  6455. //
  6456. // _jsPlumb.deleteObject({
  6457. // connection: connection,
  6458. // fireEvent: (!ignoreTarget && fireEvent),
  6459. // originalEvent: originalEvent,
  6460. // deleteAttachedObjects:params.deleteAttachedObjects
  6461. // //deleteAttachedObjects:null
  6462. // });
  6463. // actuallyDetached = true;
  6464. // }
  6465. // }
  6466. // return actuallyDetached;
  6467. // };
  6468. // this.detachAll = function (fireEvent, forceDetach) {
  6469. // var unaffectedConns = [];
  6470. // while (this.connections.length > 0) {
  6471. // // TODO this could pass the index in to the detach method to save some time (index will always be zero in this while loop)
  6472. // var actuallyDetached = _jsPlumb.detach({
  6473. // connection:this.connections[0],
  6474. // ignoreTarget:false,
  6475. // forceDetach:forceDetach === true,
  6476. // fireEvent:fireEvent !== false,
  6477. // originalEvent:null,
  6478. // endpointBeingDeleted:this,
  6479. // connectionIndex:0
  6480. // });
  6481. // if (!actuallyDetached) {
  6482. // unaffectedConns.push(this.connections[0]);
  6483. // this.connections.splice(0, 1);
  6484. // }
  6485. // }
  6486. // this.connections = unaffectedConns;
  6487. // return this;
  6488. // };
  6489. this.detachFrom = function (targetEndpoint, fireEvent, originalEvent) {
  6490. var c = [];
  6491. for (var i = 0; i < this.connections.length; i++) {
  6492. if (this.connections[i].endpoints[1] == targetEndpoint || this.connections[i].endpoints[0] == targetEndpoint) {
  6493. c.push(this.connections[i]);
  6494. }
  6495. }
  6496. var count = c.length;
  6497. for (var j = 0; j < count; j++) {
  6498. // this.detach({
  6499. // connection:c[j],
  6500. // ignoreTarget:false,
  6501. // forceDetach:true,
  6502. // fireEvent:fireEvent,
  6503. // originalEvent:originalEvent
  6504. // });
  6505. _jsPlumb.deleteConnection(c[0]);
  6506. }
  6507. return this;
  6508. };
  6509. this.getElement = function () {
  6510. return this.element;
  6511. };
  6512. this.setElement = function (el) {
  6513. var parentId = this._jsPlumb.instance.getId(el),
  6514. curId = this.elementId;
  6515. // remove the endpoint from the list for the current endpoint's element
  6516. _ju.removeWithFunction(params.endpointsByElement[this.elementId], function (e) {
  6517. return e.id == this.id;
  6518. }.bind(this));
  6519. this.element = _jp.getElement(el);
  6520. this.elementId = _jsPlumb.getId(this.element);
  6521. _jsPlumb.anchorManager.rehomeEndpoint(this, curId, this.element);
  6522. _jsPlumb.dragManager.endpointAdded(this.element);
  6523. _ju.addToList(params.endpointsByElement, parentId, this);
  6524. return this;
  6525. };
  6526. /**
  6527. * private but must be exposed.
  6528. */
  6529. this.makeInPlaceCopy = function () {
  6530. var loc = this.anchor.getCurrentLocation({element: this}),
  6531. o = this.anchor.getOrientation(this),
  6532. acc = this.anchor.getCssClass(),
  6533. inPlaceAnchor = {
  6534. bind: function () {
  6535. },
  6536. compute: function () {
  6537. return [ loc[0], loc[1] ];
  6538. },
  6539. getCurrentLocation: function () {
  6540. return [ loc[0], loc[1] ];
  6541. },
  6542. getOrientation: function () {
  6543. return o;
  6544. },
  6545. getCssClass: function () {
  6546. return acc;
  6547. }
  6548. };
  6549. return _newEndpoint({
  6550. dropOptions: params.dropOptions,
  6551. anchor: inPlaceAnchor,
  6552. source: this.element,
  6553. paintStyle: this.getPaintStyle(),
  6554. endpoint: params.hideOnDrag ? "Blank" : this.endpoint,
  6555. _transient: true,
  6556. scope: this.scope,
  6557. reference:this
  6558. });
  6559. };
  6560. /**
  6561. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  6562. */
  6563. this.connectorSelector = function () {
  6564. var candidate = this.connections[0];
  6565. // SP target source refactor
  6566. if (/*this.isTarget && */candidate) return candidate;
  6567. else {
  6568. return (this.connections.length < this._jsPlumb.maxConnections) || this._jsPlumb.maxConnections == -1 ? null : candidate;
  6569. }
  6570. };
  6571. this.setStyle = this.setPaintStyle;
  6572. this.paint = function (params) {
  6573. params = params || {};
  6574. var timestamp = params.timestamp, recalc = !(params.recalc === false);
  6575. if (!timestamp || this.timestamp !== timestamp) {
  6576. var info = _jsPlumb.updateOffset({ elId: this.elementId, timestamp: timestamp });
  6577. var xy = params.offset ? params.offset.o : info.o;
  6578. if (xy != null) {
  6579. var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle;
  6580. if (ap == null) {
  6581. var wh = params.dimensions || info.s,
  6582. anchorParams = { xy: [ xy.left, xy.top ], wh: wh, element: this, timestamp: timestamp };
  6583. if (recalc && this.anchor.isDynamic && this.connections.length > 0) {
  6584. var c = findConnectionToUseForDynamicAnchor(this, params.elementWithPrecedence),
  6585. oIdx = c.endpoints[0] == this ? 1 : 0,
  6586. oId = oIdx === 0 ? c.sourceId : c.targetId,
  6587. oInfo = _jsPlumb.getCachedData(oId),
  6588. oOffset = oInfo.o, oWH = oInfo.s;
  6589. anchorParams.txy = [ oOffset.left, oOffset.top ];
  6590. anchorParams.twh = oWH;
  6591. anchorParams.tElement = c.endpoints[oIdx];
  6592. }
  6593. ap = this.anchor.compute(anchorParams);
  6594. }
  6595. this.endpoint.compute(ap, this.anchor.getOrientation(this), this._jsPlumb.paintStyleInUse, connectorPaintStyle || this.paintStyleInUse);
  6596. this.endpoint.paint(this._jsPlumb.paintStyleInUse, this.anchor);
  6597. this.timestamp = timestamp;
  6598. // paint overlays
  6599. for (var i in this._jsPlumb.overlays) {
  6600. if (this._jsPlumb.overlays.hasOwnProperty(i)) {
  6601. var o = this._jsPlumb.overlays[i];
  6602. if (o.isVisible()) {
  6603. this._jsPlumb.overlayPlacements[i] = o.draw(this.endpoint, this._jsPlumb.paintStyleInUse);
  6604. o.paint(this._jsPlumb.overlayPlacements[i]);
  6605. }
  6606. }
  6607. }
  6608. }
  6609. }
  6610. };
  6611. this.getTypeDescriptor = function () {
  6612. return "endpoint";
  6613. };
  6614. this.isVisible = function () {
  6615. return this._jsPlumb.visible;
  6616. };
  6617. this.repaint = this.paint;
  6618. var draggingInitialised = false;
  6619. this.initDraggable = function () {
  6620. // is this a connection source? we make it draggable and have the
  6621. // drag listener maintain a connection with a floating endpoint.
  6622. if (!draggingInitialised && _jp.isDragSupported(this.element)) {
  6623. var placeholderInfo = { id: null, element: null },
  6624. jpc = null,
  6625. existingJpc = false,
  6626. existingJpcParams = null,
  6627. _dragHandler = _makeConnectionDragHandler(this, placeholderInfo, _jsPlumb),
  6628. dragOptions = params.dragOptions || {},
  6629. defaultOpts = {},
  6630. startEvent = _jp.dragEvents.start,
  6631. stopEvent = _jp.dragEvents.stop,
  6632. dragEvent = _jp.dragEvents.drag,
  6633. beforeStartEvent = _jp.dragEvents.beforeStart,
  6634. payload;
  6635. // respond to beforeStart from katavorio; this will have, optionally, a payload of attribute values
  6636. // that were placed there by the makeSource mousedown listener.
  6637. var beforeStart = function(beforeStartParams) {
  6638. payload = beforeStartParams.e.payload || {};
  6639. };
  6640. var start = function (startParams) {
  6641. // ------------- first, get a connection to drag. this may be null, in which case we are dragging a new one.
  6642. jpc = this.connectorSelector();
  6643. // -------------------------------- now a bunch of tests about whether or not to proceed -------------------------
  6644. var _continue = true;
  6645. // if not enabled, return
  6646. if (!this.isEnabled()) _continue = false;
  6647. // if no connection and we're not a source - or temporarily a source, as is the case with makeSource - return.
  6648. if (jpc == null && !this.isSource && !this.isTemporarySource) _continue = false;
  6649. // otherwise if we're full and not allowed to drag, also return false.
  6650. if (this.isSource && this.isFull() && !(jpc != null && this.dragAllowedWhenFull)) _continue = false;
  6651. // if the connection was setup as not detachable or one of its endpoints
  6652. // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
  6653. // is set to false...
  6654. if (jpc != null && !jpc.isDetachable(this)) _continue = false;
  6655. var beforeDrag = _jsPlumb.checkCondition(jpc == null ? "beforeDrag" : "beforeStartDetach", {
  6656. endpoint:this,
  6657. source:this.element,
  6658. sourceId:this.elementId,
  6659. connection:jpc
  6660. });
  6661. if (beforeDrag === false) _continue = false;
  6662. // else we might have been given some data. we'll pass it in to a new connection as 'data'.
  6663. // here we also merge in the optional payload we were given on mousedown.
  6664. else if (typeof beforeDrag === "object") {
  6665. _jp.extend(beforeDrag, payload || {});
  6666. }
  6667. else
  6668. // or if no beforeDrag data, maybe use the payload on its own.
  6669. beforeDrag = payload || {};
  6670. if (_continue === false) {
  6671. // this is for mootools and yui. returning false from this causes jquery to stop drag.
  6672. // the events are wrapped in both mootools and yui anyway, but i don't think returning
  6673. // false from the start callback would stop a drag.
  6674. if (_jsPlumb.stopDrag) _jsPlumb.stopDrag(this.canvas);
  6675. _dragHandler.stopDrag();
  6676. return false;
  6677. }
  6678. // ---------------------------------------------------------------------------------------------------------------------
  6679. // ok to proceed.
  6680. // clear hover for all connections for this endpoint before continuing.
  6681. for (var i = 0; i < this.connections.length; i++)
  6682. this.connections[i].setHover(false);
  6683. this.addClass("endpointDrag");
  6684. _jsPlumb.setConnectionBeingDragged(true);
  6685. // if we're not full but there was a connection, make it null. we'll create a new one.
  6686. if (jpc && !this.isFull() && this.isSource) jpc = null;
  6687. _jsPlumb.updateOffset({ elId: this.elementId });
  6688. // ---------------- make the element we will drag around, and position it -----------------------------
  6689. var ipco = this._jsPlumb.instance.getOffset(this.canvas),
  6690. canvasElement = this.canvas,
  6691. ips = this._jsPlumb.instance.getSize(this.canvas);
  6692. _makeDraggablePlaceholder(placeholderInfo, _jsPlumb, ipco, ips);
  6693. // store the id of the dragging div and the source element. the drop function will pick these up.
  6694. _jsPlumb.setAttributes(this.canvas, {
  6695. "dragId": placeholderInfo.id,
  6696. "elId": this.elementId
  6697. });
  6698. // ------------------- create an endpoint that will be our floating endpoint ------------------------------------
  6699. var endpointToFloat = this.dragProxy || this.endpoint;
  6700. if (this.dragProxy == null && this.connectionType != null) {
  6701. var aae = this._jsPlumb.instance.deriveEndpointAndAnchorSpec(this.connectionType);
  6702. if (aae.endpoints[1]) endpointToFloat = aae.endpoints[1];
  6703. }
  6704. var centerAnchor = this._jsPlumb.instance.makeAnchor("Center");
  6705. centerAnchor.isFloating = true;
  6706. this._jsPlumb.floatingEndpoint = _makeFloatingEndpoint(this.getPaintStyle(), centerAnchor, endpointToFloat, this.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint, this.scope);
  6707. var _savedAnchor = this._jsPlumb.floatingEndpoint.anchor;
  6708. if (jpc == null) {
  6709. this.setHover(false, false);
  6710. // create a connection. one end is this endpoint, the other is a floating endpoint.
  6711. jpc = _newConnection({
  6712. sourceEndpoint: this,
  6713. targetEndpoint: this._jsPlumb.floatingEndpoint,
  6714. source: this.element, // for makeSource with parent option. ensure source element is represented correctly.
  6715. target: placeholderInfo.element,
  6716. anchors: [ this.anchor, this._jsPlumb.floatingEndpoint.anchor ],
  6717. paintStyle: params.connectorStyle, // this can be null. Connection will use the default.
  6718. hoverPaintStyle: params.connectorHoverStyle,
  6719. connector: params.connector, // this can also be null. Connection will use the default.
  6720. overlays: params.connectorOverlays,
  6721. type: this.connectionType,
  6722. cssClass: this.connectorClass,
  6723. hoverClass: this.connectorHoverClass,
  6724. scope:params.scope,
  6725. data:beforeDrag
  6726. });
  6727. jpc.pending = true;
  6728. jpc.addClass(_jsPlumb.draggingClass);
  6729. this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
  6730. this._jsPlumb.floatingEndpoint.anchor = _savedAnchor;
  6731. // fire an event that informs that a connection is being dragged
  6732. _jsPlumb.fire("connectionDrag", jpc);
  6733. // register the new connection on the drag manager. This connection, at this point, is 'pending',
  6734. // and has as its target a temporary element (the 'placeholder'). If the connection subsequently
  6735. // becomes established, the anchor manager is informed that the target of the connection has
  6736. // changed.
  6737. _jsPlumb.anchorManager.newConnection(jpc);
  6738. } else {
  6739. existingJpc = true;
  6740. jpc.setHover(false);
  6741. // new anchor idx
  6742. var anchorIdx = jpc.endpoints[0].id == this.id ? 0 : 1;
  6743. this.detachFromConnection(jpc, null, true); // detach from the connection while dragging is occurring. but dont cleanup automatically.
  6744. // store the original scope (issue 57)
  6745. var dragScope = _jsPlumb.getDragScope(canvasElement);
  6746. _jsPlumb.setAttribute(this.canvas, "originalScope", dragScope);
  6747. // fire an event that informs that a connection is being dragged. we do this before
  6748. // replacing the original target with the floating element info.
  6749. _jsPlumb.fire("connectionDrag", jpc);
  6750. // now we replace ourselves with the temporary div we created above:
  6751. if (anchorIdx === 0) {
  6752. existingJpcParams = [ jpc.source, jpc.sourceId, canvasElement, dragScope ];
  6753. _jsPlumb.anchorManager.sourceChanged(jpc.endpoints[anchorIdx].elementId, placeholderInfo.id, jpc, placeholderInfo.element);
  6754. } else {
  6755. existingJpcParams = [ jpc.target, jpc.targetId, canvasElement, dragScope ];
  6756. jpc.target = placeholderInfo.element;
  6757. jpc.targetId = placeholderInfo.id;
  6758. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.endpoints[anchorIdx].elementId, jpc.targetId, jpc);
  6759. }
  6760. // store the original endpoint and assign the new floating endpoint for the drag.
  6761. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  6762. // PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39)
  6763. jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement();
  6764. jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId;
  6765. jpc.suspendedElementType = anchorIdx === 0 ? "source" : "target";
  6766. jpc.suspendedEndpoint.setHover(false);
  6767. this._jsPlumb.floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint;
  6768. jpc.endpoints[anchorIdx] = this._jsPlumb.floatingEndpoint;
  6769. jpc.addClass(_jsPlumb.draggingClass);
  6770. this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
  6771. }
  6772. // register it and register connection on it.
  6773. _jsPlumb.floatingConnections[placeholderInfo.id] = jpc;
  6774. // only register for the target endpoint; we will not be dragging the source at any time
  6775. // before this connection is either discarded or made into a permanent connection.
  6776. _ju.addToList(params.endpointsByElement, placeholderInfo.id, this._jsPlumb.floatingEndpoint);
  6777. // tell jsplumb about it
  6778. _jsPlumb.currentlyDragging = true;
  6779. }.bind(this);
  6780. var stop = function () {
  6781. _jsPlumb.setConnectionBeingDragged(false);
  6782. if (jpc && jpc.endpoints != null) {
  6783. // get the actual drop event (decode from library args to stop function)
  6784. var originalEvent = _jsPlumb.getDropEvent(arguments);
  6785. // unlock the other endpoint (if it is dynamic, it would have been locked at drag start)
  6786. var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
  6787. jpc.endpoints[idx === 0 ? 1 : 0].anchor.locked = false;
  6788. // TODO: Dont want to know about css classes inside jsplumb, ideally.
  6789. jpc.removeClass(_jsPlumb.draggingClass);
  6790. // if we have the floating endpoint then the connection has not been dropped
  6791. // on another endpoint. If it is a new connection we throw it away. If it is an
  6792. // existing connection we check to see if we should reattach it, throwing it away
  6793. // if not.
  6794. if (this._jsPlumb && (jpc.deleteConnectionNow || jpc.endpoints[idx] == this._jsPlumb.floatingEndpoint)) {
  6795. // 6a. if the connection was an existing one...
  6796. if (existingJpc && jpc.suspendedEndpoint) {
  6797. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  6798. // floating endpoint has been replaced.
  6799. if (idx === 0) {
  6800. jpc.floatingElement = jpc.source;
  6801. jpc.floatingId = jpc.sourceId;
  6802. jpc.floatingEndpoint = jpc.endpoints[0];
  6803. jpc.floatingIndex = 0;
  6804. jpc.source = existingJpcParams[0];
  6805. jpc.sourceId = existingJpcParams[1];
  6806. } else {
  6807. // keep a copy of the floating element; the anchor manager will want to clean up.
  6808. jpc.floatingElement = jpc.target;
  6809. jpc.floatingId = jpc.targetId;
  6810. jpc.floatingEndpoint = jpc.endpoints[1];
  6811. jpc.floatingIndex = 1;
  6812. jpc.target = existingJpcParams[0];
  6813. jpc.targetId = existingJpcParams[1];
  6814. }
  6815. var fe = this._jsPlumb.floatingEndpoint; // store for later removal.
  6816. // restore the original scope (issue 57)
  6817. _jsPlumb.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  6818. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  6819. // IF the connection should be reattached, or the other endpoint refuses detach, then
  6820. // reset the connection to its original state
  6821. //if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !jpc.endpoints[idx === 0 ? 1 : 0].detach({connection:jpc, ignoreTarget:false, forceDetach:false, fireEvent:true, originalEvent:originalEvent, endpointBeingDeleted:true})) {
  6822. if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !_jsPlumb.deleteConnection(jpc)) {
  6823. jpc.setHover(false);
  6824. jpc._forceDetach = null;
  6825. jpc._forceReattach = null;
  6826. this._jsPlumb.floatingEndpoint.detachFromConnection(jpc);
  6827. jpc.suspendedEndpoint.addConnection(jpc);
  6828. // TODO this code is duplicated in lots of places...and there is nothing external
  6829. // in the code; it all refers to the connection itself. we could add a
  6830. // `checkSanity(connection)` method to anchorManager that did this.
  6831. if (idx == 1) {
  6832. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
  6833. }
  6834. else {
  6835. _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
  6836. }
  6837. _jsPlumb.repaint(existingJpcParams[1]);
  6838. }
  6839. else {
  6840. _jsPlumb.deleteObject({endpoint: fe});
  6841. }
  6842. }
  6843. }
  6844. // makeTargets sets this flag, to tell us we have been replaced and should delete this object.
  6845. if (this.deleteAfterDragStop) {
  6846. _jsPlumb.deleteObject({endpoint: this});
  6847. }
  6848. else {
  6849. if (this._jsPlumb) {
  6850. this.paint({recalc: false});
  6851. }
  6852. }
  6853. // although the connection is no longer valid, there are use cases where this is useful.
  6854. _jsPlumb.fire("connectionDragStop", jpc, originalEvent);
  6855. // fire this event to give people more fine-grained control (connectionDragStop fires a lot)
  6856. if (jpc.pending) {
  6857. _jsPlumb.fire("connectionAborted", jpc, originalEvent);
  6858. }
  6859. // tell jsplumb that dragging is finished.
  6860. _jsPlumb.currentlyDragging = false;
  6861. jpc.suspendedElement = null;
  6862. jpc.suspendedEndpoint = null;
  6863. jpc = null;
  6864. }
  6865. // if no endpoints, jpc already cleaned up. but still we want to ensure we're reset properly.
  6866. // remove the element associated with the floating endpoint
  6867. // (and its associated floating endpoint and visual artefacts)
  6868. if (placeholderInfo && placeholderInfo.element) {
  6869. _jsPlumb.remove(placeholderInfo.element, false, false);
  6870. }
  6871. // remove the inplace copy
  6872. if (inPlaceCopy) {
  6873. _jsPlumb.deleteObject({endpoint: inPlaceCopy});
  6874. }
  6875. if (this._jsPlumb) {
  6876. // make our canvas visible (TODO: hand off to library; we should not know about DOM)
  6877. this.canvas.style.visibility = "visible";
  6878. // unlock our anchor
  6879. this.anchor.locked = false;
  6880. // clear floating anchor.
  6881. this._jsPlumb.floatingEndpoint = null;
  6882. }
  6883. }.bind(this);
  6884. dragOptions = _jp.extend(defaultOpts, dragOptions);
  6885. dragOptions.scope = this.scope || dragOptions.scope;
  6886. dragOptions[beforeStartEvent] = _ju.wrap(dragOptions[beforeStartEvent], beforeStart, false);
  6887. dragOptions[startEvent] = _ju.wrap(dragOptions[startEvent], start, false);
  6888. // extracted drag handler function so can be used by makeSource
  6889. dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], _dragHandler.drag);
  6890. dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], stop);
  6891. dragOptions.multipleDrop = false;
  6892. dragOptions.canDrag = function () {
  6893. return this.isSource || this.isTemporarySource || /*(this.isTarget && */this.connections.length > 0/*)*/;
  6894. }.bind(this);
  6895. _jsPlumb.initDraggable(this.canvas, dragOptions, "internal");
  6896. this.canvas._jsPlumbRelatedElement = this.element;
  6897. draggingInitialised = true;
  6898. }
  6899. };
  6900. var ep = params.endpoint || this._jsPlumb.instance.Defaults.Endpoint || _jp.Defaults.Endpoint;
  6901. this.setEndpoint(ep, true);
  6902. var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top");
  6903. this.setAnchor(anchorParamsToUse, true);
  6904. // finally, set type if it was provided
  6905. var type = [ "default", (params.type || "")].join(" ");
  6906. this.addType(type, params.data, true);
  6907. this.canvas = this.endpoint.canvas;
  6908. this.canvas._jsPlumb = this;
  6909. this.initDraggable();
  6910. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  6911. // back onto the endpoint you detached it from.
  6912. var _initDropTarget = function (canvas, isTransient, endpoint, referenceEndpoint) {
  6913. if (_jp.isDropSupported(this.element)) {
  6914. var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || _jp.Defaults.DropOptions;
  6915. dropOptions = _jp.extend({}, dropOptions);
  6916. dropOptions.scope = dropOptions.scope || this.scope;
  6917. var dropEvent = _jp.dragEvents.drop,
  6918. overEvent = _jp.dragEvents.over,
  6919. outEvent = _jp.dragEvents.out,
  6920. _ep = this,
  6921. drop = _jsPlumb.EndpointDropHandler({
  6922. getEndpoint: function () {
  6923. return _ep;
  6924. },
  6925. jsPlumb: _jsPlumb,
  6926. enabled: function () {
  6927. return endpoint != null ? endpoint.isEnabled() : true;
  6928. },
  6929. isFull: function () {
  6930. return endpoint.isFull();
  6931. },
  6932. element: this.element,
  6933. elementId: this.elementId,
  6934. isSource: this.isSource,
  6935. isTarget: this.isTarget,
  6936. addClass: function (clazz) {
  6937. _ep.addClass(clazz);
  6938. },
  6939. removeClass: function (clazz) {
  6940. _ep.removeClass(clazz);
  6941. },
  6942. isDropAllowed: function () {
  6943. return _ep.isDropAllowed.apply(_ep, arguments);
  6944. },
  6945. reference:referenceEndpoint,
  6946. isRedrop:function(jpc, dhParams) {
  6947. return jpc.suspendedEndpoint && dhParams.reference && (jpc.suspendedEndpoint.id === dhParams.reference.id);
  6948. }
  6949. });
  6950. dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], drop, true);
  6951. dropOptions[overEvent] = _ju.wrap(dropOptions[overEvent], function () {
  6952. var draggable = _jp.getDragObject(arguments),
  6953. id = _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
  6954. _jpc = _jsPlumb.floatingConnections[id];
  6955. if (_jpc != null) {
  6956. var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
  6957. // here we should fire the 'over' event if we are a target and this is a new connection,
  6958. // or we are the same as the floating endpoint.
  6959. var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id == _jpc.suspendedEndpoint.id);
  6960. if (_cont) {
  6961. var bb = _jsPlumb.checkCondition("checkDropAllowed", {
  6962. sourceEndpoint: _jpc.endpoints[idx],
  6963. targetEndpoint: this,
  6964. connection: _jpc
  6965. });
  6966. this[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass);
  6967. this[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass);
  6968. _jpc.endpoints[idx].anchor.over(this.anchor, this);
  6969. }
  6970. }
  6971. }.bind(this));
  6972. dropOptions[outEvent] = _ju.wrap(dropOptions[outEvent], function () {
  6973. var draggable = _jp.getDragObject(arguments),
  6974. id = draggable == null ? null : _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
  6975. _jpc = id ? _jsPlumb.floatingConnections[id] : null;
  6976. if (_jpc != null) {
  6977. var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
  6978. var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id == _jpc.suspendedEndpoint.id);
  6979. if (_cont) {
  6980. this.removeClass(_jsPlumb.endpointDropAllowedClass);
  6981. this.removeClass(_jsPlumb.endpointDropForbiddenClass);
  6982. _jpc.endpoints[idx].anchor.out();
  6983. }
  6984. }
  6985. }.bind(this));
  6986. _jsPlumb.initDroppable(canvas, dropOptions, "internal", isTransient);
  6987. }
  6988. }.bind(this);
  6989. // Initialise the endpoint's canvas as a drop target. The drop handler will take care of the logic of whether
  6990. // something can actually be dropped.
  6991. if (!this.anchor.isFloating)
  6992. _initDropTarget(this.canvas, !(params._transient || this.anchor.isFloating), this, params.reference);
  6993. return this;
  6994. };
  6995. _ju.extend(_jp.Endpoint, _jp.OverlayCapableJsPlumbUIComponent, {
  6996. setVisible: function (v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  6997. this._jsPlumb.visible = v;
  6998. if (this.canvas) this.canvas.style.display = v ? "block" : "none";
  6999. this[v ? "showOverlays" : "hideOverlays"]();
  7000. if (!doNotChangeConnections) {
  7001. for (var i = 0; i < this.connections.length; i++) {
  7002. this.connections[i].setVisible(v);
  7003. if (!doNotNotifyOtherEndpoint) {
  7004. var oIdx = this === this.connections[i].endpoints[0] ? 1 : 0;
  7005. // only change the other endpoint if this is its only connection.
  7006. if (this.connections[i].endpoints[oIdx].connections.length == 1) this.connections[i].endpoints[oIdx].setVisible(v, true, true);
  7007. }
  7008. }
  7009. }
  7010. },
  7011. getAttachedElements: function () {
  7012. return this.connections;
  7013. },
  7014. applyType: function (t, doNotRepaint) {
  7015. this.setPaintStyle(t.endpointStyle || t.paintStyle, doNotRepaint);
  7016. this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle, doNotRepaint);
  7017. if (t.maxConnections != null) this._jsPlumb.maxConnections = t.maxConnections;
  7018. if (t.scope) this.scope = t.scope;
  7019. _jp.extend(this, t, typeParameters);
  7020. if (t.cssClass != null && this.canvas) this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
  7021. _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
  7022. },
  7023. isEnabled: function () {
  7024. return this._jsPlumb.enabled;
  7025. },
  7026. setEnabled: function (e) {
  7027. this._jsPlumb.enabled = e;
  7028. },
  7029. cleanup: function () {
  7030. var anchorClass = this._jsPlumb.instance.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
  7031. _jp.removeClass(this.element, anchorClass);
  7032. this.anchor = null;
  7033. this.endpoint.cleanup(true);
  7034. this.endpoint.destroy();
  7035. this.endpoint = null;
  7036. // drag/drop
  7037. this._jsPlumb.instance.destroyDraggable(this.canvas, "internal");
  7038. this._jsPlumb.instance.destroyDroppable(this.canvas, "internal");
  7039. },
  7040. setHover: function (h) {
  7041. if (this.endpoint && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged())
  7042. this.endpoint.setHover(h);
  7043. },
  7044. isFull: function () {
  7045. return this._jsPlumb.maxConnections === 0 ? true : !(this.isFloating() || this._jsPlumb.maxConnections < 0 || this.connections.length < this._jsPlumb.maxConnections);
  7046. },
  7047. /**
  7048. * private but needs to be exposed.
  7049. */
  7050. isFloating: function () {
  7051. return this.anchor != null && this.anchor.isFloating;
  7052. },
  7053. isConnectedTo: function (endpoint) {
  7054. var found = false;
  7055. if (endpoint) {
  7056. for (var i = 0; i < this.connections.length; i++) {
  7057. if (this.connections[i].endpoints[1] == endpoint || this.connections[i].endpoints[0] == endpoint) {
  7058. found = true;
  7059. break;
  7060. }
  7061. }
  7062. }
  7063. return found;
  7064. },
  7065. getConnectionCost: function () {
  7066. return this._jsPlumb.connectionCost;
  7067. },
  7068. setConnectionCost: function (c) {
  7069. this._jsPlumb.connectionCost = c;
  7070. },
  7071. areConnectionsDirected: function () {
  7072. return this._jsPlumb.connectionsDirected;
  7073. },
  7074. setConnectionsDirected: function (b) {
  7075. this._jsPlumb.connectionsDirected = b;
  7076. },
  7077. setElementId: function (_elId) {
  7078. this.elementId = _elId;
  7079. this.anchor.elementId = _elId;
  7080. },
  7081. setReferenceElement: function (_el) {
  7082. this.element = _jp.getElement(_el);
  7083. },
  7084. setDragAllowedWhenFull: function (allowed) {
  7085. this.dragAllowedWhenFull = allowed;
  7086. },
  7087. equals: function (endpoint) {
  7088. return this.anchor.equals(endpoint.anchor);
  7089. },
  7090. getUuid: function () {
  7091. return this._jsPlumb.uuid;
  7092. },
  7093. computeAnchor: function (params) {
  7094. return this.anchor.compute(params);
  7095. }
  7096. });
  7097. root.jsPlumbInstance.prototype.EndpointDropHandler = function (dhParams) {
  7098. return function (e) {
  7099. var _jsPlumb = dhParams.jsPlumb;
  7100. // remove the classes that are added dynamically. drop is neither forbidden nor allowed now that
  7101. // the drop is finishing.
  7102. dhParams.removeClass(_jsPlumb.endpointDropAllowedClass);
  7103. dhParams.removeClass(_jsPlumb.endpointDropForbiddenClass);
  7104. var originalEvent = _jsPlumb.getDropEvent(arguments),
  7105. draggable = _jsPlumb.getDragObject(arguments),
  7106. id = _jsPlumb.getAttribute(draggable, "dragId"),
  7107. elId = _jsPlumb.getAttribute(draggable, "elId"),
  7108. scope = _jsPlumb.getAttribute(draggable, "originalScope"),
  7109. jpc = _jsPlumb.floatingConnections[id];
  7110. // if no active connection, bail.
  7111. if (jpc == null) return;
  7112. // calculate if this is an existing connection.
  7113. var existingConnection = jpc.suspendedEndpoint != null;
  7114. // if suspended endpoint exists but has been cleaned up, bail. This means it's an existing connection
  7115. // that has been detached and will shortly be discarded.
  7116. if (existingConnection && jpc.suspendedEndpoint._jsPlumb == null) return;
  7117. // get the drop endpoint. for a normal connection this is just the one that would replace the currently
  7118. // floating endpoint. for a makeTarget this is a new endpoint that is created on drop. But we leave that to
  7119. // the handler to figure out.
  7120. var _ep = dhParams.getEndpoint(jpc);
  7121. // If we're not given an endpoint to use, bail.
  7122. if (_ep == null) return;
  7123. // if this is a drop back where the connection came from, mark it force reattach and
  7124. // return; the stop handler will reattach. without firing an event.
  7125. if (dhParams.isRedrop(jpc, dhParams)) {
  7126. jpc._forceReattach = true;
  7127. jpc.setHover(false);
  7128. if (dhParams.maybeCleanup) dhParams.maybeCleanup(_ep);
  7129. return;
  7130. }
  7131. // ensure we dont bother trying to drop sources on non-source eps, and same for target.
  7132. var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
  7133. if ((idx === 0 && !dhParams.isSource)|| (idx === 1 && !dhParams.isTarget)){
  7134. if (dhParams.maybeCleanup) dhParams.maybeCleanup(_ep);
  7135. return;
  7136. }
  7137. if (dhParams.onDrop) dhParams.onDrop(jpc);
  7138. // restore the original scope if necessary (issue 57)
  7139. if (scope) _jsPlumb.setDragScope(draggable, scope);
  7140. // if the target of the drop is full, fire an event (we abort below)
  7141. // makeTarget: keep.
  7142. var isFull = dhParams.isFull(e);
  7143. if (isFull) {
  7144. _ep.fire("maxConnections", {
  7145. endpoint: this,
  7146. connection: jpc,
  7147. maxConnections: _ep._jsPlumb.maxConnections
  7148. }, originalEvent);
  7149. }
  7150. //
  7151. // if endpoint enabled, not full, and matches the index of the floating endpoint...
  7152. if (!isFull && dhParams.enabled()) {
  7153. var _doContinue = true;
  7154. // before testing for beforeDrop, reset the connection's source/target to be the actual DOM elements
  7155. // involved (that is, stash any temporary stuff used for dragging. but we need to keep it around in
  7156. // order that the anchor manager can clean things up properly).
  7157. if (idx === 0) {
  7158. jpc.floatingElement = jpc.source;
  7159. jpc.floatingId = jpc.sourceId;
  7160. jpc.floatingEndpoint = jpc.endpoints[0];
  7161. jpc.floatingIndex = 0;
  7162. jpc.source = dhParams.element;
  7163. jpc.sourceId = dhParams.elementId;
  7164. } else {
  7165. jpc.floatingElement = jpc.target;
  7166. jpc.floatingId = jpc.targetId;
  7167. jpc.floatingEndpoint = jpc.endpoints[1];
  7168. jpc.floatingIndex = 1;
  7169. jpc.target = dhParams.element;
  7170. jpc.targetId = dhParams.elementId;
  7171. }
  7172. // if this is an existing connection and detach is not allowed we won't continue. The connection's
  7173. // endpoints have been reinstated; everything is back to how it was.
  7174. if (existingConnection && jpc.suspendedEndpoint.id != _ep.id) {
  7175. if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc))
  7176. _doContinue = false;
  7177. }
  7178. // ------------ wrap the execution path in a function so we can support asynchronous beforeDrop
  7179. var continueFunction = function (optionalData) {
  7180. // remove this jpc from the current endpoint, which is a floating endpoint that we will
  7181. // subsequently discard.
  7182. jpc.endpoints[idx].detachFromConnection(jpc);
  7183. // if there's a suspended endpoint, detach it from the connection.
  7184. if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
  7185. jpc.endpoints[idx] = _ep;
  7186. _ep.addConnection(jpc);
  7187. // copy our parameters in to the connection:
  7188. var params = _ep.getParameters();
  7189. for (var aParam in params)
  7190. jpc.setParameter(aParam, params[aParam]);
  7191. if (!existingConnection) {
  7192. // if not an existing connection and
  7193. if (params.draggable)
  7194. _jsPlumb.initDraggable(this.element, dragOptions, "internal", _jsPlumb);
  7195. }
  7196. else {
  7197. var suspendedElementId = jpc.suspendedEndpoint.elementId;
  7198. _jsPlumb.fireMoveEvent({
  7199. index: idx,
  7200. originalSourceId: idx === 0 ? suspendedElementId : jpc.sourceId,
  7201. newSourceId: idx === 0 ? _ep.elementId : jpc.sourceId,
  7202. originalTargetId: idx == 1 ? suspendedElementId : jpc.targetId,
  7203. newTargetId: idx == 1 ? _ep.elementId : jpc.targetId,
  7204. originalSourceEndpoint: idx === 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  7205. newSourceEndpoint: idx === 0 ? _ep : jpc.endpoints[0],
  7206. originalTargetEndpoint: idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  7207. newTargetEndpoint: idx == 1 ? _ep : jpc.endpoints[1],
  7208. connection: jpc
  7209. }, originalEvent);
  7210. }
  7211. if (idx == 1) {
  7212. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
  7213. }
  7214. else {
  7215. _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
  7216. }
  7217. // when makeSource has uniqueEndpoint:true, we want to create connections with new endpoints
  7218. // that are subsequently deleted. So makeSource sets `finalEndpoint`, which is the Endpoint to
  7219. // which the connection should be attached. The `detachFromConnection` call below results in the
  7220. // temporary endpoint being cleaned up.
  7221. if (jpc.endpoints[0].finalEndpoint) {
  7222. var _toDelete = jpc.endpoints[0];
  7223. _toDelete.detachFromConnection(jpc);
  7224. jpc.endpoints[0] = jpc.endpoints[0].finalEndpoint;
  7225. jpc.endpoints[0].addConnection(jpc);
  7226. }
  7227. // if optionalData was given, merge it onto the connection's data.
  7228. if (_ju.isObject(optionalData)) {
  7229. jpc.mergeData(optionalData);
  7230. }
  7231. // finalise will inform the anchor manager and also add to
  7232. // connectionsByScope if necessary.
  7233. _jsPlumb.finaliseConnection(jpc, null, originalEvent, false);
  7234. jpc.setHover(false);
  7235. }.bind(this);
  7236. var dontContinueFunction = function () {
  7237. // otherwise just put it back on the endpoint it was on before the drag.
  7238. if (jpc.suspendedEndpoint) {
  7239. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  7240. jpc.setHover(false);
  7241. jpc._forceDetach = true;
  7242. if (idx === 0) {
  7243. jpc.source = jpc.suspendedEndpoint.element;
  7244. jpc.sourceId = jpc.suspendedEndpoint.elementId;
  7245. } else {
  7246. jpc.target = jpc.suspendedEndpoint.element;
  7247. jpc.targetId = jpc.suspendedEndpoint.elementId;
  7248. }
  7249. jpc.suspendedEndpoint.addConnection(jpc);
  7250. // TODO checkSanity
  7251. if (idx == 1) {
  7252. _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
  7253. }
  7254. else {
  7255. _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
  7256. }
  7257. _jsPlumb.repaint(jpc.sourceId);
  7258. jpc._forceDetach = false;
  7259. }
  7260. };
  7261. // --------------------------------------
  7262. // now check beforeDrop. this will be available only on Endpoints that are setup to
  7263. // have a beforeDrop condition (although, secretly, under the hood all Endpoints and
  7264. // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
  7265. // it only makes sense to have it on a target endpoint.
  7266. _doContinue = _doContinue && dhParams.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, _ep);// && jpc.pending;
  7267. if (_doContinue) {
  7268. continueFunction(_doContinue);
  7269. return true;
  7270. }
  7271. else {
  7272. dontContinueFunction();
  7273. }
  7274. }
  7275. if (dhParams.maybeCleanup) dhParams.maybeCleanup(_ep);
  7276. _jsPlumb.currentlyDragging = false;
  7277. };
  7278. };
  7279. }).call(typeof window !== 'undefined' ? window : this);
  7280. /*
  7281. * jsPlumb
  7282. *
  7283. * Title:jsPlumb 2.3.0
  7284. *
  7285. * Provides a way to visually connect elements on an HTML page, using SVG.
  7286. *
  7287. * This file contains the code for Connections.
  7288. *
  7289. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  7290. *
  7291. * https://jsplumbtoolkit.com
  7292. * http://github.com/sporritt/jsplumb
  7293. *
  7294. * Dual licensed under the MIT and GPL2 licenses.
  7295. */
  7296. ;
  7297. (function () {
  7298. "use strict";
  7299. var root = this,
  7300. _jp = root.jsPlumb,
  7301. _ju = root.jsPlumbUtil;
  7302. var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) {
  7303. if (!_jsPlumb.Defaults.DoNotThrowErrors && _jp.Connectors[renderMode][connectorName] == null)
  7304. throw { msg: "jsPlumb: unknown connector type '" + connectorName + "'" };
  7305. return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent);
  7306. },
  7307. _makeAnchor = function (anchorParams, elementId, _jsPlumb) {
  7308. return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null;
  7309. },
  7310. _updateConnectedClass = function (conn, element, _jsPlumb, remove) {
  7311. if (element != null) {
  7312. element._jsPlumbConnections = element._jsPlumbConnections || {};
  7313. if (remove)
  7314. delete element._jsPlumbConnections[conn.id];
  7315. else
  7316. element._jsPlumbConnections[conn.id] = true;
  7317. if (_ju.isEmpty(element._jsPlumbConnections)) {
  7318. _jsPlumb.removeClass(element, _jsPlumb.connectedClass);
  7319. }
  7320. else
  7321. _jsPlumb.addClass(element, _jsPlumb.connectedClass);
  7322. }
  7323. };
  7324. _jp.Connection = function (params) {
  7325. var _newEndpoint = params.newEndpoint;
  7326. this.id = params.id;
  7327. this.connector = null;
  7328. this.idPrefix = "_jsplumb_c_";
  7329. this.defaultLabelLocation = 0.5;
  7330. this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
  7331. // if a new connection is the result of moving some existing connection, params.previousConnection
  7332. // will have that Connection in it. listeners for the jsPlumbConnection event can look for that
  7333. // member and take action if they need to.
  7334. this.previousConnection = params.previousConnection;
  7335. this.source = _jp.getElement(params.source);
  7336. this.target = _jp.getElement(params.target);
  7337. // sourceEndpoint and targetEndpoint override source/target, if they are present. but
  7338. // source is not overridden if the Endpoint has declared it is not the final target of a connection;
  7339. // instead we use the source that the Endpoint declares will be the final source element.
  7340. if (params.sourceEndpoint) this.source = params.sourceEndpoint.getElement();
  7341. if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
  7342. _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
  7343. this.sourceId = this._jsPlumb.instance.getId(this.source);
  7344. this.targetId = this._jsPlumb.instance.getId(this.target);
  7345. 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.
  7346. this.endpoints = [];
  7347. this.endpointStyles = [];
  7348. var _jsPlumb = this._jsPlumb.instance;
  7349. _jsPlumb.manage(this.sourceId, this.source);
  7350. _jsPlumb.manage(this.targetId, this.target);
  7351. this._jsPlumb.visible = true;
  7352. this._jsPlumb.editable = params.editable === true;
  7353. this._jsPlumb.params = {
  7354. cssClass: params.cssClass,
  7355. container: params.container,
  7356. "pointer-events": params["pointer-events"],
  7357. editorParams: params.editorParams,
  7358. overlays: params.overlays
  7359. };
  7360. this._jsPlumb.lastPaintedAt = null;
  7361. // listen to mouseover and mouseout events passed from the container delegate.
  7362. this.bind("mouseover", function () {
  7363. this.setHover(true);
  7364. }.bind(this));
  7365. this.bind("mouseout", function () {
  7366. this.setHover(false);
  7367. }.bind(this));
  7368. this.editableRequested = params.editable !== false;
  7369. this.setEditable = function(e) {
  7370. return this.connector ? this.connector.setEditable(e) : false;
  7371. };
  7372. this.isEditable = function() { return this.connector ? this.connector.isEditable() : false; };
  7373. this.isEditing = function() { return this.connector ? this.connector.isEditing() : false; };
  7374. // INITIALISATION CODE
  7375. this.makeEndpoint = function (isSource, el, elId, ep) {
  7376. elId = elId || this._jsPlumb.instance.getId(el);
  7377. return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId);
  7378. };
  7379. // if type given, get the endpoint definitions mapping to that type from the jsplumb instance, and use those.
  7380. // we apply types at the end of this constructor but endpoints are only honoured in a type definition at
  7381. // create time.
  7382. if (params.type) {
  7383. params.endpoints = params.endpoints || this._jsPlumb.instance.deriveEndpointAndAnchorSpec(params.type).endpoints;
  7384. }
  7385. var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint),
  7386. eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint);
  7387. if (eS) _ju.addToList(params.endpointsByElement, this.sourceId, eS);
  7388. if (eT) _ju.addToList(params.endpointsByElement, this.targetId, eT);
  7389. // if scope not set, set it to be the scope for the source endpoint.
  7390. if (!this.scope) this.scope = this.endpoints[0].scope;
  7391. // if explicitly told to (or not to) delete endpoints when empty, override endpoint's preferences
  7392. if (params.deleteEndpointsOnEmpty != null) {
  7393. this.endpoints[0].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
  7394. this.endpoints[1].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
  7395. }
  7396. // else {
  7397. // // otherwise, unless the endpoints say otherwise, mark them for deletion.
  7398. // if (!this.endpoints[0]._doNotDeleteOnDetach) this.endpoints[0]._deleteOnDetach = true;
  7399. // if (!this.endpoints[1]._doNotDeleteOnDetach) this.endpoints[1]._deleteOnDetach = true;
  7400. // }
  7401. // -------------------------- DEFAULT TYPE ---------------------------------------------
  7402. // DETACHABLE
  7403. var _detachable = _jsPlumb.Defaults.ConnectionsDetachable;
  7404. if (params.detachable === false) _detachable = false;
  7405. if (this.endpoints[0].connectionsDetachable === false) _detachable = false;
  7406. if (this.endpoints[1].connectionsDetachable === false) _detachable = false;
  7407. // REATTACH
  7408. var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections;
  7409. this.appendToDefaultType({
  7410. detachable: _detachable,
  7411. reattach: _reattach,
  7412. paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || _jp.Defaults.PaintStyle,
  7413. hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || _jp.Defaults.HoverPaintStyle
  7414. });
  7415. var _suspendedAt = _jsPlumb.getSuspendedAt();
  7416. if (!_jsPlumb.isSuspendDrawing()) {
  7417. // paint the endpoints
  7418. var myInfo = _jsPlumb.getCachedData(this.sourceId),
  7419. myOffset = myInfo.o, myWH = myInfo.s,
  7420. otherInfo = _jsPlumb.getCachedData(this.targetId),
  7421. otherOffset = otherInfo.o,
  7422. otherWH = otherInfo.s,
  7423. initialTimestamp = _suspendedAt || _jsPlumb.timestamp(),
  7424. anchorLoc = this.endpoints[0].anchor.compute({
  7425. xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0],
  7426. elementId: this.endpoints[0].elementId,
  7427. txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1],
  7428. timestamp: initialTimestamp
  7429. });
  7430. this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
  7431. anchorLoc = this.endpoints[1].anchor.compute({
  7432. xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1],
  7433. elementId: this.endpoints[1].elementId,
  7434. txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0],
  7435. timestamp: initialTimestamp
  7436. });
  7437. this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
  7438. }
  7439. this.getTypeDescriptor = function () {
  7440. return "connection";
  7441. };
  7442. this.getAttachedElements = function () {
  7443. return this.endpoints;
  7444. };
  7445. this.isDetachable = function () {
  7446. return this._jsPlumb.detachable === true;
  7447. };
  7448. this.setDetachable = function (detachable) {
  7449. this._jsPlumb.detachable = detachable === true;
  7450. };
  7451. this.isReattach = function () {
  7452. return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true;
  7453. };
  7454. this.setReattach = function (reattach) {
  7455. this._jsPlumb.reattach = reattach === true;
  7456. };
  7457. // this["delete"] = function() {
  7458. // this.endpoints[0].detachFromConnection(this);
  7459. // this.endpoints[1].detachFromConnection(this);
  7460. // params.deleteConnection(this);
  7461. // };
  7462. // END INITIALISATION CODE
  7463. // COST + DIRECTIONALITY
  7464. // if cost not supplied, try to inherit from source endpoint
  7465. this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost();
  7466. this._jsPlumb.directed = params.directed;
  7467. // inherit directed flag if set no source endpoint
  7468. if (params.directed == null) this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected();
  7469. // END COST + DIRECTIONALITY
  7470. // PARAMETERS
  7471. // merge all the parameters objects into the connection. parameters set
  7472. // on the connection take precedence; then source endpoint params, then
  7473. // finally target endpoint params.
  7474. var _p = _jp.extend({}, this.endpoints[1].getParameters());
  7475. _jp.extend(_p, this.endpoints[0].getParameters());
  7476. _jp.extend(_p, this.getParameters());
  7477. this.setParameters(_p);
  7478. // END PARAMETERS
  7479. // PAINTING
  7480. this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true);
  7481. if (params.geometry) {
  7482. this.connector.setGeometry(params.geometry);
  7483. }
  7484. var data = params.data == null || !_ju.isObject(params.data) ? {} : params.data;
  7485. this.getData = function() { return data; };
  7486. this.setData = function(d) { data = d || {}; };
  7487. this.mergeData = function(d) { data = _jp.extend(data, d); };
  7488. // the very last thing we do is apply types, if there are any.
  7489. var _types = [ "default", this.endpoints[0].connectionType, this.endpoints[1].connectionType, params.type ].join(" ");
  7490. if (/[^\s]/.test(_types))
  7491. this.addType(_types, params.data, true);
  7492. this.updateConnectedClass();
  7493. // END PAINTING
  7494. };
  7495. _ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, {
  7496. applyType: function (t, doNotRepaint, typeMap) {
  7497. // none of these things result in the creation of objects so can be ignored.
  7498. if (t.detachable != null) this.setDetachable(t.detachable);
  7499. if (t.reattach != null) this.setReattach(t.reattach);
  7500. if (t.scope) this.scope = t.scope;
  7501. if (t.cssClass != null && this.canvas) this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
  7502. var _anchors = null;
  7503. // this also results in the creation of objects.
  7504. if (t.anchor) {
  7505. // note that even if the param was anchor, we store `anchors`.
  7506. _anchors = this.getCachedTypeItem("anchors", typeMap.anchor);
  7507. if (_anchors == null) {
  7508. _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ];
  7509. this.cacheTypeItem("anchors", _anchors, typeMap.anchor);
  7510. }
  7511. }
  7512. else if (t.anchors) {
  7513. _anchors = this.getCachedTypeItem("anchors", typeMap.anchors);
  7514. if (_anchors == null) {
  7515. _anchors = [
  7516. this._jsPlumb.instance.makeAnchor(t.anchors[0]),
  7517. this._jsPlumb.instance.makeAnchor(t.anchors[1])
  7518. ];
  7519. this.cacheTypeItem("anchors", _anchors, typeMap.anchors);
  7520. }
  7521. }
  7522. if (_anchors != null) {
  7523. this.endpoints[0].anchor = _anchors[0];
  7524. this.endpoints[1].anchor = _anchors[1];
  7525. if (this.endpoints[1].anchor.isDynamic) this._jsPlumb.instance.repaint(this.endpoints[1].elementId);
  7526. }
  7527. _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
  7528. },
  7529. addClass: function (c, informEndpoints) {
  7530. if (informEndpoints) {
  7531. this.endpoints[0].addClass(c);
  7532. this.endpoints[1].addClass(c);
  7533. if (this.suspendedEndpoint) this.suspendedEndpoint.addClass(c);
  7534. }
  7535. if (this.connector) {
  7536. this.connector.addClass(c);
  7537. }
  7538. },
  7539. removeClass: function (c, informEndpoints) {
  7540. if (informEndpoints) {
  7541. this.endpoints[0].removeClass(c);
  7542. this.endpoints[1].removeClass(c);
  7543. if (this.suspendedEndpoint) this.suspendedEndpoint.removeClass(c);
  7544. }
  7545. if (this.connector) {
  7546. this.connector.removeClass(c);
  7547. }
  7548. },
  7549. isVisible: function () {
  7550. return this._jsPlumb.visible;
  7551. },
  7552. setVisible: function (v) {
  7553. this._jsPlumb.visible = v;
  7554. if (this.connector)
  7555. this.connector.setVisible(v);
  7556. this.repaint();
  7557. },
  7558. cleanup: function () {
  7559. this.updateConnectedClass(true);
  7560. this.endpoints = null;
  7561. this.source = null;
  7562. this.target = null;
  7563. if (this.connector != null) {
  7564. this.connector.cleanup(true);
  7565. this.connector.destroy(true);
  7566. }
  7567. this.connector = null;
  7568. },
  7569. updateConnectedClass:function(remove) {
  7570. if (this._jsPlumb) {
  7571. _updateConnectedClass(this, this.source, this._jsPlumb.instance, remove);
  7572. _updateConnectedClass(this, this.target, this._jsPlumb.instance, remove);
  7573. }
  7574. },
  7575. setHover: function (state) {
  7576. if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
  7577. this.connector.setHover(state);
  7578. root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass);
  7579. root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass);
  7580. }
  7581. },
  7582. getUuids:function() {
  7583. return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ];
  7584. },
  7585. getCost: function () {
  7586. return this._jsPlumb ? this._jsPlumb.cost : -Infinity;
  7587. },
  7588. setCost: function (c) {
  7589. this._jsPlumb.cost = c;
  7590. },
  7591. isDirected: function () {
  7592. return this._jsPlumb.directed === true;
  7593. },
  7594. getConnector: function () {
  7595. return this.connector;
  7596. },
  7597. getGeometry : function() { return this.connector ? this.connector.getGeometry() : null; },
  7598. setGeometry : function(g) { if (this.connector) this.connector.setGeometry(g); },
  7599. prepareConnector:function(connectorSpec, typeId) {
  7600. var connectorArgs = {
  7601. _jsPlumb: this._jsPlumb.instance,
  7602. cssClass: (this._jsPlumb.params.cssClass || "") + (this.isEditable() ? this._jsPlumb.instance.editableConnectorClass : ""),
  7603. container: this._jsPlumb.params.container,
  7604. "pointer-events": this._jsPlumb.params["pointer-events"],
  7605. editable:this.editableRequested
  7606. },
  7607. renderMode = this._jsPlumb.instance.getRenderMode(),
  7608. connector;
  7609. if (_ju.isString(connectorSpec))
  7610. connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this); // lets you use a string as shorthand.
  7611. else if (_ju.isArray(connectorSpec)) {
  7612. if (connectorSpec.length == 1)
  7613. connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this);
  7614. else
  7615. connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this);
  7616. }
  7617. if (typeId != null) connector.typeId = typeId;
  7618. return connector;
  7619. },
  7620. setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) {
  7621. var previous, previousClasses = "";
  7622. // the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it
  7623. // and we havent passed in `true` for "force" here.
  7624. if (this.connector != null) {
  7625. previous = this.connector;
  7626. previousClasses = previous.getClass();
  7627. this.connector.cleanup();
  7628. this.connector.destroy();
  7629. }
  7630. this.connector = connector;
  7631. if (typeId) {
  7632. this.cacheTypeItem("connector", connector, typeId);
  7633. }
  7634. this.canvas = this.connector.canvas;
  7635. this.bgCanvas = this.connector.bgCanvas;
  7636. // put classes from prior connector onto the canvas
  7637. this.addClass(previousClasses);
  7638. // new: instead of binding listeners per connector, we now just have one delegate on the container.
  7639. // so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and
  7640. // bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards.
  7641. if (this.canvas) this.canvas._jsPlumb = this;
  7642. if (this.bgCanvas) this.bgCanvas._jsPlumb = this;
  7643. if (previous != null) {
  7644. var o = this.getOverlays();
  7645. for (var i = 0; i < o.length; i++) {
  7646. if (o[i].transfer) o[i].transfer(this.connector);
  7647. }
  7648. }
  7649. if (!doNotChangeListenerComponent) this.setListenerComponent(this.connector);
  7650. if (!doNotRepaint) this.repaint();
  7651. },
  7652. setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) {
  7653. var connector = this.prepareConnector(connectorSpec, typeId);
  7654. this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId);
  7655. },
  7656. paint: function (params) {
  7657. if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) {
  7658. params = params || {};
  7659. var timestamp = params.timestamp,
  7660. // if the moving object is not the source we must transpose the two references.
  7661. swap = false,
  7662. tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
  7663. tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  7664. if (timestamp == null || timestamp != this._jsPlumb.lastPaintedAt) {
  7665. var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o,
  7666. targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o,
  7667. sE = this.endpoints[sIdx], tE = this.endpoints[tIdx];
  7668. var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}),
  7669. tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp});
  7670. this.connector.resetBounds();
  7671. this.connector.compute({
  7672. sourcePos: sAnchorP,
  7673. targetPos: tAnchorP,
  7674. sourceEndpoint: this.endpoints[sIdx],
  7675. targetEndpoint: this.endpoints[tIdx],
  7676. "stroke-width": this._jsPlumb.paintStyleInUse.strokeWidth,
  7677. sourceInfo: sourceInfo,
  7678. targetInfo: targetInfo
  7679. });
  7680. var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
  7681. // compute overlays. we do this first so we can get their placements, and adjust the
  7682. // container if needs be (if an overlay would be clipped)
  7683. for (var i in this._jsPlumb.overlays) {
  7684. if (this._jsPlumb.overlays.hasOwnProperty(i)) {
  7685. var o = this._jsPlumb.overlays[i];
  7686. if (o.isVisible()) {
  7687. this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o));
  7688. overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX);
  7689. overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX);
  7690. overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY);
  7691. overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY);
  7692. }
  7693. }
  7694. }
  7695. var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 1) / 2,
  7696. outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 0),
  7697. extents = {
  7698. xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX),
  7699. ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY),
  7700. xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX),
  7701. ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY)
  7702. };
  7703. // paint the connector.
  7704. this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents);
  7705. // and then the overlays
  7706. for (var j in this._jsPlumb.overlays) {
  7707. if (this._jsPlumb.overlays.hasOwnProperty(j)) {
  7708. var p = this._jsPlumb.overlays[j];
  7709. if (p.isVisible()) {
  7710. p.paint(this._jsPlumb.overlayPlacements[j], extents);
  7711. }
  7712. }
  7713. }
  7714. }
  7715. this._jsPlumb.lastPaintedAt = timestamp;
  7716. }
  7717. },
  7718. repaint: function (params) {
  7719. params = params || {};
  7720. this.paint({ elId: this.sourceId, recalc: !(params.recalc === false), timestamp: params.timestamp});
  7721. },
  7722. prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) {
  7723. var e;
  7724. if (existing) {
  7725. conn.endpoints[index] = existing;
  7726. existing.addConnection(conn);
  7727. } else {
  7728. if (!params.endpoints) params.endpoints = [ null, null ];
  7729. var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || _jp.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || _jp.Defaults.Endpoint;
  7730. if (!params.endpointStyles) params.endpointStyles = [ null, null ];
  7731. if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
  7732. var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || _jp.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle;
  7733. // Endpoints derive their fill from the connector's stroke, if no fill was specified.
  7734. if (es.fill == null && params.paintStyle != null)
  7735. es.fill = params.paintStyle.stroke;
  7736. if (es.outlineStroke == null && params.paintStyle != null)
  7737. es.outlineStroke = params.paintStyle.outlineStroke;
  7738. if (es.outlineWidth == null && params.paintStyle != null)
  7739. es.outlineWidth = params.paintStyle.outlineWidth;
  7740. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || _jp.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle;
  7741. // endpoint hover fill style is derived from connector's hover stroke style
  7742. if (params.hoverPaintStyle != null) {
  7743. if (ehs == null) ehs = {};
  7744. if (ehs.fill == null) {
  7745. ehs.fill = params.hoverPaintStyle.stroke;
  7746. }
  7747. }
  7748. var a = params.anchors ? params.anchors[index] :
  7749. params.anchor ? params.anchor :
  7750. _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) ||
  7751. _makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) ||
  7752. _makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) ||
  7753. _makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb),
  7754. u = params.uuids ? params.uuids[index] : null;
  7755. e = _newEndpoint({
  7756. paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ],
  7757. uuid: u, anchor: a, source: element, scope: params.scope,
  7758. reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections,
  7759. detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable
  7760. });
  7761. if (existing == null) {
  7762. e.setDeleteOnEmpty(true);
  7763. }
  7764. conn.endpoints[index] = e;
  7765. if (params.drawEndpoints === false) e.setVisible(false, true, true);
  7766. }
  7767. return e;
  7768. }
  7769. }); // END Connection class
  7770. }).call(typeof window !== 'undefined' ? window : this);
  7771. /*
  7772. * jsPlumb
  7773. *
  7774. * Title:jsPlumb 2.3.0
  7775. *
  7776. * Provides a way to visually connect elements on an HTML page, using SVG.
  7777. *
  7778. * This file contains the code for creating and manipulating anchors.
  7779. *
  7780. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  7781. *
  7782. * http://jsplumbtoolkit.com
  7783. * http://github.com/sporritt/jsplumb
  7784. *
  7785. * Dual licensed under the MIT and GPL2 licenses.
  7786. */
  7787. ;
  7788. (function () {
  7789. "use strict";
  7790. var root = this,
  7791. _ju = root.jsPlumbUtil,
  7792. _jp = root.jsPlumb;
  7793. //
  7794. // manages anchors for all elements.
  7795. //
  7796. _jp.AnchorManager = function (params) {
  7797. var _amEndpoints = {},
  7798. continuousAnchorLocations = {},
  7799. userDefinedContinuousAnchorLocations = {},
  7800. continuousAnchorOrientations = {},
  7801. Orientation = { HORIZONTAL: "horizontal", VERTICAL: "vertical", DIAGONAL: "diagonal", IDENTITY: "identity" },
  7802. axes = ["left", "top", "right", "bottom"],
  7803. connectionsByElementId = {},
  7804. self = this,
  7805. anchorLists = {},
  7806. jsPlumbInstance = params.jsPlumbInstance,
  7807. floatingConnections = {},
  7808. calculateOrientation = function (sourceId, targetId, sd, td, sourceAnchor, targetAnchor) {
  7809. if (sourceId === targetId) return {
  7810. orientation: Orientation.IDENTITY,
  7811. a: ["top", "top"]
  7812. };
  7813. var theta = Math.atan2((td.centery - sd.centery), (td.centerx - sd.centerx)),
  7814. theta2 = Math.atan2((sd.centery - td.centery), (sd.centerx - td.centerx));
  7815. // --------------------------------------------------------------------------------------
  7816. // improved face calculation. get midpoints of each face for source and target, then put in an array with all combinations of
  7817. // source/target faces. sort this array by distance between midpoints. the entry at index 0 is our preferred option. we can
  7818. // go through the array one by one until we find an entry in which each requested face is supported.
  7819. var candidates = [], midpoints = { };
  7820. (function (types, dim) {
  7821. for (var i = 0; i < types.length; i++) {
  7822. midpoints[types[i]] = {
  7823. "left": [ dim[i].left, dim[i].centery ],
  7824. "right": [ dim[i].right, dim[i].centery ],
  7825. "top": [ dim[i].centerx, dim[i].top ],
  7826. "bottom": [ dim[i].centerx , dim[i].bottom]
  7827. };
  7828. }
  7829. })([ "source", "target" ], [ sd, td ]);
  7830. for (var sf = 0; sf < axes.length; sf++) {
  7831. for (var tf = 0; tf < axes.length; tf++) {
  7832. candidates.push({
  7833. source: axes[sf],
  7834. target: axes[tf],
  7835. dist: Biltong.lineLength(midpoints.source[axes[sf]], midpoints.target[axes[tf]])
  7836. });
  7837. }
  7838. }
  7839. candidates.sort(function (a, b) {
  7840. return a.dist < b.dist ? -1 : a.dist > b.dist ? 1 : 0;
  7841. });
  7842. // now go through this list and try to get an entry that satisfies both (there will be one, unless one of the anchors
  7843. // declares no available faces)
  7844. var sourceEdge = candidates[0].source, targetEdge = candidates[0].target;
  7845. for (var i = 0; i < candidates.length; i++) {
  7846. if (!sourceAnchor.isContinuous || sourceAnchor.isEdgeSupported(candidates[i].source))
  7847. sourceEdge = candidates[i].source;
  7848. else
  7849. sourceEdge = null;
  7850. if (!targetAnchor.isContinuous || targetAnchor.isEdgeSupported(candidates[i].target))
  7851. targetEdge = candidates[i].target;
  7852. else {
  7853. targetEdge = null;
  7854. }
  7855. if (sourceEdge != null && targetEdge != null) break;
  7856. }
  7857. // --------------------------------------------------------------------------------------
  7858. return {
  7859. a: [ sourceEdge, targetEdge ],
  7860. theta: theta,
  7861. theta2: theta2
  7862. };
  7863. },
  7864. // used by placeAnchors function
  7865. placeAnchorsOnLine = function (desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) {
  7866. var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
  7867. for (var i = 0; i < connections.length; i++) {
  7868. var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
  7869. if (reverse)
  7870. val = elementDimensions[horizontal ? 0 : 1] - val;
  7871. var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
  7872. dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
  7873. a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
  7874. }
  7875. return a;
  7876. },
  7877. // used by edgeSortFunctions
  7878. currySort = function (reverseAngles) {
  7879. return function (a, b) {
  7880. var r = true;
  7881. if (reverseAngles) {
  7882. r = a[0][0] < b[0][0];
  7883. }
  7884. else {
  7885. r = a[0][0] > b[0][0];
  7886. }
  7887. return r === false ? -1 : 1;
  7888. };
  7889. },
  7890. // used by edgeSortFunctions
  7891. leftSort = function (a, b) {
  7892. // first get adjusted values
  7893. var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
  7894. p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
  7895. if (p1 > p2) return 1;
  7896. else return -1;
  7897. },
  7898. // used by placeAnchors
  7899. edgeSortFunctions = {
  7900. "top": function (a, b) {
  7901. return a[0] > b[0] ? 1 : -1;
  7902. },
  7903. "right": currySort(true),
  7904. "bottom": currySort(true),
  7905. "left": leftSort
  7906. },
  7907. // used by placeAnchors
  7908. _sortHelper = function (_array, _fn) {
  7909. return _array.sort(_fn);
  7910. },
  7911. // used by AnchorManager.redraw
  7912. placeAnchors = function (elementId, _anchorLists) {
  7913. var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o,
  7914. placeSomeAnchors = function (desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) {
  7915. if (unsortedConnections.length > 0) {
  7916. var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
  7917. reverse = desc === "right" || desc === "top",
  7918. anchors = placeAnchorsOnLine(desc, elementDimensions,
  7919. elementPosition, sc,
  7920. isHorizontal, otherMultiplier, reverse);
  7921. // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
  7922. var _setAnchorLocation = function (endpoint, anchorPos) {
  7923. continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ];
  7924. continuousAnchorOrientations[endpoint.id] = orientation;
  7925. };
  7926. for (var i = 0; i < anchors.length; i++) {
  7927. var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
  7928. if (weAreSource)
  7929. _setAnchorLocation(c.endpoints[0], anchors[i]);
  7930. if (weAreTarget)
  7931. _setAnchorLocation(c.endpoints[1], anchors[i]);
  7932. }
  7933. }
  7934. };
  7935. placeSomeAnchors("bottom", sS, [sO.left, sO.top], _anchorLists.bottom, true, 1, [0, 1]);
  7936. placeSomeAnchors("top", sS, [sO.left, sO.top], _anchorLists.top, true, 0, [0, -1]);
  7937. placeSomeAnchors("left", sS, [sO.left, sO.top], _anchorLists.left, false, 0, [-1, 0]);
  7938. placeSomeAnchors("right", sS, [sO.left, sO.top], _anchorLists.right, false, 1, [1, 0]);
  7939. };
  7940. this.reset = function () {
  7941. _amEndpoints = {};
  7942. connectionsByElementId = {};
  7943. anchorLists = {};
  7944. };
  7945. this.addFloatingConnection = function (key, conn) {
  7946. floatingConnections[key] = conn;
  7947. };
  7948. this.removeFloatingConnection = function (key) {
  7949. delete floatingConnections[key];
  7950. };
  7951. this.newConnection = function (conn) {
  7952. var sourceId = conn.sourceId, targetId = conn.targetId,
  7953. ep = conn.endpoints,
  7954. doRegisterTarget = true,
  7955. registerConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
  7956. if ((sourceId == targetId) && otherAnchor.isContinuous) {
  7957. // remove the target endpoint's canvas. we dont need it.
  7958. conn._jsPlumb.instance.removeElement(ep[1].canvas);
  7959. doRegisterTarget = false;
  7960. }
  7961. _ju.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor == _jp.DynamicAnchor]);
  7962. };
  7963. registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
  7964. if (doRegisterTarget)
  7965. registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
  7966. };
  7967. var removeEndpointFromAnchorLists = function (endpoint) {
  7968. (function (list, eId) {
  7969. if (list) { // transient anchors dont get entries in this list.
  7970. var f = function (e) {
  7971. return e[4] == eId;
  7972. };
  7973. _ju.removeWithFunction(list.top, f);
  7974. _ju.removeWithFunction(list.left, f);
  7975. _ju.removeWithFunction(list.bottom, f);
  7976. _ju.removeWithFunction(list.right, f);
  7977. }
  7978. })(anchorLists[endpoint.elementId], endpoint.id);
  7979. };
  7980. this.connectionDetached = function (connInfo, doNotRedraw) {
  7981. var connection = connInfo.connection || connInfo,
  7982. sourceId = connInfo.sourceId,
  7983. targetId = connInfo.targetId,
  7984. ep = connection.endpoints,
  7985. removeConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
  7986. _ju.removeWithFunction(connectionsByElementId[elId], function (_c) {
  7987. return _c[0].id == c.id;
  7988. });
  7989. };
  7990. removeConnection(1, ep[1], ep[1].anchor, sourceId, connection);
  7991. removeConnection(0, ep[0], ep[0].anchor, targetId, connection);
  7992. if (connection.floatingId) {
  7993. removeConnection(connection.floatingIndex, connection.floatingEndpoint, connection.floatingEndpoint.anchor, connection.floatingId, connection);
  7994. removeEndpointFromAnchorLists(connection.floatingEndpoint);
  7995. }
  7996. // remove from anchorLists
  7997. removeEndpointFromAnchorLists(connection.endpoints[0]);
  7998. removeEndpointFromAnchorLists(connection.endpoints[1]);
  7999. if (!doNotRedraw) {
  8000. self.redraw(connection.sourceId);
  8001. if (connection.targetId !== connection.sourceId)
  8002. self.redraw(connection.targetId);
  8003. }
  8004. };
  8005. this.add = function (endpoint, elementId) {
  8006. _ju.addToList(_amEndpoints, elementId, endpoint);
  8007. };
  8008. this.changeId = function (oldId, newId) {
  8009. connectionsByElementId[newId] = connectionsByElementId[oldId];
  8010. _amEndpoints[newId] = _amEndpoints[oldId];
  8011. delete connectionsByElementId[oldId];
  8012. delete _amEndpoints[oldId];
  8013. };
  8014. this.getConnectionsFor = function (elementId) {
  8015. return connectionsByElementId[elementId] || [];
  8016. };
  8017. this.getEndpointsFor = function (elementId) {
  8018. return _amEndpoints[elementId] || [];
  8019. };
  8020. this.deleteEndpoint = function (endpoint) {
  8021. _ju.removeWithFunction(_amEndpoints[endpoint.elementId], function (e) {
  8022. return e.id == endpoint.id;
  8023. });
  8024. removeEndpointFromAnchorLists(endpoint);
  8025. };
  8026. this.clearFor = function (elementId) {
  8027. delete _amEndpoints[elementId];
  8028. _amEndpoints[elementId] = [];
  8029. };
  8030. // updates the given anchor list by either updating an existing anchor's info, or adding it. this function
  8031. // also removes the anchor from its previous list, if the edge it is on has changed.
  8032. // all connections found along the way (those that are connected to one of the faces this function
  8033. // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
  8034. // them wthout having to calculate anything else about them.
  8035. var _updateAnchorList = function (lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
  8036. // first try to find the exact match, but keep track of the first index of a matching element id along the way.s
  8037. var exactIdx = -1,
  8038. firstMatchingElIdx = -1,
  8039. endpoint = conn.endpoints[idx],
  8040. endpointId = endpoint.id,
  8041. oIdx = [1, 0][idx],
  8042. values = [
  8043. [ theta, order ],
  8044. conn,
  8045. aBoolean,
  8046. otherElId,
  8047. endpointId
  8048. ],
  8049. listToAddTo = lists[edgeId],
  8050. listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null,
  8051. i,
  8052. candidate;
  8053. if (listToRemoveFrom) {
  8054. var rIdx = _ju.findWithFunction(listToRemoveFrom, function (e) {
  8055. return e[4] == endpointId;
  8056. });
  8057. if (rIdx != -1) {
  8058. listToRemoveFrom.splice(rIdx, 1);
  8059. // get all connections from this list
  8060. for (i = 0; i < listToRemoveFrom.length; i++) {
  8061. candidate = listToRemoveFrom[i][1];
  8062. _ju.addWithFunction(connsToPaint, candidate, function (c) {
  8063. return c.id == candidate.id;
  8064. });
  8065. _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function (e) {
  8066. return e.id == candidate.endpoints[idx].id;
  8067. });
  8068. _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function (e) {
  8069. return e.id == candidate.endpoints[oIdx].id;
  8070. });
  8071. }
  8072. }
  8073. }
  8074. for (i = 0; i < listToAddTo.length; i++) {
  8075. candidate = listToAddTo[i][1];
  8076. if (params.idx == 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx == -1)
  8077. firstMatchingElIdx = i;
  8078. _ju.addWithFunction(connsToPaint, candidate, function (c) {
  8079. return c.id == candidate.id;
  8080. });
  8081. _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function (e) {
  8082. return e.id == candidate.endpoints[idx].id;
  8083. });
  8084. _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function (e) {
  8085. return e.id == candidate.endpoints[oIdx].id;
  8086. });
  8087. }
  8088. if (exactIdx != -1) {
  8089. listToAddTo[exactIdx] = values;
  8090. }
  8091. else {
  8092. var insertIdx = reverse ? firstMatchingElIdx != -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
  8093. listToAddTo.splice(insertIdx, 0, values);
  8094. }
  8095. // store this for next time.
  8096. endpoint._continuousAnchorEdge = edgeId;
  8097. };
  8098. //
  8099. // find the entry in an endpoint's list for this connection and update its target endpoint
  8100. // with the current target in the connection.
  8101. // This method and sourceChanged need to be folder into one.
  8102. //
  8103. this.updateOtherEndpoint = function (sourceElId, oldTargetId, newTargetId, connection) {
  8104. var sIndex = _ju.findWithFunction(connectionsByElementId[sourceElId], function (i) {
  8105. return i[0].id === connection.id;
  8106. }),
  8107. tIndex = _ju.findWithFunction(connectionsByElementId[oldTargetId], function (i) {
  8108. return i[0].id === connection.id;
  8109. });
  8110. // update or add data for source
  8111. if (sIndex != -1) {
  8112. connectionsByElementId[sourceElId][sIndex][0] = connection;
  8113. connectionsByElementId[sourceElId][sIndex][1] = connection.endpoints[1];
  8114. connectionsByElementId[sourceElId][sIndex][2] = connection.endpoints[1].anchor.constructor == _jp.DynamicAnchor;
  8115. }
  8116. // remove entry for previous target (if there)
  8117. if (tIndex > -1) {
  8118. connectionsByElementId[oldTargetId].splice(tIndex, 1);
  8119. // add entry for new target
  8120. _ju.addToList(connectionsByElementId, newTargetId, [connection, connection.endpoints[0], connection.endpoints[0].anchor.constructor == _jp.DynamicAnchor]);
  8121. }
  8122. connection.updateConnectedClass();
  8123. };
  8124. //
  8125. // notification that the connection given has changed source from the originalId to the newId.
  8126. // This involves:
  8127. // 1. removing the connection from the list of connections stored for the originalId
  8128. // 2. updating the source information for the target of the connection
  8129. // 3. re-registering the connection in connectionsByElementId with the newId
  8130. //
  8131. this.sourceChanged = function (originalId, newId, connection, newElement) {
  8132. if (originalId !== newId) {
  8133. connection.sourceId = newId;
  8134. connection.source = newElement;
  8135. // remove the entry that points from the old source to the target
  8136. _ju.removeWithFunction(connectionsByElementId[originalId], function (info) {
  8137. return info[0].id === connection.id;
  8138. });
  8139. // find entry for target and update it
  8140. var tIdx = _ju.findWithFunction(connectionsByElementId[connection.targetId], function (i) {
  8141. return i[0].id === connection.id;
  8142. });
  8143. if (tIdx > -1) {
  8144. connectionsByElementId[connection.targetId][tIdx][0] = connection;
  8145. connectionsByElementId[connection.targetId][tIdx][1] = connection.endpoints[0];
  8146. connectionsByElementId[connection.targetId][tIdx][2] = connection.endpoints[0].anchor.constructor == _jp.DynamicAnchor;
  8147. }
  8148. // add entry for new source
  8149. _ju.addToList(connectionsByElementId, newId, [connection, connection.endpoints[1], connection.endpoints[1].anchor.constructor == _jp.DynamicAnchor]);
  8150. // TODO SP not final on this yet. when a user drags an existing connection and it turns into a self
  8151. // loop, then this code hides the target endpoint (by removing it from the DOM) But I think this should
  8152. // occur only if the anchor is Continuous
  8153. if (connection.endpoints[1].anchor.isContinuous) {
  8154. if (connection.source === connection.target) {
  8155. connection._jsPlumb.instance.removeElement(connection.endpoints[1].canvas);
  8156. }
  8157. else {
  8158. if (connection.endpoints[1].canvas.parentNode == null) {
  8159. connection._jsPlumb.instance.appendElement(connection.endpoints[1].canvas);
  8160. }
  8161. }
  8162. }
  8163. connection.updateConnectedClass();
  8164. }
  8165. };
  8166. //
  8167. // moves the given endpoint from `currentId` to `element`.
  8168. // This involves:
  8169. //
  8170. // 1. changing the key in _amEndpoints under which the endpoint is stored
  8171. // 2. changing the source or target values in all of the endpoint's connections
  8172. // 3. changing the array in connectionsByElementId in which the endpoint's connections
  8173. // are stored (done by either sourceChanged or updateOtherEndpoint)
  8174. //
  8175. this.rehomeEndpoint = function (ep, currentId, element) {
  8176. var eps = _amEndpoints[currentId] || [],
  8177. elementId = jsPlumbInstance.getId(element);
  8178. if (elementId !== currentId) {
  8179. var idx = eps.indexOf(ep);
  8180. if (idx > -1) {
  8181. var _ep = eps.splice(idx, 1)[0];
  8182. self.add(_ep, elementId);
  8183. }
  8184. }
  8185. for (var i = 0; i < ep.connections.length; i++) {
  8186. if (ep.connections[i].sourceId == currentId) {
  8187. //ep.connections[i].sourceId = ep.elementId;
  8188. //ep.connections[i].source = ep.element;
  8189. self.sourceChanged(currentId, ep.elementId, ep.connections[i], ep.element);
  8190. }
  8191. else if (ep.connections[i].targetId == currentId) {
  8192. ep.connections[i].targetId = ep.elementId;
  8193. ep.connections[i].target = ep.element;
  8194. self.updateOtherEndpoint(ep.connections[i].sourceId, currentId, ep.elementId, ep.connections[i]);
  8195. }
  8196. }
  8197. };
  8198. this.redraw = function (elementId, ui, timestamp, offsetToUI, clearEdits, doNotRecalcEndpoint) {
  8199. if (!jsPlumbInstance.isSuspendDrawing()) {
  8200. // get all the endpoints for this element
  8201. var ep = _amEndpoints[elementId] || [],
  8202. endpointConnections = connectionsByElementId[elementId] || [],
  8203. connectionsToPaint = [],
  8204. endpointsToPaint = [],
  8205. anchorsToUpdate = [];
  8206. timestamp = timestamp || jsPlumbInstance.timestamp();
  8207. // offsetToUI are values that would have been calculated in the dragManager when registering
  8208. // an endpoint for an element that had a parent (somewhere in the hierarchy) that had been
  8209. // registered as draggable.
  8210. offsetToUI = offsetToUI || {left: 0, top: 0};
  8211. if (ui) {
  8212. ui = {
  8213. left: ui.left + offsetToUI.left,
  8214. top: ui.top + offsetToUI.top
  8215. };
  8216. }
  8217. // valid for one paint cycle.
  8218. var myOffset = jsPlumbInstance.updateOffset({ elId: elementId, offset: ui, recalc: false, timestamp: timestamp }),
  8219. orientationCache = {};
  8220. // actually, first we should compute the orientation of this element to all other elements to which
  8221. // this element is connected with a continuous anchor (whether both ends of the connection have
  8222. // a continuous anchor or just one)
  8223. for (var i = 0; i < endpointConnections.length; i++) {
  8224. var conn = endpointConnections[i][0],
  8225. sourceId = conn.sourceId,
  8226. targetId = conn.targetId,
  8227. sourceContinuous = conn.endpoints[0].anchor.isContinuous,
  8228. targetContinuous = conn.endpoints[1].anchor.isContinuous;
  8229. if (sourceContinuous || targetContinuous) {
  8230. var oKey = sourceId + "_" + targetId,
  8231. o = orientationCache[oKey],
  8232. oIdx = conn.sourceId == elementId ? 1 : 0;
  8233. if (sourceContinuous && !anchorLists[sourceId]) anchorLists[sourceId] = { top: [], right: [], bottom: [], left: [] };
  8234. if (targetContinuous && !anchorLists[targetId]) anchorLists[targetId] = { top: [], right: [], bottom: [], left: [] };
  8235. if (elementId != targetId) jsPlumbInstance.updateOffset({ elId: targetId, timestamp: timestamp });
  8236. if (elementId != sourceId) jsPlumbInstance.updateOffset({ elId: sourceId, timestamp: timestamp });
  8237. var td = jsPlumbInstance.getCachedData(targetId),
  8238. sd = jsPlumbInstance.getCachedData(sourceId);
  8239. if (targetId == sourceId && (sourceContinuous || targetContinuous)) {
  8240. // here we may want to improve this by somehow determining the face we'd like
  8241. // to put the connector on. ideally, when drawing, the face should be calculated
  8242. // by determining which face is closest to the point at which the mouse button
  8243. // was released. for now, we're putting it on the top face.
  8244. _updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint);
  8245. _updateAnchorList( anchorLists[targetId], -Math.PI / 2, 0, conn, false, sourceId, 1, false, "top", targetId, connectionsToPaint, endpointsToPaint);
  8246. }
  8247. else {
  8248. if (!o) {
  8249. o = calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor);
  8250. orientationCache[oKey] = o;
  8251. // this would be a performance enhancement, but the computed angles need to be clamped to
  8252. //the (-PI/2 -> PI/2) range in order for the sorting to work properly.
  8253. /* orientationCache[oKey2] = {
  8254. orientation:o.orientation,
  8255. a:[o.a[1], o.a[0]],
  8256. theta:o.theta + Math.PI,
  8257. theta2:o.theta2 + Math.PI
  8258. };*/
  8259. }
  8260. if (sourceContinuous) _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
  8261. if (targetContinuous) _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
  8262. }
  8263. if (sourceContinuous) _ju.addWithFunction(anchorsToUpdate, sourceId, function (a) {
  8264. return a === sourceId;
  8265. });
  8266. if (targetContinuous) _ju.addWithFunction(anchorsToUpdate, targetId, function (a) {
  8267. return a === targetId;
  8268. });
  8269. _ju.addWithFunction(connectionsToPaint, conn, function (c) {
  8270. return c.id == conn.id;
  8271. });
  8272. if ((sourceContinuous && oIdx === 0) || (targetContinuous && oIdx === 1))
  8273. _ju.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function (e) {
  8274. return e.id == conn.endpoints[oIdx].id;
  8275. });
  8276. }
  8277. }
  8278. // place Endpoints whose anchors are continuous but have no Connections
  8279. for (i = 0; i < ep.length; i++) {
  8280. if (ep[i].connections.length === 0 && ep[i].anchor.isContinuous) {
  8281. if (!anchorLists[elementId]) anchorLists[elementId] = { top: [], right: [], bottom: [], left: [] };
  8282. _updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints: [ep[i], ep[i]], paint: function () {
  8283. }}, false, elementId, 0, false, ep[i].anchor.getDefaultFace(), elementId, connectionsToPaint, endpointsToPaint);
  8284. _ju.addWithFunction(anchorsToUpdate, elementId, function (a) {
  8285. return a === elementId;
  8286. });
  8287. }
  8288. }
  8289. // now place all the continuous anchors we need to;
  8290. for (i = 0; i < anchorsToUpdate.length; i++) {
  8291. placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]);
  8292. }
  8293. // now that continuous anchors have been placed, paint all the endpoints for this element
  8294. // TODO performance: add the endpoint ids to a temp array, and then when iterating in the next
  8295. // loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way.
  8296. for (i = 0; i < ep.length; i++) {
  8297. ep[i].paint({ timestamp: timestamp, offset: myOffset, dimensions: myOffset.s, recalc: doNotRecalcEndpoint !== true });
  8298. }
  8299. // ... and any other endpoints we came across as a result of the continuous anchors.
  8300. for (i = 0; i < endpointsToPaint.length; i++) {
  8301. var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId);
  8302. endpointsToPaint[i].paint({ timestamp: timestamp, offset: cd, dimensions: cd.s });
  8303. }
  8304. // paint all the standard and "dynamic connections", which are connections whose other anchor is
  8305. // static and therefore does need to be recomputed; we make sure that happens only one time.
  8306. // TODO we could have compiled a list of these in the first pass through connections; might save some time.
  8307. for (i = 0; i < endpointConnections.length; i++) {
  8308. var otherEndpoint = endpointConnections[i][1];
  8309. if (otherEndpoint.anchor.constructor == _jp.DynamicAnchor) {
  8310. otherEndpoint.paint({ elementWithPrecedence: elementId, timestamp: timestamp });
  8311. _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
  8312. return c.id == endpointConnections[i][0].id;
  8313. });
  8314. // all the connections for the other endpoint now need to be repainted
  8315. for (var k = 0; k < otherEndpoint.connections.length; k++) {
  8316. if (otherEndpoint.connections[k] !== endpointConnections[i][0])
  8317. _ju.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function (c) {
  8318. return c.id == otherEndpoint.connections[k].id;
  8319. });
  8320. }
  8321. } else if (otherEndpoint.anchor.constructor == _jp.Anchor) {
  8322. _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
  8323. return c.id == endpointConnections[i][0].id;
  8324. });
  8325. }
  8326. }
  8327. // paint current floating connection for this element, if there is one.
  8328. var fc = floatingConnections[elementId];
  8329. if (fc)
  8330. fc.paint({timestamp: timestamp, recalc: false, elId: elementId});
  8331. // paint all the connections
  8332. for (i = 0; i < connectionsToPaint.length; i++) {
  8333. connectionsToPaint[i].paint({elId: elementId, timestamp: timestamp, recalc: false, clearEdits: clearEdits});
  8334. }
  8335. }
  8336. };
  8337. var ContinuousAnchor = function (anchorParams) {
  8338. _ju.EventGenerator.apply(this);
  8339. this.type = "Continuous";
  8340. this.isDynamic = true;
  8341. this.isContinuous = true;
  8342. var faces = anchorParams.faces || ["top", "right", "bottom", "left"],
  8343. clockwise = !(anchorParams.clockwise === false),
  8344. availableFaces = { },
  8345. opposites = { "top": "bottom", "right": "left", "left": "right", "bottom": "top" },
  8346. clockwiseOptions = { "top": "right", "right": "bottom", "left": "top", "bottom": "left" },
  8347. antiClockwiseOptions = { "top": "left", "right": "top", "left": "bottom", "bottom": "right" },
  8348. secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions,
  8349. lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions,
  8350. cssClass = anchorParams.cssClass || "";
  8351. for (var i = 0; i < faces.length; i++) {
  8352. availableFaces[faces[i]] = true;
  8353. }
  8354. this.getDefaultFace = function () {
  8355. return faces.length === 0 ? "top" : faces[0];
  8356. };
  8357. // if the given edge is supported, returns it. otherwise looks for a substitute that _is_
  8358. // supported. if none supported we also return the request edge.
  8359. this.verifyEdge = function (edge) {
  8360. if (availableFaces[edge]) return edge;
  8361. else if (availableFaces[opposites[edge]]) return opposites[edge];
  8362. else if (availableFaces[secondBest[edge]]) return secondBest[edge];
  8363. else if (availableFaces[lastChoice[edge]]) return lastChoice[edge];
  8364. return edge; // we have to give them something.
  8365. };
  8366. this.isEdgeSupported = function (edge) {
  8367. return availableFaces[edge] === true;
  8368. };
  8369. this.compute = function (params) {
  8370. return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0];
  8371. };
  8372. this.getCurrentLocation = function (params) {
  8373. return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0];
  8374. };
  8375. this.getOrientation = function (endpoint) {
  8376. return continuousAnchorOrientations[endpoint.id] || [0, 0];
  8377. };
  8378. this.clearUserDefinedLocation = function () {
  8379. delete userDefinedContinuousAnchorLocations[anchorParams.elementId];
  8380. };
  8381. this.setUserDefinedLocation = function (loc) {
  8382. userDefinedContinuousAnchorLocations[anchorParams.elementId] = loc;
  8383. };
  8384. this.getCssClass = function () {
  8385. return cssClass;
  8386. };
  8387. };
  8388. // continuous anchors
  8389. jsPlumbInstance.continuousAnchorFactory = {
  8390. get: function (params) {
  8391. return new ContinuousAnchor(params);
  8392. },
  8393. clear: function (elementId) {
  8394. delete userDefinedContinuousAnchorLocations[elementId];
  8395. delete continuousAnchorLocations[elementId];
  8396. }
  8397. };
  8398. };
  8399. /**
  8400. * 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
  8401. * 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"),
  8402. * 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
  8403. * creation of Anchors without user intervention.
  8404. */
  8405. _jp.Anchor = function (params) {
  8406. this.x = params.x || 0;
  8407. this.y = params.y || 0;
  8408. this.elementId = params.elementId;
  8409. this.cssClass = params.cssClass || "";
  8410. this.userDefinedLocation = null;
  8411. this.orientation = params.orientation || [ 0, 0 ];
  8412. this.lastReturnValue = null;
  8413. this.offsets = params.offsets || [ 0, 0 ];
  8414. this.timestamp = null;
  8415. _ju.EventGenerator.apply(this);
  8416. this.compute = function (params) {
  8417. var xy = params.xy, wh = params.wh, timestamp = params.timestamp;
  8418. if (params.clearUserDefinedLocation)
  8419. this.userDefinedLocation = null;
  8420. if (timestamp && timestamp === this.timestamp)
  8421. return this.lastReturnValue;
  8422. if (this.userDefinedLocation != null) {
  8423. this.lastReturnValue = this.userDefinedLocation;
  8424. }
  8425. else {
  8426. this.lastReturnValue = [ xy[0] + (this.x * wh[0]) + this.offsets[0], xy[1] + (this.y * wh[1]) + this.offsets[1] ];
  8427. }
  8428. this.timestamp = timestamp;
  8429. return this.lastReturnValue;
  8430. };
  8431. this.getCurrentLocation = function (params) {
  8432. params = params || {};
  8433. return (this.lastReturnValue == null || (params.timestamp != null && this.timestamp != params.timestamp)) ? this.compute(params) : this.lastReturnValue;
  8434. };
  8435. };
  8436. _ju.extend(_jp.Anchor, _ju.EventGenerator, {
  8437. equals: function (anchor) {
  8438. if (!anchor) return false;
  8439. var ao = anchor.getOrientation(),
  8440. o = this.getOrientation();
  8441. 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];
  8442. },
  8443. getUserDefinedLocation: function () {
  8444. return this.userDefinedLocation;
  8445. },
  8446. setUserDefinedLocation: function (l) {
  8447. this.userDefinedLocation = l;
  8448. },
  8449. clearUserDefinedLocation: function () {
  8450. this.userDefinedLocation = null;
  8451. },
  8452. getOrientation: function () {
  8453. return this.orientation;
  8454. },
  8455. getCssClass: function () {
  8456. return this.cssClass;
  8457. }
  8458. });
  8459. /**
  8460. * An Anchor that floats. its orientation is computed dynamically from
  8461. * its position relative to the anchor it is floating relative to. It is used when creating
  8462. * a connection through drag and drop.
  8463. *
  8464. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  8465. */
  8466. _jp.FloatingAnchor = function (params) {
  8467. _jp.Anchor.apply(this, arguments);
  8468. // this is the anchor that this floating anchor is referenced to for
  8469. // purposes of calculating the orientation.
  8470. var ref = params.reference,
  8471. // the canvas this refers to.
  8472. refCanvas = params.referenceCanvas,
  8473. size = _jp.getSize(refCanvas),
  8474. // these are used to store the current relative position of our
  8475. // anchor wrt the reference anchor. they only indicate
  8476. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  8477. // values are written by the compute method, and read
  8478. // by the getOrientation method.
  8479. xDir = 0, yDir = 0,
  8480. // temporary member used to store an orientation when the floating
  8481. // anchor is hovering over another anchor.
  8482. orientation = null,
  8483. _lastResult = null;
  8484. // clear from parent. we want floating anchor orientation to always be computed.
  8485. this.orientation = null;
  8486. // set these to 0 each; they are used by certain types of connectors in the loopback case,
  8487. // when the connector is trying to clear the element it is on. but for floating anchor it's not
  8488. // very important.
  8489. this.x = 0;
  8490. this.y = 0;
  8491. this.isFloating = true;
  8492. this.compute = function (params) {
  8493. var xy = params.xy,
  8494. 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.
  8495. _lastResult = result;
  8496. return result;
  8497. };
  8498. this.getOrientation = function (_endpoint) {
  8499. if (orientation) return orientation;
  8500. else {
  8501. var o = ref.getOrientation(_endpoint);
  8502. // here we take into account the orientation of the other
  8503. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  8504. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  8505. return [ Math.abs(o[0]) * xDir * -1,
  8506. Math.abs(o[1]) * yDir * -1 ];
  8507. }
  8508. };
  8509. /**
  8510. * notification the endpoint associated with this anchor is hovering
  8511. * over another anchor; we want to assume that anchor's orientation
  8512. * for the duration of the hover.
  8513. */
  8514. this.over = function (anchor, endpoint) {
  8515. orientation = anchor.getOrientation(endpoint);
  8516. };
  8517. /**
  8518. * notification the endpoint associated with this anchor is no
  8519. * longer hovering over another anchor; we should resume calculating
  8520. * orientation as we normally do.
  8521. */
  8522. this.out = function () {
  8523. orientation = null;
  8524. };
  8525. this.getCurrentLocation = function (params) {
  8526. return _lastResult == null ? this.compute(params) : _lastResult;
  8527. };
  8528. };
  8529. _ju.extend(_jp.FloatingAnchor, _jp.Anchor);
  8530. var _convertAnchor = function (anchor, jsPlumbInstance, elementId) {
  8531. return anchor.constructor == _jp.Anchor ? anchor : jsPlumbInstance.makeAnchor(anchor, elementId, jsPlumbInstance);
  8532. };
  8533. /*
  8534. * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
  8535. * through at compute time to find the one that is located closest to
  8536. * the center of the target element, and returns that Anchor's compute
  8537. * method result. this causes endpoints to follow each other with
  8538. * respect to the orientation of their target elements, which is a useful
  8539. * feature for some applications.
  8540. *
  8541. */
  8542. _jp.DynamicAnchor = function (params) {
  8543. _jp.Anchor.apply(this, arguments);
  8544. this.isDynamic = true;
  8545. this.anchors = [];
  8546. this.elementId = params.elementId;
  8547. this.jsPlumbInstance = params.jsPlumbInstance;
  8548. for (var i = 0; i < params.anchors.length; i++)
  8549. this.anchors[i] = _convertAnchor(params.anchors[i], this.jsPlumbInstance, this.elementId);
  8550. this.getAnchors = function () {
  8551. return this.anchors;
  8552. };
  8553. this.locked = false;
  8554. var _curAnchor = this.anchors.length > 0 ? this.anchors[0] : null,
  8555. _lastAnchor = _curAnchor,
  8556. self = this,
  8557. // helper method to calculate the distance between the centers of the two elements.
  8558. _distance = function (anchor, cx, cy, xy, wh) {
  8559. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]),
  8560. acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2);
  8561. return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) +
  8562. Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2)));
  8563. },
  8564. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  8565. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  8566. // xy - xy loc of the anchor's element
  8567. // wh - anchor's element's dimensions
  8568. // txy - xy loc of the element of the other anchor in the connection
  8569. // twh - dimensions of the element of the other anchor in the connection.
  8570. // anchors - the list of selectable anchors
  8571. _anchorSelector = params.selector || function (xy, wh, txy, twh, anchors) {
  8572. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  8573. var minIdx = -1, minDist = Infinity;
  8574. for (var i = 0; i < anchors.length; i++) {
  8575. var d = _distance(anchors[i], cx, cy, xy, wh);
  8576. if (d < minDist) {
  8577. minIdx = i + 0;
  8578. minDist = d;
  8579. }
  8580. }
  8581. return anchors[minIdx];
  8582. };
  8583. this.compute = function (params) {
  8584. var xy = params.xy, wh = params.wh, txy = params.txy, twh = params.twh;
  8585. this.timestamp = params.timestamp;
  8586. var udl = self.getUserDefinedLocation();
  8587. if (udl != null) {
  8588. return udl;
  8589. }
  8590. // if anchor is locked or an opposite element was not given, we
  8591. // maintain our state. anchor will be locked
  8592. // if it is the source of a drag and drop.
  8593. if (this.locked || txy == null || twh == null)
  8594. return _curAnchor.compute(params);
  8595. else
  8596. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  8597. _curAnchor = _anchorSelector(xy, wh, txy, twh, this.anchors);
  8598. this.x = _curAnchor.x;
  8599. this.y = _curAnchor.y;
  8600. if (_curAnchor != _lastAnchor)
  8601. this.fire("anchorChanged", _curAnchor);
  8602. _lastAnchor = _curAnchor;
  8603. return _curAnchor.compute(params);
  8604. };
  8605. this.getCurrentLocation = function (params) {
  8606. return this.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation(params) : null);
  8607. };
  8608. this.getOrientation = function (_endpoint) {
  8609. return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ];
  8610. };
  8611. this.over = function (anchor, endpoint) {
  8612. if (_curAnchor != null) _curAnchor.over(anchor, endpoint);
  8613. };
  8614. this.out = function () {
  8615. if (_curAnchor != null) _curAnchor.out();
  8616. };
  8617. this.getCssClass = function () {
  8618. return (_curAnchor && _curAnchor.getCssClass()) || "";
  8619. };
  8620. };
  8621. _ju.extend(_jp.DynamicAnchor, _jp.Anchor);
  8622. // -------- basic anchors ------------------
  8623. var _curryAnchor = function (x, y, ox, oy, type, fnInit) {
  8624. _jp.Anchors[type] = function (params) {
  8625. var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
  8626. a.type = type;
  8627. if (fnInit) fnInit(a, params);
  8628. return a;
  8629. };
  8630. };
  8631. _curryAnchor(0.5, 0, 0, -1, "TopCenter");
  8632. _curryAnchor(0.5, 1, 0, 1, "BottomCenter");
  8633. _curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
  8634. _curryAnchor(1, 0.5, 1, 0, "RightMiddle");
  8635. _curryAnchor(0.5, 0, 0, -1, "Top");
  8636. _curryAnchor(0.5, 1, 0, 1, "Bottom");
  8637. _curryAnchor(0, 0.5, -1, 0, "Left");
  8638. _curryAnchor(1, 0.5, 1, 0, "Right");
  8639. _curryAnchor(0.5, 0.5, 0, 0, "Center");
  8640. _curryAnchor(1, 0, 0, -1, "TopRight");
  8641. _curryAnchor(1, 1, 0, 1, "BottomRight");
  8642. _curryAnchor(0, 0, 0, -1, "TopLeft");
  8643. _curryAnchor(0, 1, 0, 1, "BottomLeft");
  8644. // ------- dynamic anchors -------------------
  8645. // default dynamic anchors chooses from Top, Right, Bottom, Left
  8646. _jp.Defaults.DynamicAnchors = function (params) {
  8647. return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
  8648. };
  8649. // default dynamic anchors bound to name 'AutoDefault'
  8650. _jp.Anchors.AutoDefault = function (params) {
  8651. var a = params.jsPlumbInstance.makeDynamicAnchor(_jp.Defaults.DynamicAnchors(params));
  8652. a.type = "AutoDefault";
  8653. return a;
  8654. };
  8655. // ------- continuous anchors -------------------
  8656. var _curryContinuousAnchor = function (type, faces) {
  8657. _jp.Anchors[type] = function (params) {
  8658. var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces: faces }], params.elementId, params.jsPlumbInstance);
  8659. a.type = type;
  8660. return a;
  8661. };
  8662. };
  8663. _jp.Anchors.Continuous = function (params) {
  8664. return params.jsPlumbInstance.continuousAnchorFactory.get(params);
  8665. };
  8666. _curryContinuousAnchor("ContinuousLeft", ["left"]);
  8667. _curryContinuousAnchor("ContinuousTop", ["top"]);
  8668. _curryContinuousAnchor("ContinuousBottom", ["bottom"]);
  8669. _curryContinuousAnchor("ContinuousRight", ["right"]);
  8670. // ------- position assign anchors -------------------
  8671. // this anchor type lets you assign the position at connection time.
  8672. _curryAnchor(0, 0, 0, 0, "Assign", function (anchor, params) {
  8673. // find what to use as the "position finder". the user may have supplied a String which represents
  8674. // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
  8675. // position finder as a function. we find out what to use and then set it on the anchor.
  8676. var pf = params.position || "Fixed";
  8677. anchor.positionFinder = pf.constructor == String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf;
  8678. // always set the constructor params; the position finder might need them later (the Grid one does,
  8679. // for example)
  8680. anchor.constructorParams = params;
  8681. });
  8682. // these are the default anchor positions finders, which are used by the makeTarget function. supplying
  8683. // a position finder argument to that function allows you to specify where the resulting anchor will
  8684. // be located
  8685. root.jsPlumbInstance.prototype.AnchorPositionFinders = {
  8686. "Fixed": function (dp, ep, es) {
  8687. return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
  8688. },
  8689. "Grid": function (dp, ep, es, params) {
  8690. var dx = dp.left - ep.left, dy = dp.top - ep.top,
  8691. gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]),
  8692. mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
  8693. return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
  8694. }
  8695. };
  8696. // ------- perimeter anchors -------------------
  8697. _jp.Anchors.Perimeter = function (params) {
  8698. params = params || {};
  8699. var anchorCount = params.anchorCount || 60,
  8700. shape = params.shape;
  8701. if (!shape) throw new Error("no shape supplied to Perimeter Anchor type");
  8702. var _circle = function () {
  8703. var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = [];
  8704. for (var i = 0; i < anchorCount; i++) {
  8705. var x = r + (r * Math.sin(current)),
  8706. y = r + (r * Math.cos(current));
  8707. a.push([ x, y, 0, 0 ]);
  8708. current += step;
  8709. }
  8710. return a;
  8711. },
  8712. _path = function (segments) {
  8713. var anchorsPerFace = anchorCount / segments.length, a = [],
  8714. _computeFace = function (x1, y1, x2, y2, fractionalLength) {
  8715. anchorsPerFace = anchorCount * fractionalLength;
  8716. var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace;
  8717. for (var i = 0; i < anchorsPerFace; i++) {
  8718. a.push([
  8719. x1 + (dx * i),
  8720. y1 + (dy * i),
  8721. 0,
  8722. 0
  8723. ]);
  8724. }
  8725. };
  8726. for (var i = 0; i < segments.length; i++)
  8727. _computeFace.apply(null, segments[i]);
  8728. return a;
  8729. },
  8730. _shape = function (faces) {
  8731. var s = [];
  8732. for (var i = 0; i < faces.length; i++) {
  8733. s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]);
  8734. }
  8735. return _path(s);
  8736. },
  8737. _rectangle = function () {
  8738. return _shape([
  8739. [ 0, 0, 1, 0 ],
  8740. [ 1, 0, 1, 1 ],
  8741. [ 1, 1, 0, 1 ],
  8742. [ 0, 1, 0, 0 ]
  8743. ]);
  8744. };
  8745. var _shapes = {
  8746. "Circle": _circle,
  8747. "Ellipse": _circle,
  8748. "Diamond": function () {
  8749. return _shape([
  8750. [ 0.5, 0, 1, 0.5 ],
  8751. [ 1, 0.5, 0.5, 1 ],
  8752. [ 0.5, 1, 0, 0.5 ],
  8753. [ 0, 0.5, 0.5, 0 ]
  8754. ]);
  8755. },
  8756. "Rectangle": _rectangle,
  8757. "Square": _rectangle,
  8758. "Triangle": function () {
  8759. return _shape([
  8760. [ 0.5, 0, 1, 1 ],
  8761. [ 1, 1, 0, 1 ],
  8762. [ 0, 1, 0.5, 0]
  8763. ]);
  8764. },
  8765. "Path": function (params) {
  8766. var points = params.points, p = [], tl = 0;
  8767. for (var i = 0; i < points.length - 1; i++) {
  8768. var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1]));
  8769. tl += l;
  8770. p.push([points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], l]);
  8771. }
  8772. for (var j = 0; j < p.length; j++) {
  8773. p[j][4] = p[j][4] / tl;
  8774. }
  8775. return _path(p);
  8776. }
  8777. },
  8778. _rotate = function (points, amountInDegrees) {
  8779. var o = [], theta = amountInDegrees / 180 * Math.PI;
  8780. for (var i = 0; i < points.length; i++) {
  8781. var _x = points[i][0] - 0.5,
  8782. _y = points[i][1] - 0.5;
  8783. o.push([
  8784. 0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))),
  8785. 0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))),
  8786. points[i][2],
  8787. points[i][3]
  8788. ]);
  8789. }
  8790. return o;
  8791. };
  8792. if (!_shapes[shape]) throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type");
  8793. var da = _shapes[shape](params);
  8794. if (params.rotation) da = _rotate(da, params.rotation);
  8795. var a = params.jsPlumbInstance.makeDynamicAnchor(da);
  8796. a.type = "Perimeter";
  8797. return a;
  8798. };
  8799. }).call(typeof window !== 'undefined' ? window : this);
  8800. /*
  8801. * jsPlumb
  8802. *
  8803. * Title:jsPlumb 2.3.0
  8804. *
  8805. * Provides a way to visually connect elements on an HTML page, using SVG.
  8806. *
  8807. * This file contains the default Connectors, Endpoint and Overlay definitions.
  8808. *
  8809. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  8810. *
  8811. * http://jsplumbtoolkit.com
  8812. * http://github.com/sporritt/jsplumb
  8813. *
  8814. * Dual licensed under the MIT and GPL2 licenses.
  8815. */
  8816. ;
  8817. (function () {
  8818. "use strict";
  8819. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jg = root.Biltong;
  8820. _jp.Segments = {
  8821. /*
  8822. * Class: AbstractSegment
  8823. * A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc',
  8824. * 'Bezier'. This is new from 1.4.2, and gives us a lot more flexibility when drawing connections: things such
  8825. * as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are
  8826. * much easier to do now.
  8827. *
  8828. * A Segment is responsible for providing coordinates for painting it, and also must be able to report its length.
  8829. *
  8830. */
  8831. AbstractSegment: function (params) {
  8832. this.params = params;
  8833. /**
  8834. * Function: findClosestPointOnPath
  8835. * Finds the closest point on this segment to the given [x, y],
  8836. * returning both the x and y of the point plus its distance from
  8837. * the supplied point, and its location along the length of the
  8838. * path inscribed by the segment. This implementation returns
  8839. * Infinity for distance and null values for everything else;
  8840. * subclasses are expected to override.
  8841. */
  8842. this.findClosestPointOnPath = function (x, y) {
  8843. return {
  8844. d: Infinity,
  8845. x: null,
  8846. y: null,
  8847. l: null
  8848. };
  8849. };
  8850. this.getBounds = function () {
  8851. return {
  8852. minX: Math.min(params.x1, params.x2),
  8853. minY: Math.min(params.y1, params.y2),
  8854. maxX: Math.max(params.x1, params.x2),
  8855. maxY: Math.max(params.y1, params.y2)
  8856. };
  8857. };
  8858. },
  8859. Straight: function (params) {
  8860. var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
  8861. length, m, m2, x1, x2, y1, y2,
  8862. _recalc = function () {
  8863. length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  8864. m = _jg.gradient({x: x1, y: y1}, {x: x2, y: y2});
  8865. m2 = -1 / m;
  8866. };
  8867. this.type = "Straight";
  8868. this.getLength = function () {
  8869. return length;
  8870. };
  8871. this.getGradient = function () {
  8872. return m;
  8873. };
  8874. this.getCoordinates = function () {
  8875. return { x1: x1, y1: y1, x2: x2, y2: y2 };
  8876. };
  8877. this.setCoordinates = function (coords) {
  8878. x1 = coords.x1;
  8879. y1 = coords.y1;
  8880. x2 = coords.x2;
  8881. y2 = coords.y2;
  8882. _recalc();
  8883. };
  8884. this.setCoordinates({x1: params.x1, y1: params.y1, x2: params.x2, y2: params.y2});
  8885. this.getBounds = function () {
  8886. return {
  8887. minX: Math.min(x1, x2),
  8888. minY: Math.min(y1, y2),
  8889. maxX: Math.max(x1, x2),
  8890. maxY: Math.max(y1, y2)
  8891. };
  8892. };
  8893. /**
  8894. * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
  8895. * 0 to 1 inclusive. for the straight line segment this is simple maths.
  8896. */
  8897. this.pointOnPath = function (location, absolute) {
  8898. if (location === 0 && !absolute)
  8899. return { x: x1, y: y1 };
  8900. else if (location == 1 && !absolute)
  8901. return { x: x2, y: y2 };
  8902. else {
  8903. var l = absolute ? location > 0 ? location : length + location : location * length;
  8904. return _jg.pointOnLine({x: x1, y: y1}, {x: x2, y: y2}, l);
  8905. }
  8906. };
  8907. /**
  8908. * returns the gradient of the segment at the given point - which for us is constant.
  8909. */
  8910. this.gradientAtPoint = function (_) {
  8911. return m;
  8912. };
  8913. /**
  8914. * returns the point on the segment's path that is 'distance' along the length of the path from 'location', where
  8915. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
  8916. * this hands off to jsPlumbUtil to do the maths, supplying two points and the distance.
  8917. */
  8918. this.pointAlongPathFrom = function (location, distance, absolute) {
  8919. var p = this.pointOnPath(location, absolute),
  8920. farAwayPoint = distance <= 0 ? {x: x1, y: y1} : {x: x2, y: y2 };
  8921. /*
  8922. location == 1 ? {
  8923. x:x1 + ((x2 - x1) * 10),
  8924. y:y1 + ((y1 - y2) * 10)
  8925. } :
  8926. */
  8927. if (distance <= 0 && Math.abs(distance) > 1) distance *= -1;
  8928. return _jg.pointOnLine(p, farAwayPoint, distance);
  8929. };
  8930. // is c between a and b?
  8931. var within = function (a, b, c) {
  8932. return c >= Math.min(a, b) && c <= Math.max(a, b);
  8933. };
  8934. // find which of a and b is closest to c
  8935. var closest = function (a, b, c) {
  8936. return Math.abs(c - a) < Math.abs(c - b) ? a : b;
  8937. };
  8938. /**
  8939. Function: findClosestPointOnPath
  8940. Finds the closest point on this segment to [x,y]. See
  8941. notes on this method in AbstractSegment.
  8942. */
  8943. this.findClosestPointOnPath = function (x, y) {
  8944. var out = {
  8945. d: Infinity,
  8946. x: null,
  8947. y: null,
  8948. l: null,
  8949. x1: x1,
  8950. x2: x2,
  8951. y1: y1,
  8952. y2: y2
  8953. };
  8954. if (m === 0) {
  8955. out.y = y1;
  8956. out.x = within(x1, x2, x) ? x : closest(x1, x2, x);
  8957. }
  8958. else if (m == Infinity || m == -Infinity) {
  8959. out.x = x1;
  8960. out.y = within(y1, y2, y) ? y : closest(y1, y2, y);
  8961. }
  8962. else {
  8963. // closest point lies on normal from given point to this line.
  8964. var b = y1 - (m * x1),
  8965. b2 = y - (m2 * x),
  8966. // y1 = m.x1 + b and y1 = m2.x1 + b2
  8967. // so m.x1 + b = m2.x1 + b2
  8968. // x1(m - m2) = b2 - b
  8969. // x1 = (b2 - b) / (m - m2)
  8970. _x1 = (b2 - b) / (m - m2),
  8971. _y1 = (m * _x1) + b;
  8972. out.x = within(x1, x2, _x1) ? _x1 : closest(x1, x2, _x1);//_x1;
  8973. out.y = within(y1, y2, _y1) ? _y1 : closest(y1, y2, _y1);//_y1;
  8974. }
  8975. var fractionInSegment = _jg.lineLength([ out.x, out.y ], [ x1, y1 ]);
  8976. out.d = _jg.lineLength([x, y], [out.x, out.y]);
  8977. out.l = fractionInSegment / length;
  8978. return out;
  8979. };
  8980. },
  8981. /*
  8982. Arc Segment. You need to supply:
  8983. r - radius
  8984. cx - center x for the arc
  8985. cy - center y for the arc
  8986. ac - whether the arc is anticlockwise or not. default is clockwise.
  8987. and then either:
  8988. startAngle - startAngle for the arc.
  8989. endAngle - endAngle for the arc.
  8990. or:
  8991. x1 - x for start point
  8992. y1 - y for start point
  8993. x2 - x for end point
  8994. y2 - y for end point
  8995. */
  8996. Arc: function (params) {
  8997. var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
  8998. _calcAngle = function (_x, _y) {
  8999. return _jg.theta([params.cx, params.cy], [_x, _y]);
  9000. },
  9001. _calcAngleForLocation = function (segment, location) {
  9002. if (segment.anticlockwise) {
  9003. var sa = segment.startAngle < segment.endAngle ? segment.startAngle + TWO_PI : segment.startAngle,
  9004. s = Math.abs(sa - segment.endAngle);
  9005. return sa - (s * location);
  9006. }
  9007. else {
  9008. var ea = segment.endAngle < segment.startAngle ? segment.endAngle + TWO_PI : segment.endAngle,
  9009. ss = Math.abs(ea - segment.startAngle);
  9010. return segment.startAngle + (ss * location);
  9011. }
  9012. },
  9013. TWO_PI = 2 * Math.PI;
  9014. this.radius = params.r;
  9015. this.anticlockwise = params.ac;
  9016. this.type = "Arc";
  9017. if (params.startAngle && params.endAngle) {
  9018. this.startAngle = params.startAngle;
  9019. this.endAngle = params.endAngle;
  9020. this.x1 = params.cx + (this.radius * Math.cos(params.startAngle));
  9021. this.y1 = params.cy + (this.radius * Math.sin(params.startAngle));
  9022. this.x2 = params.cx + (this.radius * Math.cos(params.endAngle));
  9023. this.y2 = params.cy + (this.radius * Math.sin(params.endAngle));
  9024. }
  9025. else {
  9026. this.startAngle = _calcAngle(params.x1, params.y1);
  9027. this.endAngle = _calcAngle(params.x2, params.y2);
  9028. this.x1 = params.x1;
  9029. this.y1 = params.y1;
  9030. this.x2 = params.x2;
  9031. this.y2 = params.y2;
  9032. }
  9033. if (this.endAngle < 0) this.endAngle += TWO_PI;
  9034. if (this.startAngle < 0) this.startAngle += TWO_PI;
  9035. // segment is used by vml
  9036. //this.segment = _jg.quadrant([this.x1, this.y1], [this.x2, this.y2]);
  9037. // we now have startAngle and endAngle as positive numbers, meaning the
  9038. // absolute difference (|d|) between them is the sweep (s) of this arc, unless the
  9039. // arc is 'anticlockwise' in which case 's' is given by 2PI - |d|.
  9040. var ea = this.endAngle < this.startAngle ? this.endAngle + TWO_PI : this.endAngle;
  9041. this.sweep = Math.abs(ea - this.startAngle);
  9042. if (this.anticlockwise) this.sweep = TWO_PI - this.sweep;
  9043. var circumference = 2 * Math.PI * this.radius,
  9044. frac = this.sweep / TWO_PI,
  9045. length = circumference * frac;
  9046. this.getLength = function () {
  9047. return length;
  9048. };
  9049. this.getBounds = function () {
  9050. return {
  9051. minX: params.cx - params.r,
  9052. maxX: params.cx + params.r,
  9053. minY: params.cy - params.r,
  9054. maxY: params.cy + params.r
  9055. };
  9056. };
  9057. var VERY_SMALL_VALUE = 0.0000000001,
  9058. gentleRound = function (n) {
  9059. var f = Math.floor(n), r = Math.ceil(n);
  9060. if (n - f < VERY_SMALL_VALUE)
  9061. return f;
  9062. else if (r - n < VERY_SMALL_VALUE)
  9063. return r;
  9064. return n;
  9065. };
  9066. /**
  9067. * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
  9068. * 0 to 1 inclusive.
  9069. */
  9070. this.pointOnPath = function (location, absolute) {
  9071. if (location === 0) {
  9072. return { x: this.x1, y: this.y1, theta: this.startAngle };
  9073. }
  9074. else if (location == 1) {
  9075. return { x: this.x2, y: this.y2, theta: this.endAngle };
  9076. }
  9077. if (absolute) {
  9078. location = location / length;
  9079. }
  9080. var angle = _calcAngleForLocation(this, location),
  9081. _x = params.cx + (params.r * Math.cos(angle)),
  9082. _y = params.cy + (params.r * Math.sin(angle));
  9083. return { x: gentleRound(_x), y: gentleRound(_y), theta: angle };
  9084. };
  9085. /**
  9086. * returns the gradient of the segment at the given point.
  9087. */
  9088. this.gradientAtPoint = function (location, absolute) {
  9089. var p = this.pointOnPath(location, absolute);
  9090. var m = _jg.normal([ params.cx, params.cy ], [p.x, p.y ]);
  9091. if (!this.anticlockwise && (m == Infinity || m == -Infinity)) m *= -1;
  9092. return m;
  9093. };
  9094. this.pointAlongPathFrom = function (location, distance, absolute) {
  9095. var p = this.pointOnPath(location, absolute),
  9096. arcSpan = distance / circumference * 2 * Math.PI,
  9097. dir = this.anticlockwise ? -1 : 1,
  9098. startAngle = p.theta + (dir * arcSpan),
  9099. startX = params.cx + (this.radius * Math.cos(startAngle)),
  9100. startY = params.cy + (this.radius * Math.sin(startAngle));
  9101. return {x: startX, y: startY};
  9102. };
  9103. },
  9104. Bezier: function (params) {
  9105. this.curve = [
  9106. { x: params.x1, y: params.y1},
  9107. { x: params.cp1x, y: params.cp1y },
  9108. { x: params.cp2x, y: params.cp2y },
  9109. { x: params.x2, y: params.y2 }
  9110. ];
  9111. var _super = _jp.Segments.AbstractSegment.apply(this, arguments);
  9112. // although this is not a strictly rigorous determination of bounds
  9113. // of a bezier curve, it works for the types of curves that this segment
  9114. // type produces.
  9115. this.bounds = {
  9116. minX: Math.min(params.x1, params.x2, params.cp1x, params.cp2x),
  9117. minY: Math.min(params.y1, params.y2, params.cp1y, params.cp2y),
  9118. maxX: Math.max(params.x1, params.x2, params.cp1x, params.cp2x),
  9119. maxY: Math.max(params.y1, params.y2, params.cp1y, params.cp2y)
  9120. };
  9121. this.type = "Bezier";
  9122. var _translateLocation = function (_curve, location, absolute) {
  9123. if (absolute)
  9124. location = root.jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location);
  9125. return location;
  9126. };
  9127. /**
  9128. * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
  9129. * 0 to 1 inclusive.
  9130. */
  9131. this.pointOnPath = function (location, absolute) {
  9132. location = _translateLocation(this.curve, location, absolute);
  9133. return root.jsBezier.pointOnCurve(this.curve, location);
  9134. };
  9135. /**
  9136. * returns the gradient of the segment at the given point.
  9137. */
  9138. this.gradientAtPoint = function (location, absolute) {
  9139. location = _translateLocation(this.curve, location, absolute);
  9140. return root.jsBezier.gradientAtPoint(this.curve, location);
  9141. };
  9142. this.pointAlongPathFrom = function (location, distance, absolute) {
  9143. location = _translateLocation(this.curve, location, absolute);
  9144. return root.jsBezier.pointAlongCurveFrom(this.curve, location, distance);
  9145. };
  9146. this.getLength = function () {
  9147. return root.jsBezier.getLength(this.curve);
  9148. };
  9149. this.getBounds = function () {
  9150. return this.bounds;
  9151. };
  9152. }
  9153. };
  9154. _jp.SegmentRenderer = {
  9155. getPath: function (segment) {
  9156. return ({
  9157. "Straight": function () {
  9158. var d = segment.getCoordinates();
  9159. return "M " + d.x1 + " " + d.y1 + " L " + d.x2 + " " + d.y2;
  9160. },
  9161. "Bezier": function () {
  9162. var d = segment.params;
  9163. return "M " + d.x1 + " " + d.y1 +
  9164. " C " + d.cp1x + " " + d.cp1y + " " + d.cp2x + " " + d.cp2y + " " + d.x2 + " " + d.y2;
  9165. },
  9166. "Arc": function () {
  9167. var d = segment.params,
  9168. laf = segment.sweep > Math.PI ? 1 : 0,
  9169. sf = segment.anticlockwise ? 0 : 1;
  9170. return "M" + segment.x1 + " " + segment.y1 + " A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2;
  9171. }
  9172. })[segment.type]();
  9173. }
  9174. };
  9175. /*
  9176. Class: AbstractComponent
  9177. Superclass for AbstractConnector and AbstractEndpoint.
  9178. */
  9179. var AbstractComponent = function () {
  9180. this.resetBounds = function () {
  9181. this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
  9182. };
  9183. this.resetBounds();
  9184. };
  9185. /*
  9186. * Class: AbstractConnector
  9187. * Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it
  9188. * can be accessed from other files. You should not try to instantiate one of these directly.
  9189. *
  9190. * When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch
  9191. * that request to. This is done by keeping track of the total connector length as segments are added, and also
  9192. * their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching
  9193. * the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.)
  9194. */
  9195. _jp.Connectors.AbstractConnector = function (params) {
  9196. AbstractComponent.apply(this, arguments);
  9197. var segments = [],
  9198. totalLength = 0,
  9199. segmentProportions = [],
  9200. segmentProportionalLengths = [],
  9201. stub = params.stub || 0,
  9202. sourceStub = _ju.isArray(stub) ? stub[0] : stub,
  9203. targetStub = _ju.isArray(stub) ? stub[1] : stub,
  9204. gap = params.gap || 0,
  9205. sourceGap = _ju.isArray(gap) ? gap[0] : gap,
  9206. targetGap = _ju.isArray(gap) ? gap[1] : gap,
  9207. userProvidedSegments = null,
  9208. edited = false,
  9209. paintInfo = null,
  9210. geometry = null,
  9211. editable = params.editable !== false && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null;
  9212. var _setGeometry = this.setGeometry = function(g, internallyComputed) {
  9213. edited = (!internallyComputed);
  9214. geometry = g;
  9215. };
  9216. var _getGeometry = this.getGeometry = function() {
  9217. return geometry;
  9218. };
  9219. this.getPathData = function() {
  9220. var p = "";
  9221. for (var i = 0; i < segments.length; i++) {
  9222. p += _jp.SegmentRenderer.getPath(segments[i]);
  9223. p += " ";
  9224. }
  9225. return p;
  9226. };
  9227. this.hasBeenEdited = function() { return edited; };
  9228. this.isEditing = function() { return this.editor != null && this.editor.isActive(); };
  9229. this.setEditable = function(e) {
  9230. // if this connector has an editor already, or
  9231. // if an editor for this connector's type is available, or
  9232. // if the child declares an overrideSetEditable and it does not return false, editable is true.
  9233. if (e && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null && (this.overrideSetEditable == null || this.overrideSetEditable())) {
  9234. editable = e;
  9235. } else {
  9236. editable = false;
  9237. }
  9238. return editable;
  9239. };
  9240. this.isEditable = function() { return editable; };
  9241. /**
  9242. * Function: findSegmentForPoint
  9243. * Returns the segment that is closest to the given [x,y],
  9244. * null if nothing found. This function returns a JS
  9245. * object with:
  9246. *
  9247. * d - distance from segment
  9248. * l - proportional location in segment
  9249. * x - x point on the segment
  9250. * y - y point on the segment
  9251. * s - the segment itself.
  9252. */
  9253. this.findSegmentForPoint = function (x, y) {
  9254. var out = { d: Infinity, s: null, x: null, y: null, l: null };
  9255. for (var i = 0; i < segments.length; i++) {
  9256. var _s = segments[i].findClosestPointOnPath(x, y);
  9257. if (_s.d < out.d) {
  9258. out.d = _s.d;
  9259. out.l = _s.l;
  9260. out.x = _s.x;
  9261. out.y = _s.y;
  9262. out.s = segments[i];
  9263. out.x1 = _s.x1;
  9264. out.x2 = _s.x2;
  9265. out.y1 = _s.y1;
  9266. out.y2 = _s.y2;
  9267. out.index = i;
  9268. }
  9269. }
  9270. return out;
  9271. };
  9272. var _updateSegmentProportions = function () {
  9273. var curLoc = 0;
  9274. for (var i = 0; i < segments.length; i++) {
  9275. var sl = segments[i].getLength();
  9276. segmentProportionalLengths[i] = sl / totalLength;
  9277. segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ];
  9278. }
  9279. },
  9280. /**
  9281. * returns [segment, proportion of travel in segment, segment index] for the segment
  9282. * that contains the point which is 'location' distance along the entire path, where
  9283. * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
  9284. * are made up of a list of segments, each of which contributes some fraction to
  9285. * the total length.
  9286. * From 1.3.10 this also supports the 'absolute' property, which lets us specify a location
  9287. * as the absolute distance in pixels, rather than a proportion of the total path.
  9288. */
  9289. _findSegmentForLocation = function (location, absolute) {
  9290. if (absolute) {
  9291. location = location > 0 ? location / totalLength : (totalLength + location) / totalLength;
  9292. }
  9293. var idx = segmentProportions.length - 1, inSegmentProportion = 1;
  9294. for (var i = 0; i < segmentProportions.length; i++) {
  9295. if (segmentProportions[i][1] >= location) {
  9296. idx = i;
  9297. // todo is this correct for all connector path types?
  9298. inSegmentProportion = location == 1 ? 1 : location === 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
  9299. break;
  9300. }
  9301. }
  9302. return { segment: segments[idx], proportion: inSegmentProportion, index: idx };
  9303. },
  9304. _addSegment = function (conn, type, params) {
  9305. if (params.x1 == params.x2 && params.y1 == params.y2) return;
  9306. var s = new _jp.Segments[type](params);
  9307. segments.push(s);
  9308. totalLength += s.getLength();
  9309. conn.updateBounds(s);
  9310. },
  9311. _clearSegments = function () {
  9312. totalLength = segments.length = segmentProportions.length = segmentProportionalLengths.length = 0;
  9313. };
  9314. this.setSegments = function (_segs) {
  9315. userProvidedSegments = [];
  9316. totalLength = 0;
  9317. for (var i = 0; i < _segs.length; i++) {
  9318. userProvidedSegments.push(_segs[i]);
  9319. totalLength += _segs[i].getLength();
  9320. }
  9321. };
  9322. this.getLength = function() {
  9323. return totalLength;
  9324. };
  9325. var _prepareCompute = function (params) {
  9326. this.strokeWidth = params.strokeWidth;
  9327. var segment = _jg.quadrant(params.sourcePos, params.targetPos),
  9328. swapX = params.targetPos[0] < params.sourcePos[0],
  9329. swapY = params.targetPos[1] < params.sourcePos[1],
  9330. lw = params.strokeWidth || 1,
  9331. so = params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint),
  9332. to = params.targetEndpoint.anchor.getOrientation(params.targetEndpoint),
  9333. x = swapX ? params.targetPos[0] : params.sourcePos[0],
  9334. y = swapY ? params.targetPos[1] : params.sourcePos[1],
  9335. w = Math.abs(params.targetPos[0] - params.sourcePos[0]),
  9336. h = Math.abs(params.targetPos[1] - params.sourcePos[1]);
  9337. // if either anchor does not have an orientation set, we derive one from their relative
  9338. // positions. we fix the axis to be the one in which the two elements are further apart, and
  9339. // point each anchor at the other element. this is also used when dragging a new connection.
  9340. if (so[0] === 0 && so[1] === 0 || to[0] === 0 && to[1] === 0) {
  9341. var index = w > h ? 0 : 1, oIndex = [1, 0][index];
  9342. so = [];
  9343. to = [];
  9344. so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1;
  9345. to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1;
  9346. so[oIndex] = 0;
  9347. to[oIndex] = 0;
  9348. }
  9349. var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0],
  9350. sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1],
  9351. tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]),
  9352. ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]),
  9353. oProduct = ((so[0] * to[0]) + (so[1] * to[1]));
  9354. var result = {
  9355. sx: sx, sy: sy, tx: tx, ty: ty, lw: lw,
  9356. xSpan: Math.abs(tx - sx),
  9357. ySpan: Math.abs(ty - sy),
  9358. mx: (sx + tx) / 2,
  9359. my: (sy + ty) / 2,
  9360. so: so, to: to, x: x, y: y, w: w, h: h,
  9361. segment: segment,
  9362. startStubX: sx + (so[0] * sourceStub),
  9363. startStubY: sy + (so[1] * sourceStub),
  9364. endStubX: tx + (to[0] * targetStub),
  9365. endStubY: ty + (to[1] * targetStub),
  9366. isXGreaterThanStubTimes2: Math.abs(sx - tx) > (sourceStub + targetStub),
  9367. isYGreaterThanStubTimes2: Math.abs(sy - ty) > (sourceStub + targetStub),
  9368. opposite: oProduct == -1,
  9369. perpendicular: oProduct === 0,
  9370. orthogonal: oProduct == 1,
  9371. sourceAxis: so[0] === 0 ? "y" : "x",
  9372. points: [x, y, w, h, sx, sy, tx, ty ]
  9373. };
  9374. result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular";
  9375. return result;
  9376. };
  9377. this.getSegments = function () {
  9378. return segments;
  9379. };
  9380. this.updateBounds = function (segment) {
  9381. var segBounds = segment.getBounds();
  9382. this.bounds.minX = Math.min(this.bounds.minX, segBounds.minX);
  9383. this.bounds.maxX = Math.max(this.bounds.maxX, segBounds.maxX);
  9384. this.bounds.minY = Math.min(this.bounds.minY, segBounds.minY);
  9385. this.bounds.maxY = Math.max(this.bounds.maxY, segBounds.maxY);
  9386. };
  9387. var dumpSegmentsToConsole = function () {
  9388. console.log("SEGMENTS:");
  9389. for (var i = 0; i < segments.length; i++) {
  9390. console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]);
  9391. }
  9392. };
  9393. this.pointOnPath = function (location, absolute) {
  9394. var seg = _findSegmentForLocation(location, absolute);
  9395. return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || [0, 0];
  9396. };
  9397. this.gradientAtPoint = function (location, absolute) {
  9398. var seg = _findSegmentForLocation(location, absolute);
  9399. return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0;
  9400. };
  9401. this.pointAlongPathFrom = function (location, distance, absolute) {
  9402. var seg = _findSegmentForLocation(location, absolute);
  9403. // TODO what happens if this crosses to the next segment?
  9404. return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || [0, 0];
  9405. };
  9406. this.compute = function (params) {
  9407. paintInfo = _prepareCompute.call(this, params);
  9408. _clearSegments();
  9409. this._compute(paintInfo, params);
  9410. this.x = paintInfo.points[0];
  9411. this.y = paintInfo.points[1];
  9412. this.w = paintInfo.points[2];
  9413. this.h = paintInfo.points[3];
  9414. this.segment = paintInfo.segment;
  9415. _updateSegmentProportions();
  9416. };
  9417. return {
  9418. addSegment: _addSegment,
  9419. prepareCompute: _prepareCompute,
  9420. sourceStub: sourceStub,
  9421. targetStub: targetStub,
  9422. maxStub: Math.max(sourceStub, targetStub),
  9423. sourceGap: sourceGap,
  9424. targetGap: targetGap,
  9425. maxGap: Math.max(sourceGap, targetGap),
  9426. setGeometry:_setGeometry,
  9427. getGeometry:_getGeometry
  9428. };
  9429. };
  9430. _ju.extend(_jp.Connectors.AbstractConnector, AbstractComponent);
  9431. // ********************************* END OF CONNECTOR TYPES *******************************************************************
  9432. // ********************************* ENDPOINT TYPES *******************************************************************
  9433. _jp.Endpoints.AbstractEndpoint = function (params) {
  9434. AbstractComponent.apply(this, arguments);
  9435. var compute = this.compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9436. var out = this._compute.apply(this, arguments);
  9437. this.x = out[0];
  9438. this.y = out[1];
  9439. this.w = out[2];
  9440. this.h = out[3];
  9441. this.bounds.minX = this.x;
  9442. this.bounds.minY = this.y;
  9443. this.bounds.maxX = this.x + this.w;
  9444. this.bounds.maxY = this.y + this.h;
  9445. return out;
  9446. };
  9447. return {
  9448. compute: compute,
  9449. cssClass: params.cssClass
  9450. };
  9451. };
  9452. _ju.extend(_jp.Endpoints.AbstractEndpoint, AbstractComponent);
  9453. /**
  9454. * Class: Endpoints.Dot
  9455. * A round endpoint, with default radius 10 pixels.
  9456. */
  9457. /**
  9458. * Function: Constructor
  9459. *
  9460. * Parameters:
  9461. *
  9462. * radius - radius of the endpoint. defaults to 10 pixels.
  9463. */
  9464. _jp.Endpoints.Dot = function (params) {
  9465. this.type = "Dot";
  9466. var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  9467. params = params || {};
  9468. this.radius = params.radius || 10;
  9469. this.defaultOffset = 0.5 * this.radius;
  9470. this.defaultInnerRadius = this.radius / 3;
  9471. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9472. this.radius = endpointStyle.radius || this.radius;
  9473. var x = anchorPoint[0] - this.radius,
  9474. y = anchorPoint[1] - this.radius,
  9475. w = this.radius * 2,
  9476. h = this.radius * 2;
  9477. if (endpointStyle.stroke) {
  9478. var lw = endpointStyle.strokeWidth || 1;
  9479. x -= lw;
  9480. y -= lw;
  9481. w += (lw * 2);
  9482. h += (lw * 2);
  9483. }
  9484. return [ x, y, w, h, this.radius ];
  9485. };
  9486. };
  9487. _ju.extend(_jp.Endpoints.Dot, _jp.Endpoints.AbstractEndpoint);
  9488. _jp.Endpoints.Rectangle = function (params) {
  9489. this.type = "Rectangle";
  9490. var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  9491. params = params || {};
  9492. this.width = params.width || 20;
  9493. this.height = params.height || 20;
  9494. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9495. var width = endpointStyle.width || this.width,
  9496. height = endpointStyle.height || this.height,
  9497. x = anchorPoint[0] - (width / 2),
  9498. y = anchorPoint[1] - (height / 2);
  9499. return [ x, y, width, height];
  9500. };
  9501. };
  9502. _ju.extend(_jp.Endpoints.Rectangle, _jp.Endpoints.AbstractEndpoint);
  9503. var DOMElementEndpoint = function (params) {
  9504. _jp.jsPlumbUIComponent.apply(this, arguments);
  9505. this._jsPlumb.displayElements = [];
  9506. };
  9507. _ju.extend(DOMElementEndpoint, _jp.jsPlumbUIComponent, {
  9508. getDisplayElements: function () {
  9509. return this._jsPlumb.displayElements;
  9510. },
  9511. appendDisplayElement: function (el) {
  9512. this._jsPlumb.displayElements.push(el);
  9513. }
  9514. });
  9515. /**
  9516. * Class: Endpoints.Image
  9517. * Draws an image as the Endpoint.
  9518. */
  9519. /**
  9520. * Function: Constructor
  9521. *
  9522. * Parameters:
  9523. *
  9524. * src - location of the image to use.
  9525. TODO: multiple references to self. not sure quite how to get rid of them entirely. perhaps self = null in the cleanup
  9526. function will suffice
  9527. TODO this class still might leak memory.
  9528. */
  9529. _jp.Endpoints.Image = function (params) {
  9530. this.type = "Image";
  9531. DOMElementEndpoint.apply(this, arguments);
  9532. _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  9533. var _onload = params.onload,
  9534. src = params.src || params.url,
  9535. clazz = params.cssClass ? " " + params.cssClass : "";
  9536. this._jsPlumb.img = new Image();
  9537. this._jsPlumb.ready = false;
  9538. this._jsPlumb.initialized = false;
  9539. this._jsPlumb.deleted = false;
  9540. this._jsPlumb.widthToUse = params.width;
  9541. this._jsPlumb.heightToUse = params.height;
  9542. this._jsPlumb.endpoint = params.endpoint;
  9543. this._jsPlumb.img.onload = function () {
  9544. if (this._jsPlumb != null) {
  9545. this._jsPlumb.ready = true;
  9546. this._jsPlumb.widthToUse = this._jsPlumb.widthToUse || this._jsPlumb.img.width;
  9547. this._jsPlumb.heightToUse = this._jsPlumb.heightToUse || this._jsPlumb.img.height;
  9548. if (_onload) {
  9549. _onload(this);
  9550. }
  9551. }
  9552. }.bind(this);
  9553. /*
  9554. Function: setImage
  9555. Sets the Image to use in this Endpoint.
  9556. Parameters:
  9557. img - may be a URL or an Image object
  9558. onload - optional; a callback to execute once the image has loaded.
  9559. */
  9560. this._jsPlumb.endpoint.setImage = function (_img, onload) {
  9561. var s = _img.constructor == String ? _img : _img.src;
  9562. _onload = onload;
  9563. this._jsPlumb.img.src = s;
  9564. if (this.canvas != null)
  9565. this.canvas.setAttribute("src", this._jsPlumb.img.src);
  9566. }.bind(this);
  9567. this._jsPlumb.endpoint.setImage(src, _onload);
  9568. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9569. this.anchorPoint = anchorPoint;
  9570. if (this._jsPlumb.ready) return [anchorPoint[0] - this._jsPlumb.widthToUse / 2, anchorPoint[1] - this._jsPlumb.heightToUse / 2,
  9571. this._jsPlumb.widthToUse, this._jsPlumb.heightToUse];
  9572. else return [0, 0, 0, 0];
  9573. };
  9574. this.canvas = _jp.createElement("img", {
  9575. position:"absolute",
  9576. margin:0,
  9577. padding:0,
  9578. outline:0
  9579. }, this._jsPlumb.instance.endpointClass + clazz);
  9580. if (this._jsPlumb.widthToUse) this.canvas.setAttribute("width", this._jsPlumb.widthToUse);
  9581. if (this._jsPlumb.heightToUse) this.canvas.setAttribute("height", this._jsPlumb.heightToUse);
  9582. this._jsPlumb.instance.appendElement(this.canvas);
  9583. this.actuallyPaint = function (d, style, anchor) {
  9584. if (!this._jsPlumb.deleted) {
  9585. if (!this._jsPlumb.initialized) {
  9586. this.canvas.setAttribute("src", this._jsPlumb.img.src);
  9587. this.appendDisplayElement(this.canvas);
  9588. this._jsPlumb.initialized = true;
  9589. }
  9590. var x = this.anchorPoint[0] - (this._jsPlumb.widthToUse / 2),
  9591. y = this.anchorPoint[1] - (this._jsPlumb.heightToUse / 2);
  9592. _ju.sizeElement(this.canvas, x, y, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse);
  9593. }
  9594. };
  9595. this.paint = function (style, anchor) {
  9596. if (this._jsPlumb != null) { // may have been deleted
  9597. if (this._jsPlumb.ready) {
  9598. this.actuallyPaint(style, anchor);
  9599. }
  9600. else {
  9601. root.setTimeout(function () {
  9602. this.paint(style, anchor);
  9603. }.bind(this), 200);
  9604. }
  9605. }
  9606. };
  9607. };
  9608. _ju.extend(_jp.Endpoints.Image, [ DOMElementEndpoint, _jp.Endpoints.AbstractEndpoint ], {
  9609. cleanup: function (force) {
  9610. if (force) {
  9611. this._jsPlumb.deleted = true;
  9612. if (this.canvas) this.canvas.parentNode.removeChild(this.canvas);
  9613. this.canvas = null;
  9614. }
  9615. }
  9616. });
  9617. /*
  9618. * Class: Endpoints.Blank
  9619. * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints.
  9620. */
  9621. _jp.Endpoints.Blank = function (params) {
  9622. var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  9623. this.type = "Blank";
  9624. DOMElementEndpoint.apply(this, arguments);
  9625. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9626. return [anchorPoint[0], anchorPoint[1], 10, 0];
  9627. };
  9628. var clazz = params.cssClass ? " " + params.cssClass : "";
  9629. this.canvas = _jp.createElement("div", {
  9630. display: "block",
  9631. width: "1px",
  9632. height: "1px",
  9633. background: "transparent",
  9634. position: "absolute"
  9635. }, this._jsPlumb.instance.endpointClass + clazz);
  9636. this._jsPlumb.instance.appendElement(this.canvas);
  9637. this.paint = function (style, anchor) {
  9638. _ju.sizeElement(this.canvas, this.x, this.y, this.w, this.h);
  9639. };
  9640. };
  9641. _ju.extend(_jp.Endpoints.Blank, [_jp.Endpoints.AbstractEndpoint, DOMElementEndpoint], {
  9642. cleanup: function () {
  9643. if (this.canvas && this.canvas.parentNode) {
  9644. this.canvas.parentNode.removeChild(this.canvas);
  9645. }
  9646. }
  9647. });
  9648. /*
  9649. * Class: Endpoints.Triangle
  9650. * A triangular Endpoint.
  9651. */
  9652. /*
  9653. * Function: Constructor
  9654. *
  9655. * Parameters:
  9656. *
  9657. * width - width of the triangle's base. defaults to 55 pixels.
  9658. * height - height of the triangle from base to apex. defaults to 55 pixels.
  9659. */
  9660. _jp.Endpoints.Triangle = function (params) {
  9661. this.type = "Triangle";
  9662. _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
  9663. params = params || { };
  9664. params.width = params.width || 55;
  9665. params.height = params.height || 55;
  9666. this.width = params.width;
  9667. this.height = params.height;
  9668. this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  9669. var width = endpointStyle.width || self.width,
  9670. height = endpointStyle.height || self.height,
  9671. x = anchorPoint[0] - (width / 2),
  9672. y = anchorPoint[1] - (height / 2);
  9673. return [ x, y, width, height ];
  9674. };
  9675. };
  9676. // ********************************* END OF ENDPOINT TYPES *******************************************************************
  9677. // ********************************* OVERLAY DEFINITIONS ***********************************************************************
  9678. var AbstractOverlay = _jp.Overlays.AbstractOverlay = function (params) {
  9679. this.visible = true;
  9680. this.isAppendedAtTopLevel = true;
  9681. this.component = params.component;
  9682. this.loc = params.location == null ? 0.5 : params.location;
  9683. this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation;
  9684. this.visible = params.visible !== false;
  9685. };
  9686. AbstractOverlay.prototype = {
  9687. cleanup: function (force) {
  9688. if (force) {
  9689. this.component = null;
  9690. this.canvas = null;
  9691. this.endpointLoc = null;
  9692. }
  9693. },
  9694. reattach:function(instance) {
  9695. },
  9696. setVisible: function (val) {
  9697. this.visible = val;
  9698. this.component.repaint();
  9699. },
  9700. isVisible: function () {
  9701. return this.visible;
  9702. },
  9703. hide: function () {
  9704. this.setVisible(false);
  9705. },
  9706. show: function () {
  9707. this.setVisible(true);
  9708. },
  9709. incrementLocation: function (amount) {
  9710. this.loc += amount;
  9711. this.component.repaint();
  9712. },
  9713. setLocation: function (l) {
  9714. this.loc = l;
  9715. this.component.repaint();
  9716. },
  9717. getLocation: function () {
  9718. return this.loc;
  9719. },
  9720. updateFrom:function() { }
  9721. };
  9722. /*
  9723. * Class: Overlays.Arrow
  9724. *
  9725. * 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
  9726. * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
  9727. * 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
  9728. * across the tail.
  9729. */
  9730. /*
  9731. * @constructor
  9732. *
  9733. * @param {Object} params Constructor params.
  9734. * @param {Number} [params.length] Distance in pixels from head to tail baseline. default 20.
  9735. * @param {Number} [params.width] Width in pixels of the tail baseline. default 20.
  9736. * @param {String} [params.fill] Style to use when filling the arrow. defaults to "black".
  9737. * @param {String} [params.stroke] Style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
  9738. * @param {Number} [params.stroke-width] Line width to use when stroking the arrow. defaults to 1, but only used if stroke is not null.
  9739. * @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.
  9740. * @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.
  9741. * @param {NUmber} [params.direction] Indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
  9742. */
  9743. _jp.Overlays.Arrow = function (params) {
  9744. this.type = "Arrow";
  9745. AbstractOverlay.apply(this, arguments);
  9746. this.isAppendedAtTopLevel = false;
  9747. params = params || {};
  9748. this.length = params.length || 20;
  9749. this.width = params.width || 20;
  9750. this.id = params.id;
  9751. var direction = (params.direction || 1) < 0 ? -1 : 1,
  9752. paintStyle = params.paintStyle || { "stroke-width": 1 },
  9753. // how far along the arrow the lines folding back in come to. default is 62.3%.
  9754. foldback = params.foldback || 0.623;
  9755. this.computeMaxSize = function () {
  9756. return self.width * 1.5;
  9757. };
  9758. this.elementCreated = function(p, component) {
  9759. this.path = p;
  9760. if (params.events) {
  9761. for (var i in params.events) {
  9762. _jp.on(p, i, params.events[i]);
  9763. }
  9764. }
  9765. };
  9766. this.draw = function (component, currentConnectionPaintStyle) {
  9767. var hxy, mid, txy, tail, cxy;
  9768. if (component.pointAlongPathFrom) {
  9769. if (_ju.isString(this.loc) || this.loc > 1 || this.loc < 0) {
  9770. var l = parseInt(this.loc, 10),
  9771. fromLoc = this.loc < 0 ? 1 : 0;
  9772. hxy = component.pointAlongPathFrom(fromLoc, l, false);
  9773. mid = component.pointAlongPathFrom(fromLoc, l - (direction * this.length / 2), false);
  9774. txy = _jg.pointOnLine(hxy, mid, this.length);
  9775. }
  9776. else if (this.loc == 1) {
  9777. hxy = component.pointOnPath(this.loc);
  9778. mid = component.pointAlongPathFrom(this.loc, -(this.length));
  9779. txy = _jg.pointOnLine(hxy, mid, this.length);
  9780. if (direction == -1) {
  9781. var _ = txy;
  9782. txy = hxy;
  9783. hxy = _;
  9784. }
  9785. }
  9786. else if (this.loc === 0) {
  9787. txy = component.pointOnPath(this.loc);
  9788. mid = component.pointAlongPathFrom(this.loc, this.length);
  9789. hxy = _jg.pointOnLine(txy, mid, this.length);
  9790. if (direction == -1) {
  9791. var __ = txy;
  9792. txy = hxy;
  9793. hxy = __;
  9794. }
  9795. }
  9796. else {
  9797. hxy = component.pointAlongPathFrom(this.loc, direction * this.length / 2);
  9798. mid = component.pointOnPath(this.loc);
  9799. txy = _jg.pointOnLine(hxy, mid, this.length);
  9800. }
  9801. tail = _jg.perpendicularLineTo(hxy, txy, this.width);
  9802. cxy = _jg.pointOnLine(hxy, txy, foldback * this.length);
  9803. var d = { hxy: hxy, tail: tail, cxy: cxy },
  9804. stroke = paintStyle.stroke || currentConnectionPaintStyle.stroke,
  9805. fill = paintStyle.fill || currentConnectionPaintStyle.stroke,
  9806. lineWidth = paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth;
  9807. return {
  9808. component: component,
  9809. d: d,
  9810. "stroke-width": lineWidth,
  9811. stroke: stroke,
  9812. fill: fill,
  9813. minX: Math.min(hxy.x, tail[0].x, tail[1].x),
  9814. maxX: Math.max(hxy.x, tail[0].x, tail[1].x),
  9815. minY: Math.min(hxy.y, tail[0].y, tail[1].y),
  9816. maxY: Math.max(hxy.y, tail[0].y, tail[1].y)
  9817. };
  9818. }
  9819. else return {component: component, minX: 0, maxX: 0, minY: 0, maxY: 0};
  9820. };
  9821. };
  9822. _ju.extend(_jp.Overlays.Arrow, AbstractOverlay, {
  9823. updateFrom:function(d) {
  9824. this.length = d.length || this.length;
  9825. this.width = d.width|| this.width;
  9826. this.direction = d.direction != null ? d.direction : this.direction;
  9827. this.foldback = d.foldback|| this.foldback;
  9828. }
  9829. });
  9830. /*
  9831. * Class: Overlays.PlainArrow
  9832. *
  9833. * 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
  9834. * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
  9835. * a 'call' to Arrow with foldback set appropriately.
  9836. */
  9837. /*
  9838. * Function: Constructor
  9839. * See <Overlays.Arrow> for allowed parameters for this overlay.
  9840. */
  9841. _jp.Overlays.PlainArrow = function (params) {
  9842. params = params || {};
  9843. var p = _jp.extend(params, {foldback: 1});
  9844. _jp.Overlays.Arrow.call(this, p);
  9845. this.type = "PlainArrow";
  9846. };
  9847. _ju.extend(_jp.Overlays.PlainArrow, _jp.Overlays.Arrow);
  9848. /*
  9849. * Class: Overlays.Diamond
  9850. *
  9851. * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
  9852. * happens that in this case, that point is greater than the length of the the arrow.
  9853. *
  9854. * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
  9855. * 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
  9856. * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
  9857. * would be -l/4 in this case - move along one quarter of the total length.
  9858. */
  9859. /*
  9860. * Function: Constructor
  9861. * See <Overlays.Arrow> for allowed parameters for this overlay.
  9862. */
  9863. _jp.Overlays.Diamond = function (params) {
  9864. params = params || {};
  9865. var l = params.length || 40,
  9866. p = _jp.extend(params, {length: l / 2, foldback: 2});
  9867. _jp.Overlays.Arrow.call(this, p);
  9868. this.type = "Diamond";
  9869. };
  9870. _ju.extend(_jp.Overlays.Diamond, _jp.Overlays.Arrow);
  9871. var _getDimensions = function (component, forceRefresh) {
  9872. if (component._jsPlumb.cachedDimensions == null || forceRefresh)
  9873. component._jsPlumb.cachedDimensions = component.getDimensions();
  9874. return component._jsPlumb.cachedDimensions;
  9875. };
  9876. // abstract superclass for overlays that add an element to the DOM.
  9877. var AbstractDOMOverlay = function (params) {
  9878. _jp.jsPlumbUIComponent.apply(this, arguments);
  9879. AbstractOverlay.apply(this, arguments);
  9880. // hand off fired events to associated component.
  9881. var _f = this.fire;
  9882. this.fire = function () {
  9883. _f.apply(this, arguments);
  9884. if (this.component) this.component.fire.apply(this.component, arguments);
  9885. };
  9886. this.detached=false;
  9887. this.id = params.id;
  9888. this._jsPlumb.div = null;
  9889. this._jsPlumb.initialised = false;
  9890. this._jsPlumb.component = params.component;
  9891. this._jsPlumb.cachedDimensions = null;
  9892. this._jsPlumb.create = params.create;
  9893. this._jsPlumb.initiallyInvisible = params.visible === false;
  9894. this.getElement = function () {
  9895. if (this._jsPlumb.div == null) {
  9896. var div = this._jsPlumb.div = _jp.getElement(this._jsPlumb.create(this._jsPlumb.component));
  9897. div.style.position = "absolute";
  9898. div.className = this._jsPlumb.instance.overlayClass + " " +
  9899. (this.cssClass ? this.cssClass :
  9900. params.cssClass ? params.cssClass : "");
  9901. this._jsPlumb.instance.appendElement(div);
  9902. this._jsPlumb.instance.getId(div);
  9903. this.canvas = div;
  9904. // in IE the top left corner is what it placed at the desired location. This will not
  9905. // be fixed. IE8 is not going to be supported for much longer.
  9906. var ts = "translate(-50%, -50%)";
  9907. div.style.webkitTransform = ts;
  9908. div.style.mozTransform = ts;
  9909. div.style.msTransform = ts;
  9910. div.style.oTransform = ts;
  9911. div.style.transform = ts;
  9912. // write the related component into the created element
  9913. div._jsPlumb = this;
  9914. if (params.visible === false)
  9915. div.style.display = "none";
  9916. }
  9917. return this._jsPlumb.div;
  9918. };
  9919. this.draw = function (component, currentConnectionPaintStyle, absolutePosition) {
  9920. var td = _getDimensions(this);
  9921. if (td != null && td.length == 2) {
  9922. var cxy = { x: 0, y: 0 };
  9923. // absolutePosition would have been set by a call to connection.setAbsoluteOverlayPosition.
  9924. if (absolutePosition) {
  9925. cxy = { x: absolutePosition[0], y: absolutePosition[1] };
  9926. }
  9927. else if (component.pointOnPath) {
  9928. var loc = this.loc, absolute = false;
  9929. if (_ju.isString(this.loc) || this.loc < 0 || this.loc > 1) {
  9930. loc = parseInt(this.loc, 10);
  9931. absolute = true;
  9932. }
  9933. cxy = component.pointOnPath(loc, absolute); // a connection
  9934. }
  9935. else {
  9936. var locToUse = this.loc.constructor == Array ? this.loc : this.endpointLoc;
  9937. cxy = { x: locToUse[0] * component.w,
  9938. y: locToUse[1] * component.h };
  9939. }
  9940. var minx = cxy.x - (td[0] / 2),
  9941. miny = cxy.y - (td[1] / 2);
  9942. return {
  9943. component: component,
  9944. d: { minx: minx, miny: miny, td: td, cxy: cxy },
  9945. minX: minx,
  9946. maxX: minx + td[0],
  9947. minY: miny,
  9948. maxY: miny + td[1]
  9949. };
  9950. }
  9951. else return {minX: 0, maxX: 0, minY: 0, maxY: 0};
  9952. };
  9953. };
  9954. _ju.extend(AbstractDOMOverlay, [_jp.jsPlumbUIComponent, AbstractOverlay], {
  9955. getDimensions: function () {
  9956. return [1,1];
  9957. },
  9958. setVisible: function (state) {
  9959. if (this._jsPlumb.div) {
  9960. this._jsPlumb.div.style.display = state ? "block" : "none";
  9961. // if initially invisible, dimensions are 0,0 and never get updated
  9962. if (state && this._jsPlumb.initiallyInvisible) {
  9963. _getDimensions(this, true);
  9964. this.component.repaint();
  9965. this._jsPlumb.initiallyInvisible = false;
  9966. }
  9967. }
  9968. },
  9969. /*
  9970. * Function: clearCachedDimensions
  9971. * Clears the cached dimensions for the label. As a performance enhancement, label dimensions are
  9972. * cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but
  9973. * there are other reasons why the text dimensions might change - if you make a change through CSS, for
  9974. * example, you might change the font size. in that case you should explicitly call this method.
  9975. */
  9976. clearCachedDimensions: function () {
  9977. this._jsPlumb.cachedDimensions = null;
  9978. },
  9979. cleanup: function (force) {
  9980. if (force) {
  9981. if (this._jsPlumb.div != null) {
  9982. this._jsPlumb.div._jsPlumb = null;
  9983. this._jsPlumb.instance.removeElement(this._jsPlumb.div);
  9984. }
  9985. }
  9986. else {
  9987. // if not a forced cleanup, just detach child from parent for now.
  9988. if (this._jsPlumb && this._jsPlumb.div && this._jsPlumb.div.parentNode)
  9989. this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
  9990. this.detached = true;
  9991. }
  9992. },
  9993. reattach:function(instance) {
  9994. if (this._jsPlumb.div != null) instance.getContainer().appendChild(this._jsPlumb.div);
  9995. this.detached = false;
  9996. },
  9997. computeMaxSize: function () {
  9998. var td = _getDimensions(this);
  9999. return Math.max(td[0], td[1]);
  10000. },
  10001. paint: function (p, containerExtents) {
  10002. if (!this._jsPlumb.initialised) {
  10003. this.getElement();
  10004. p.component.appendDisplayElement(this._jsPlumb.div);
  10005. this._jsPlumb.initialised = true;
  10006. if (this.detached) this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
  10007. }
  10008. this._jsPlumb.div.style.left = (p.component.x + p.d.minx) + "px";
  10009. this._jsPlumb.div.style.top = (p.component.y + p.d.miny) + "px";
  10010. }
  10011. });
  10012. /*
  10013. * Class: Overlays.Custom
  10014. * A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it.
  10015. * The 'create' function is passed a Connection or Endpoint.
  10016. */
  10017. /*
  10018. * Function: Constructor
  10019. *
  10020. * Parameters:
  10021. * create - function for jsPlumb to call that returns a DOM element.
  10022. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  10023. * id - optional id to use for later retrieval of this overlay.
  10024. *
  10025. */
  10026. _jp.Overlays.Custom = function (params) {
  10027. this.type = "Custom";
  10028. AbstractDOMOverlay.apply(this, arguments);
  10029. };
  10030. _ju.extend(_jp.Overlays.Custom, AbstractDOMOverlay);
  10031. _jp.Overlays.GuideLines = function () {
  10032. var self = this;
  10033. self.length = 50;
  10034. self.strokeWidth = 5;
  10035. this.type = "GuideLines";
  10036. AbstractOverlay.apply(this, arguments);
  10037. _jp.jsPlumbUIComponent.apply(this, arguments);
  10038. this.draw = function (connector, currentConnectionPaintStyle) {
  10039. var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
  10040. mid = connector.pointOnPath(self.loc),
  10041. tail = _jg.pointOnLine(head, mid, self.length),
  10042. tailLine = _jg.perpendicularLineTo(head, tail, 40),
  10043. headLine = _jg.perpendicularLineTo(tail, head, 20);
  10044. return {
  10045. connector: connector,
  10046. head: head,
  10047. tail: tail,
  10048. headLine: headLine,
  10049. tailLine: tailLine,
  10050. minX: Math.min(head.x, tail.x, headLine[0].x, headLine[1].x),
  10051. minY: Math.min(head.y, tail.y, headLine[0].y, headLine[1].y),
  10052. maxX: Math.max(head.x, tail.x, headLine[0].x, headLine[1].x),
  10053. maxY: Math.max(head.y, tail.y, headLine[0].y, headLine[1].y)
  10054. };
  10055. };
  10056. // this.cleanup = function() { }; // nothing to clean up for GuideLines
  10057. };
  10058. /*
  10059. * Class: Overlays.Label
  10060. */
  10061. /*
  10062. * Function: Constructor
  10063. *
  10064. * Parameters:
  10065. * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
  10066. * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
  10067. * 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
  10068. * label function returns null. empty strings _will_ be painted.
  10069. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  10070. * id - optional id to use for later retrieval of this overlay.
  10071. *
  10072. *
  10073. */
  10074. _jp.Overlays.Label = function (params) {
  10075. this.labelStyle = params.labelStyle;
  10076. var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
  10077. this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null;
  10078. var p = _jp.extend({
  10079. create: function () {
  10080. return _jp.createElement("div");
  10081. }}, params);
  10082. _jp.Overlays.Custom.call(this, p);
  10083. this.type = "Label";
  10084. this.label = params.label || "";
  10085. this.labelText = null;
  10086. if (this.labelStyle) {
  10087. var el = this.getElement();
  10088. this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
  10089. el.style.font = this.labelStyle.font;
  10090. el.style.color = this.labelStyle.color || "black";
  10091. if (this.labelStyle.fill) el.style.background = this.labelStyle.fill;
  10092. if (this.labelStyle.borderWidth > 0) {
  10093. var dStyle = this.labelStyle.borderStyle ? this.labelStyle.borderStyle : "black";
  10094. el.style.border = this.labelStyle.borderWidth + "px solid " + dStyle;
  10095. }
  10096. if (this.labelStyle.padding) el.style.padding = this.labelStyle.padding;
  10097. }
  10098. };
  10099. _ju.extend(_jp.Overlays.Label, _jp.Overlays.Custom, {
  10100. cleanup: function (force) {
  10101. if (force) {
  10102. this.div = null;
  10103. this.label = null;
  10104. this.labelText = null;
  10105. this.cssClass = null;
  10106. this.labelStyle = null;
  10107. }
  10108. },
  10109. getLabel: function () {
  10110. return this.label;
  10111. },
  10112. /*
  10113. * Function: setLabel
  10114. * sets the label's, um, label. you would think i'd call this function
  10115. * 'setText', but you can pass either a Function or a String to this, so
  10116. * it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep
  10117. * that in mind if you need escaped HTML.
  10118. */
  10119. setLabel: function (l) {
  10120. this.label = l;
  10121. this.labelText = null;
  10122. this.clearCachedDimensions();
  10123. this.update();
  10124. this.component.repaint();
  10125. },
  10126. getDimensions: function () {
  10127. this.update();
  10128. return AbstractDOMOverlay.prototype.getDimensions.apply(this, arguments);
  10129. },
  10130. update: function () {
  10131. if (typeof this.label == "function") {
  10132. var lt = this.label(this);
  10133. this.getElement().innerHTML = lt.replace(/\r\n/g, "<br/>");
  10134. }
  10135. else {
  10136. if (this.labelText == null) {
  10137. this.labelText = this.label;
  10138. this.getElement().innerHTML = this.labelText.replace(/\r\n/g, "<br/>");
  10139. }
  10140. }
  10141. },
  10142. updateFrom:function(d) {
  10143. if(d.label != null){
  10144. this.setLabel(d.label);
  10145. }
  10146. }
  10147. });
  10148. // ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
  10149. }).call(typeof window !== 'undefined' ? window : this);
  10150. /*
  10151. * jsPlumb
  10152. *
  10153. * Title:jsPlumb 2.3.0
  10154. *
  10155. * Provides a way to visually connect elements on an HTML page, using SVG.
  10156. *
  10157. * This file contains the base class for library adapters.
  10158. *
  10159. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  10160. *
  10161. * http://jsplumbtoolkit.com
  10162. * http://github.com/sporritt/jsplumb
  10163. *
  10164. * Dual licensed under the MIT and GPL2 licenses.
  10165. */
  10166. ;(function() {
  10167. "use strict";
  10168. var root = this,
  10169. _jp = root.jsPlumb;
  10170. var _getEventManager = function(instance) {
  10171. var e = instance._mottle;
  10172. if (!e) {
  10173. e = instance._mottle = new root.Mottle();
  10174. }
  10175. return e;
  10176. };
  10177. _jp.extend(root.jsPlumbInstance.prototype, {
  10178. getEventManager:function() {
  10179. return _getEventManager(this);
  10180. },
  10181. on : function(el, event, callback) {
  10182. // TODO: here we would like to map the tap event if we know its
  10183. // an internal bind to a click. we have to know its internal because only
  10184. // then can we be sure that the UP event wont be consumed (tap is a synthesized
  10185. // event from a mousedown followed by a mouseup).
  10186. //event = { "click":"tap", "dblclick":"dbltap"}[event] || event;
  10187. this.getEventManager().on.apply(this, arguments);
  10188. return this;
  10189. },
  10190. off : function(el, event, callback) {
  10191. this.getEventManager().off.apply(this, arguments);
  10192. return this;
  10193. }
  10194. });
  10195. }).call(typeof window !== 'undefined' ? window : this);
  10196. /*
  10197. * jsPlumb
  10198. *
  10199. * Title:jsPlumb 2.3.0
  10200. *
  10201. * Provides a way to visually connect elements on an HTML page, using SVG.
  10202. *
  10203. * This file contains the code for working with Groups.
  10204. *
  10205. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  10206. *
  10207. * http://jsplumbtoolkit.com
  10208. * http://github.com/sporritt/jsplumb
  10209. *
  10210. * Dual licensed under the MIT and GPL2 licenses.
  10211. */
  10212. ;(function() {
  10213. "use strict";
  10214. var root = this,
  10215. _ju = root.jsPlumbUtil,
  10216. _jpi = root.jsPlumbInstance;
  10217. var GROUP_COLLAPSED_CLASS = "jtk-group-collapsed";
  10218. var GROUP_EXPANDED_CLASS = "jtk-group-expanded";
  10219. var GROUP_CONTAINER_SELECTOR = "[jtk-group-content]";
  10220. var ELEMENT_DRAGGABLE_EVENT = "elementDraggable";
  10221. var STOP = "stop";
  10222. var REVERT = "revert";
  10223. var GROUP_MANAGER = "_groupManager";
  10224. var GROUP = "_jsPlumbGroup";
  10225. var GROUP_DRAG_SCOPE = "_jsPlumbGroupDrag";
  10226. var EVT_CHILD_ADDED = "group:addMember";
  10227. var EVT_CHILD_REMOVED = "group:removeMember";
  10228. var EVT_GROUP_ADDED = "group:add";
  10229. var EVT_GROUP_REMOVED = "group:remove";
  10230. var EVT_EXPAND = "group:expand";
  10231. var EVT_COLLAPSE = "group:collapse";
  10232. var EVT_GROUP_DRAG_STOP = "groupDragStop";
  10233. var EVT_CONNECTION_MOVED = "connectionMoved";
  10234. var EVT_INTERNAL_CONNECTION_DETACHED = "internal.connectionDetached";
  10235. var CMD_REMOVE_ALL = "removeAll";
  10236. var CMD_ORPHAN_ALL = "orphanAll";
  10237. var CMD_SHOW = "show";
  10238. var CMD_HIDE = "hide";
  10239. var GroupManager = function(_jsPlumb) {
  10240. var _managedGroups = {}, _connectionSourceMap = {}, _connectionTargetMap = {}, self = this;
  10241. _jsPlumb.bind("connection", function(p) {
  10242. if (p.source[GROUP] != null && p.target[GROUP] != null && p.source[GROUP] === p.target[GROUP]) {
  10243. _connectionSourceMap[p.connection.id] = p.source[GROUP];
  10244. _connectionTargetMap[p.connection.id] = p.source[GROUP];
  10245. }
  10246. else {
  10247. if (p.source[GROUP] != null) {
  10248. _ju.suggest(p.source[GROUP].connections.source, p.connection);
  10249. _connectionSourceMap[p.connection.id] = p.source[GROUP];
  10250. }
  10251. if (p.target[GROUP] != null) {
  10252. _ju.suggest(p.target[GROUP].connections.target, p.connection);
  10253. _connectionTargetMap[p.connection.id] = p.target[GROUP];
  10254. }
  10255. }
  10256. });
  10257. function _cleanupDetachedConnection(conn) {
  10258. delete conn.proxies;
  10259. var group = _connectionSourceMap[conn.id], f;
  10260. if (group != null) {
  10261. f = function(c) { return c.id === conn.id; };
  10262. _ju.removeWithFunction(group.connections.source, f);
  10263. _ju.removeWithFunction(group.connections.target, f);
  10264. delete _connectionSourceMap[conn.id];
  10265. }
  10266. group = _connectionTargetMap[conn.id];
  10267. if (group != null) {
  10268. f = function(c) { return c.id === conn.id; };
  10269. _ju.removeWithFunction(group.connections.source, f);
  10270. _ju.removeWithFunction(group.connections.target, f);
  10271. delete _connectionTargetMap[conn.id];
  10272. }
  10273. }
  10274. _jsPlumb.bind(EVT_INTERNAL_CONNECTION_DETACHED, function(p) {
  10275. _cleanupDetachedConnection(p.connection);
  10276. });
  10277. _jsPlumb.bind(EVT_CONNECTION_MOVED, function(p) {
  10278. var connMap = p.index === 0 ? _connectionSourceMap : _connectionTargetMap;
  10279. var group = connMap[p.connection.id];
  10280. if (group) {
  10281. var list = group.connections[p.index === 0 ? "source" : "target"];
  10282. var idx = list.indexOf(p.connection);
  10283. if (idx != -1) {
  10284. list.splice(idx, 1);
  10285. }
  10286. }
  10287. });
  10288. this.addGroup = function(group) {
  10289. _jsPlumb.addClass(group.getEl(), GROUP_EXPANDED_CLASS);
  10290. _managedGroups[group.id] = group;
  10291. group.manager = this;
  10292. _updateConnectionsForGroup(group);
  10293. _jsPlumb.fire(EVT_GROUP_ADDED, { group:group });
  10294. };
  10295. this.addToGroup = function(group, el, doNotFireEvent) {
  10296. group = this.getGroup(group);
  10297. if (group) {
  10298. //group.add(el, doNotFireEvent);
  10299. var groupEl = group.getEl();
  10300. if (el._isJsPlumbGroup) return;
  10301. var currentGroup = el._jsPlumbGroup;
  10302. // if already a member of this group, do nothing
  10303. if (currentGroup !== group) {
  10304. var elpos = _jsPlumb.getOffset(el, true);
  10305. var cpos = group.collapsed ? _jsPlumb.getOffset(groupEl, true) : _jsPlumb.getOffset(group.getDragArea(), true);
  10306. // otherwise, transfer to this group.
  10307. if (currentGroup != null) {
  10308. currentGroup.remove(el, doNotFireEvent);
  10309. self.updateConnectionsForGroup(currentGroup);
  10310. }
  10311. group.add(el, doNotFireEvent);
  10312. var handleDroppedConnections = function (list, index) {
  10313. var oidx = index == 0 ? 1 : 0;
  10314. list.each(function (c) {
  10315. c.setVisible(false);
  10316. if (c.endpoints[oidx].element._jsPlumbGroup === group) {
  10317. c.endpoints[oidx].setVisible(false);
  10318. self.expandConnection(c, oidx, group);
  10319. }
  10320. else {
  10321. c.endpoints[index].setVisible(false);
  10322. self.collapseConnection(c, index, group);
  10323. }
  10324. });
  10325. };
  10326. if (group.collapsed) {
  10327. handleDroppedConnections(_jsPlumb.select({source: el}), 0);
  10328. handleDroppedConnections(_jsPlumb.select({target: el}), 1);
  10329. }
  10330. var elId = _jsPlumb.getId(el);
  10331. _jsPlumb.dragManager.setParent(el, elId, groupEl, _jsPlumb.getId(groupEl), elpos);
  10332. var newPosition = { left: elpos.left - cpos.left, top: elpos.top - cpos.top };
  10333. _jsPlumb.setPosition(el, newPosition);
  10334. _jsPlumb.dragManager.revalidateParent(el, elId, elpos);
  10335. self.updateConnectionsForGroup(group);
  10336. _jsPlumb.revalidate(elId);
  10337. setTimeout(function () {
  10338. _jsPlumb.fire(EVT_CHILD_ADDED, {group: group, el: el});
  10339. }, 0);
  10340. }
  10341. }
  10342. };
  10343. this.removeFromGroup = function(group, el, doNotFireEvent) {
  10344. group = this.getGroup(group);
  10345. if (group) {
  10346. group.remove(el, null, doNotFireEvent);
  10347. }
  10348. };
  10349. this.getGroup = function(groupId) {
  10350. var group = groupId;
  10351. if (_ju.isString(groupId)) {
  10352. group = _managedGroups[groupId];
  10353. if (group == null) throw new TypeError("No such group [" + groupId + "]");
  10354. }
  10355. return group;
  10356. };
  10357. this.getGroups = function() {
  10358. var o = [];
  10359. for (var g in _managedGroups) {
  10360. o.push(_managedGroups[g]);
  10361. }
  10362. return o;
  10363. };
  10364. this.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
  10365. group = this.getGroup(group);
  10366. this.expandGroup(group, true); // this reinstates any original connections and removes all proxies, but does not fire an event.
  10367. group[deleteMembers ? CMD_REMOVE_ALL : CMD_ORPHAN_ALL](manipulateDOM, doNotFireEvent);
  10368. _jsPlumb.remove(group.getEl());
  10369. delete _managedGroups[group.id];
  10370. delete _jsPlumb._groups[group.id];
  10371. _jsPlumb.fire(EVT_GROUP_REMOVED, { group:group });
  10372. };
  10373. this.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
  10374. for (var g in _managedGroups) {
  10375. this.removeGroup(_managedGroups[g], deleteMembers, manipulateDOM, doNotFireEvent);
  10376. }
  10377. };
  10378. function _setVisible(group, state) {
  10379. var m = group.getMembers();
  10380. for (var i = 0; i < m.length; i++) {
  10381. _jsPlumb[state ? CMD_SHOW : CMD_HIDE](m[i], true);
  10382. }
  10383. }
  10384. var _collapseConnection = this.collapseConnection = function(c, index, group) {
  10385. var proxyEp, groupEl = group.getEl(), groupElId = _jsPlumb.getId(groupEl),
  10386. originalElementId = c.endpoints[index].elementId;
  10387. var otherEl = c.endpoints[index === 0 ? 1 : 0].element;
  10388. if (otherEl[GROUP] && (!otherEl[GROUP].shouldProxy() && otherEl[GROUP].collapsed)) {
  10389. return;
  10390. }
  10391. c.proxies = c.proxies || [];
  10392. if(c.proxies[index]) {
  10393. proxyEp = c.proxies[index].ep;
  10394. }else {
  10395. proxyEp = _jsPlumb.addEndpoint(groupEl, {
  10396. endpoint:group.getEndpoint(c, index),
  10397. anchor:group.getAnchor(c, index),
  10398. parameters:{
  10399. isProxyEndpoint:true
  10400. }
  10401. });
  10402. }
  10403. proxyEp.setDeleteOnEmpty(true);
  10404. // for this index, stash proxy info: the new EP, the original EP.
  10405. c.proxies[index] = { ep:proxyEp, originalEp: c.endpoints[index] };
  10406. // and advise the anchor manager
  10407. if (index === 0) {
  10408. // TODO why are there two differently named methods? Why is there not one method that says "some end of this
  10409. // connection changed (you give the index), and here's the new element and element id."
  10410. _jsPlumb.anchorManager.sourceChanged(originalElementId, groupElId, c, groupEl);
  10411. }
  10412. else {
  10413. _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, originalElementId, groupElId, c);
  10414. c.target = groupEl;
  10415. c.targetId = groupElId;
  10416. }
  10417. // detach the original EP from the connection.
  10418. c.proxies[index].originalEp.detachFromConnection(c, null, true);
  10419. // set the proxy as the new ep
  10420. proxyEp.connections = [ c ];
  10421. c.endpoints[index] = proxyEp;
  10422. c.setVisible(true);
  10423. };
  10424. this.collapseGroup = function(group) {
  10425. group = this.getGroup(group);
  10426. if (group == null || group.collapsed) return;
  10427. var groupEl = group.getEl();
  10428. // todo remove old proxy endpoints first, just in case?
  10429. //group.proxies.length = 0;
  10430. // hide all connections
  10431. _setVisible(group, false);
  10432. if (group.shouldProxy()) {
  10433. // collapses all connections in a group.
  10434. var _collapseSet = function (conns, index) {
  10435. for (var i = 0; i < conns.length; i++) {
  10436. var c = conns[i];
  10437. _collapseConnection(c, index, group);
  10438. }
  10439. };
  10440. // setup proxies for sources and targets
  10441. _collapseSet(group.connections.source, 0);
  10442. _collapseSet(group.connections.target, 1);
  10443. }
  10444. group.collapsed = true;
  10445. _jsPlumb.removeClass(groupEl, GROUP_EXPANDED_CLASS);
  10446. _jsPlumb.addClass(groupEl, GROUP_COLLAPSED_CLASS);
  10447. _jsPlumb.revalidate(groupEl);
  10448. _jsPlumb.fire(EVT_COLLAPSE, { group:group });
  10449. };
  10450. var _expandConnection = this.expandConnection = function(c, index, group) {
  10451. // if no proxies or none for this end of the connection, abort.
  10452. if (c.proxies == null || c.proxies[index] == null) return;
  10453. var groupElId = _jsPlumb.getId(group.getEl()),
  10454. originalElement = c.proxies[index].originalEp.element,
  10455. originalElementId = c.proxies[index].originalEp.elementId;
  10456. c.endpoints[index] = c.proxies[index].originalEp;
  10457. // and advise the anchor manager
  10458. if (index === 0) {
  10459. // TODO why are there two differently named methods? Why is there not one method that says "some end of this
  10460. // connection changed (you give the index), and here's the new element and element id."
  10461. _jsPlumb.anchorManager.sourceChanged(groupElId, originalElementId, c, originalElement);
  10462. }
  10463. else {
  10464. _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, groupElId, originalElementId, c);
  10465. c.target = originalElement;
  10466. c.targetId = originalElementId;
  10467. }
  10468. // detach the proxy EP from the connection (which will cause it to be removed as we no longer need it)
  10469. c.proxies[index].ep.detachFromConnection(c, null);
  10470. c.proxies[index].originalEp.addConnection(c);
  10471. // cleanup
  10472. delete c.proxies[index];
  10473. };
  10474. this.expandGroup = function(group, doNotFireEvent) {
  10475. group = this.getGroup(group);
  10476. if (group == null || !group.collapsed) return;
  10477. var groupEl = group.getEl();
  10478. _setVisible(group, true);
  10479. if (group.shouldProxy()) {
  10480. // collapses all connections in a group.
  10481. var _expandSet = function (conns, index) {
  10482. for (var i = 0; i < conns.length; i++) {
  10483. var c = conns[i];
  10484. _expandConnection(c, index, group);
  10485. }
  10486. };
  10487. // setup proxies for sources and targets
  10488. _expandSet(group.connections.source, 0);
  10489. _expandSet(group.connections.target, 1);
  10490. }
  10491. group.collapsed = false;
  10492. _jsPlumb.addClass(groupEl, GROUP_EXPANDED_CLASS);
  10493. _jsPlumb.removeClass(groupEl, GROUP_COLLAPSED_CLASS);
  10494. _jsPlumb.revalidate(groupEl);
  10495. this.repaintGroup(group);
  10496. if (!doNotFireEvent) {
  10497. _jsPlumb.fire(EVT_EXPAND, { group: group});
  10498. }
  10499. };
  10500. this.repaintGroup = function(group) {
  10501. group = this.getGroup(group);
  10502. var m = group.getMembers();
  10503. for (var i = 0; i < m.length; i++) {
  10504. _jsPlumb.revalidate(m[i]);
  10505. }
  10506. };
  10507. // TODO refactor this with the code that responds to `connection` events.
  10508. function _updateConnectionsForGroup(group) {
  10509. var members = group.getMembers();
  10510. var c1 = _jsPlumb.getConnections({source:members}, true);
  10511. var c2 = _jsPlumb.getConnections({target:members}, true);
  10512. var processed = {};
  10513. group.connections.source.length = 0;
  10514. group.connections.target.length = 0;
  10515. var oneSet = function(c) {
  10516. for (var i = 0; i < c.length; i++) {
  10517. if (processed[c[i].id]) continue;
  10518. processed[c[i].id] = true;
  10519. if (c[i].source._jsPlumbGroup === group) {
  10520. if (c[i].target._jsPlumbGroup !== group) {
  10521. group.connections.source.push(c[i]);
  10522. }
  10523. _connectionSourceMap[c[i].id] = group;
  10524. }
  10525. else if (c[i].target._jsPlumbGroup === group) {
  10526. group.connections.target.push(c[i]);
  10527. _connectionTargetMap[c[i].id] = group;
  10528. }
  10529. }
  10530. };
  10531. oneSet(c1); oneSet(c2);
  10532. }
  10533. this.updateConnectionsForGroup = _updateConnectionsForGroup;
  10534. this.refreshAllGroups = function() {
  10535. for (var g in _managedGroups) {
  10536. _updateConnectionsForGroup(_managedGroups[g]);
  10537. _jsPlumb.dragManager.updateOffsets(_jsPlumb.getId(_managedGroups[g].getEl()));
  10538. }
  10539. };
  10540. };
  10541. /**
  10542. *
  10543. * @param {jsPlumbInstance} _jsPlumb Associated jsPlumb instance.
  10544. * @param {Object} params
  10545. * @param {Element} params.el The DOM element representing the Group.
  10546. * @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.
  10547. * @param {Boolean} [params.constrain=false] If true, child elements will not be able to be dragged outside of the Group container.
  10548. * @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`.
  10549. * @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).
  10550. * @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.
  10551. * @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`.
  10552. * @constructor
  10553. */
  10554. var Group = function(_jsPlumb, params) {
  10555. var self = this;
  10556. var el = params.el;
  10557. this.getEl = function() { return el; };
  10558. this.id = params.id || _ju.uuid();
  10559. el._isJsPlumbGroup = true;
  10560. var getDragArea = this.getDragArea = function() {
  10561. var da = _jsPlumb.getSelector(el, GROUP_CONTAINER_SELECTOR);
  10562. return da && da.length > 0 ? da[0] : el;
  10563. };
  10564. var ghost = params.ghost === true;
  10565. var constrain = ghost || (params.constrain === true);
  10566. var revert = params.revert !== false;
  10567. var orphan = params.orphan === true;
  10568. var prune = params.prune === true;
  10569. var dropOverride = params.dropOverride === true;
  10570. var proxied = params.proxied !== false;
  10571. var elements = [];
  10572. this.connections = { source:[], target:[], internal:[] };
  10573. // this function, and getEndpoint below, are stubs for a future setup in which we can choose endpoint
  10574. // and anchor based upon the connection and the index (source/target) of the endpoint to be proxied.
  10575. this.getAnchor = function(conn, endpointIndex) {
  10576. return params.anchor || "Continuous";
  10577. };
  10578. this.getEndpoint = function(conn, endpointIndex) {
  10579. return params.endpoint || [ "Dot", { radius:10 }];
  10580. };
  10581. this.collapsed = false;
  10582. if (params.draggable !== false) {
  10583. var opts = {
  10584. stop:function(params) {
  10585. _jsPlumb.fire(EVT_GROUP_DRAG_STOP, jsPlumb.extend(params, {group:self}));
  10586. },
  10587. scope:GROUP_DRAG_SCOPE
  10588. };
  10589. if (params.dragOptions) {
  10590. root.jsPlumb.extend(opts, params.dragOptions);
  10591. }
  10592. _jsPlumb.draggable(params.el, opts);
  10593. }
  10594. if (params.droppable !== false) {
  10595. _jsPlumb.droppable(params.el, {
  10596. drop:function(p) {
  10597. var el = p.drag.el;
  10598. if (el._isJsPlumbGroup) return;
  10599. var currentGroup = el._jsPlumbGroup;
  10600. if (currentGroup !== self) {
  10601. if (currentGroup != null) {
  10602. if (currentGroup.overrideDrop(el, self)) {
  10603. return;
  10604. }
  10605. }
  10606. _jsPlumb.getGroupManager().addToGroup(self, el, false);
  10607. }
  10608. }
  10609. });
  10610. }
  10611. var _each = function(_el, fn) {
  10612. var els = _el.nodeType == null ? _el : [ _el ];
  10613. for (var i = 0; i < els.length; i++) {
  10614. fn(els[i]);
  10615. }
  10616. };
  10617. this.overrideDrop = function(_el, targetGroup) {
  10618. return dropOverride && (revert || prune || orphan);
  10619. };
  10620. this.add = function(_el, doNotFireEvent) {
  10621. var dragArea = getDragArea();
  10622. _each(_el, function(__el) {
  10623. if (__el._jsPlumbGroup != null) {
  10624. if (__el._jsPlumbGroup === self) {
  10625. return;
  10626. } else {
  10627. __el._jsPlumbGroup.remove(__el, true, doNotFireEvent, false);
  10628. }
  10629. }
  10630. __el._jsPlumbGroup = self;
  10631. elements.push(__el);
  10632. // test if draggable and add handlers if so.
  10633. if (_jsPlumb.isAlreadyDraggable(__el)) {
  10634. _bindDragHandlers(__el);
  10635. }
  10636. if (__el.parentNode != dragArea) {
  10637. dragArea.appendChild(__el);
  10638. }
  10639. if (!doNotFireEvent) {
  10640. _jsPlumb.fire(EVT_CHILD_ADDED, {group: self, el: __el});
  10641. }
  10642. });
  10643. _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
  10644. };
  10645. this.remove = function(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections) {
  10646. _each(el, function(__el) {
  10647. delete __el._jsPlumbGroup;
  10648. _ju.removeWithFunction(elements, function(e) {
  10649. return e === __el;
  10650. });
  10651. if (manipulateDOM) {
  10652. try { self.getDragArea().removeChild(__el); }
  10653. catch (e) {
  10654. jsPlumbUtil.log("Could not remove element from Group " + e);
  10655. }
  10656. }
  10657. _unbindDragHandlers(__el);
  10658. if (!doNotFireEvent) {
  10659. _jsPlumb.fire(EVT_CHILD_REMOVED, {group: self, el: __el});
  10660. }
  10661. });
  10662. if (!doNotUpdateConnections) {
  10663. _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
  10664. }
  10665. };
  10666. this.removeAll = function(manipulateDOM, doNotFireEvent) {
  10667. for (var i = 0, l = elements.length; i < l; i++) {
  10668. self.remove(elements[0], manipulateDOM, doNotFireEvent, true);
  10669. }
  10670. elements.length = 0;
  10671. _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
  10672. };
  10673. this.orphanAll = function() {
  10674. for (var i = 0; i < elements.length; i++) {
  10675. _orphan(elements[i]);
  10676. }
  10677. elements.length = 0;
  10678. };
  10679. this.getMembers = function() { return elements; };
  10680. el[GROUP] = this;
  10681. _jsPlumb.bind(ELEMENT_DRAGGABLE_EVENT, function(dragParams) {
  10682. // if its for the current group,
  10683. if (dragParams.el._jsPlumbGroup == this) {
  10684. _bindDragHandlers(dragParams.el);
  10685. }
  10686. }.bind(this));
  10687. function _findParent(_el) {
  10688. return _el.offsetParent;
  10689. }
  10690. function _isInsideParent(_el, pos) {
  10691. var p = _findParent(_el),
  10692. s = _jsPlumb.getSize(p),
  10693. ss = _jsPlumb.getSize(_el),
  10694. leftEdge = pos[0],
  10695. rightEdge = leftEdge + ss[0],
  10696. topEdge = pos[1],
  10697. bottomEdge = topEdge + ss[1];
  10698. return rightEdge > 0 && leftEdge < s[0] && bottomEdge > 0 && topEdge < s[1];
  10699. }
  10700. //
  10701. // orphaning an element means taking it out of the group and adding it to the main jsplumb container.
  10702. //
  10703. function _orphan(_el) {
  10704. var id = _jsPlumb.getId(_el);
  10705. var pos = _jsPlumb.getOffset(_el);
  10706. _el.parentNode.removeChild(_el);
  10707. _jsPlumb.getContainer().appendChild(_el);
  10708. _jsPlumb.setPosition(_el, pos);
  10709. delete _el._jsPlumbGroup;
  10710. _unbindDragHandlers(_el);
  10711. _jsPlumb.dragManager.clearParent(_el, id);
  10712. }
  10713. //
  10714. // remove an element from the group, then either prune it from the jsplumb instance, or just orphan it.
  10715. //
  10716. function _pruneOrOrphan(p) {
  10717. if (!_isInsideParent(p.el, p.pos)) {
  10718. var group = p.el._jsPlumbGroup;
  10719. if (prune) {
  10720. _jsPlumb.remove(p.el);
  10721. } else {
  10722. _orphan(p.el);
  10723. }
  10724. group.remove(p.el);
  10725. }
  10726. }
  10727. //
  10728. // redraws the element
  10729. //
  10730. function _revalidate(_el) {
  10731. var id = _jsPlumb.getId(_el);
  10732. _jsPlumb.revalidate(_el);
  10733. _jsPlumb.dragManager.revalidateParent(_el, id);
  10734. }
  10735. //
  10736. // unbind the group specific drag/revert handlers.
  10737. //
  10738. function _unbindDragHandlers(_el) {
  10739. if (!_el._katavorioDrag) return;
  10740. if (prune || orphan) {
  10741. _el._katavorioDrag.off(STOP, _pruneOrOrphan);
  10742. }
  10743. if (!prune && !orphan && revert) {
  10744. _el._katavorioDrag.off(REVERT, _revalidate);
  10745. _el._katavorioDrag.setRevert(null);
  10746. }
  10747. }
  10748. function _bindDragHandlers(_el) {
  10749. if (!_el._katavorioDrag) return;
  10750. if (prune || orphan) {
  10751. _el._katavorioDrag.on(STOP, _pruneOrOrphan);
  10752. }
  10753. if (constrain) {
  10754. _el._katavorioDrag.setConstrain(true);
  10755. }
  10756. if (ghost) {
  10757. _el._katavorioDrag.setUseGhostProxy(true);
  10758. }
  10759. if (!prune && !orphan && revert) {
  10760. _el._katavorioDrag.on(REVERT, _revalidate);
  10761. _el._katavorioDrag.setRevert(function(__el, pos) {
  10762. return !_isInsideParent(__el, pos);
  10763. });
  10764. }
  10765. }
  10766. this.shouldProxy = function() {
  10767. return proxied;
  10768. };
  10769. _jsPlumb.getGroupManager().addGroup(this);
  10770. };
  10771. /**
  10772. * Adds a group to the jsPlumb instance.
  10773. * @method addGroup
  10774. * @param {Object} params
  10775. * @return {Group} The newly created Group.
  10776. */
  10777. _jpi.prototype.addGroup = function(params) {
  10778. var j = this;
  10779. j._groups = j._groups || {};
  10780. if (j._groups[params.id] != null) {
  10781. throw new TypeError("cannot create Group [" + params.id + "]; a Group with that ID exists");
  10782. }
  10783. if (params.el[GROUP] != null) {
  10784. throw new TypeError("cannot create Group [" + params.id + "]; the given element is already a Group");
  10785. }
  10786. var group = new Group(j, params);
  10787. j._groups[group.id] = group;
  10788. if (params.collapsed) {
  10789. this.collapseGroup(group);
  10790. }
  10791. return group;
  10792. };
  10793. /**
  10794. * Add an element to a group.
  10795. * @method addToGroup
  10796. * @param {String} group Group, or ID of the group, to add the element to.
  10797. * @param {Element} el Element to add to the group.
  10798. */
  10799. _jpi.prototype.addToGroup = function(group, el, doNotFireEvent) {
  10800. var _one = function(_el) {
  10801. var id = this.getId(_el);
  10802. this.manage(id, _el);
  10803. this.getGroupManager().addToGroup(group, _el, doNotFireEvent);
  10804. }.bind(this);
  10805. if (Array.isArray(el)) {
  10806. for (var i = 0; i < el.length; i++) {
  10807. _one(el[i]);
  10808. }
  10809. } else {
  10810. _one(el);
  10811. }
  10812. };
  10813. /**
  10814. * Remove an element from a group.
  10815. * @method removeFromGroup
  10816. * @param {String} group Group, or ID of the group, to remove the element from.
  10817. * @param {Element} el Element to add to the group.
  10818. */
  10819. _jpi.prototype.removeFromGroup = function(group, el, doNotFireEvent) {
  10820. this.getGroupManager().removeFromGroup(group, el, doNotFireEvent);
  10821. };
  10822. /**
  10823. * Remove a group, and optionally remove its members from the jsPlumb instance.
  10824. * @method removeGroup
  10825. * @param {String|Group} group Group to delete, or ID of Group to delete.
  10826. * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will
  10827. * just be 'orphaned' (returned to the main container).
  10828. */
  10829. _jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
  10830. this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent);
  10831. };
  10832. /**
  10833. * Remove all groups, and optionally remove their members from the jsPlumb instance.
  10834. * @method removeAllGroup
  10835. * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will
  10836. * just be 'orphaned' (returned to the main container).
  10837. */
  10838. _jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
  10839. this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent);
  10840. };
  10841. /**
  10842. * Get a Group
  10843. * @method getGroup
  10844. * @param {String} groupId ID of the group to get
  10845. * @return {Group} Group with the given ID, null if not found.
  10846. */
  10847. _jpi.prototype.getGroup = function(groupId) {
  10848. return this.getGroupManager().getGroup(groupId);
  10849. };
  10850. /**
  10851. * Gets all the Groups managed by the jsPlumb instance.
  10852. * @returns {Group[]} List of Groups. Empty if none.
  10853. */
  10854. _jpi.prototype.getGroups = function() {
  10855. return this.getGroupManager().getGroups();
  10856. };
  10857. /**
  10858. * Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group
  10859. * will vary from application to application. jsPlumb does these things:
  10860. *
  10861. * - Hides any connections that are internal to the group (connections between members, and connections from member of
  10862. * the group to the group itself)
  10863. * - Proxies all connections for which the source or target is a member of the group.
  10864. * - Hides the proxied connections.
  10865. * - Adds the jtk-group-expanded class to the group's element
  10866. * - Removes the jtk-group-collapsed class from the group's element.
  10867. *
  10868. * @method expandGroup
  10869. * @param {String|Group} group Group to expand, or ID of Group to expand.
  10870. */
  10871. _jpi.prototype.expandGroup = function(group) {
  10872. this.getGroupManager().expandGroup(group);
  10873. };
  10874. /**
  10875. * Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group
  10876. * will vary from application to application. jsPlumb does these things:
  10877. *
  10878. * - Shows any connections that are internal to the group (connections between members, and connections from member of
  10879. * the group to the group itself)
  10880. * - Removes proxies for all connections for which the source or target is a member of the group.
  10881. * - Shows the previously proxied connections.
  10882. * - Adds the jtk-group-collapsed class to the group's element
  10883. * - Removes the jtk-group-expanded class from the group's element.
  10884. *
  10885. * @method expandGroup
  10886. * @param {String|Group} group Group to expand, or ID of Group to expand.
  10887. */
  10888. _jpi.prototype.collapseGroup = function(groupId) {
  10889. this.getGroupManager().collapseGroup(groupId);
  10890. };
  10891. _jpi.prototype.repaintGroup = function(group) {
  10892. this.getGroupManager().repaintGroup(group);
  10893. };
  10894. /**
  10895. * Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method.
  10896. *
  10897. * @method toggleGroup
  10898. * @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse.
  10899. */
  10900. _jpi.prototype.toggleGroup = function(group) {
  10901. group = this.getGroupManager().getGroup(group);
  10902. if (group != null) {
  10903. this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group);
  10904. }
  10905. };
  10906. //
  10907. // lazy init a group manager for the given jsplumb instance.
  10908. //
  10909. _jpi.prototype.getGroupManager = function() {
  10910. var mgr = this[GROUP_MANAGER];
  10911. if (mgr == null) {
  10912. mgr = this[GROUP_MANAGER] = new GroupManager(this);
  10913. }
  10914. return mgr;
  10915. };
  10916. _jpi.prototype.removeGroupManager = function() {
  10917. delete this[GROUP_MANAGER];
  10918. };
  10919. /**
  10920. * Gets the Group that the given element belongs to, null if none.
  10921. * @method getGroupFor
  10922. * @param {String|Element} el Element, or element ID.
  10923. * @returns {Group} A Group, if found, or null.
  10924. */
  10925. _jpi.prototype.getGroupFor = function(el) {
  10926. el = this.getElement(el);
  10927. if (el) {
  10928. return el[GROUP];
  10929. }
  10930. };
  10931. }).call(typeof window !== 'undefined' ? window : this);
  10932. /*
  10933. * jsPlumb
  10934. *
  10935. * Title:jsPlumb 2.3.0
  10936. *
  10937. * Provides a way to visually connect elements on an HTML page, using SVG.
  10938. *
  10939. * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
  10940. *
  10941. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  10942. *
  10943. * http://jsplumbtoolkit.com
  10944. * http://github.com/sporritt/jsplumb
  10945. *
  10946. * Dual licensed under the MIT and GPL2 licenses.
  10947. */
  10948. ;
  10949. (function () {
  10950. "use strict";
  10951. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  10952. var Flowchart = function (params) {
  10953. this.type = "Flowchart";
  10954. params = params || {};
  10955. params.stub = params.stub == null ? 30 : params.stub;
  10956. var segments,
  10957. _super = _jp.Connectors.AbstractConnector.apply(this, arguments),
  10958. midpoint = params.midpoint == null ? 0.5 : params.midpoint,
  10959. alwaysRespectStubs = params.alwaysRespectStubs === true,
  10960. lastx = null, lasty = null, lastOrientation,
  10961. cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0,
  10962. // TODO now common between this and AbstractBezierEditor; refactor into superclass?
  10963. loopbackRadius = params.loopbackRadius || 25,
  10964. isLoopbackCurrently = false,
  10965. sgn = function (n) {
  10966. return n < 0 ? -1 : n === 0 ? 0 : 1;
  10967. },
  10968. /**
  10969. * helper method to add a segment.
  10970. */
  10971. addSegment = function (segments, x, y, paintInfo) {
  10972. if (lastx == x && lasty == y) return;
  10973. var lx = lastx == null ? paintInfo.sx : lastx,
  10974. ly = lasty == null ? paintInfo.sy : lasty,
  10975. o = lx == x ? "v" : "h",
  10976. sgnx = sgn(x - lx),
  10977. sgny = sgn(y - ly);
  10978. lastx = x;
  10979. lasty = y;
  10980. segments.push([lx, ly, x, y, o, sgnx, sgny]);
  10981. },
  10982. segLength = function (s) {
  10983. return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2));
  10984. },
  10985. _cloneArray = function (a) {
  10986. var _a = [];
  10987. _a.push.apply(_a, a);
  10988. return _a;
  10989. },
  10990. writeSegments = function (conn, segments, paintInfo) {
  10991. var current = null, next;
  10992. for (var i = 0; i < segments.length - 1; i++) {
  10993. current = current || _cloneArray(segments[i]);
  10994. next = _cloneArray(segments[i + 1]);
  10995. if (cornerRadius > 0 && current[4] != next[4]) {
  10996. var radiusToUse = Math.min(cornerRadius, segLength(current), segLength(next));
  10997. // right angle. adjust current segment's end point, and next segment's start point.
  10998. current[2] -= current[5] * radiusToUse;
  10999. current[3] -= current[6] * radiusToUse;
  11000. next[0] += next[5] * radiusToUse;
  11001. next[1] += next[6] * radiusToUse;
  11002. var ac = (current[6] == next[5] && next[5] == 1) ||
  11003. ((current[6] == next[5] && next[5] === 0) && current[5] != next[6]) ||
  11004. (current[6] == next[5] && next[5] == -1),
  11005. sgny = next[1] > current[3] ? 1 : -1,
  11006. sgnx = next[0] > current[2] ? 1 : -1,
  11007. sgnEqual = sgny == sgnx,
  11008. cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2],
  11009. cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1];
  11010. _super.addSegment(conn, "Straight", {
  11011. x1: current[0], y1: current[1], x2: current[2], y2: current[3]
  11012. });
  11013. _super.addSegment(conn, "Arc", {
  11014. r: radiusToUse,
  11015. x1: current[2],
  11016. y1: current[3],
  11017. x2: next[0],
  11018. y2: next[1],
  11019. cx: cx,
  11020. cy: cy,
  11021. ac: ac
  11022. });
  11023. }
  11024. else {
  11025. // dx + dy are used to adjust for line width.
  11026. var dx = (current[2] == current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2),
  11027. dy = (current[3] == current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2);
  11028. _super.addSegment(conn, "Straight", {
  11029. x1: current[0] - dx, y1: current[1] - dy, x2: current[2] + dx, y2: current[3] + dy
  11030. });
  11031. }
  11032. current = next;
  11033. }
  11034. if (next != null) {
  11035. // last segment
  11036. _super.addSegment(conn, "Straight", {
  11037. x1: next[0], y1: next[1], x2: next[2], y2: next[3]
  11038. });
  11039. }
  11040. };
  11041. this._compute = function (paintInfo, params) {
  11042. segments = [];
  11043. lastx = null;
  11044. lasty = null;
  11045. lastOrientation = null;
  11046. var commonStubCalculator = function () {
  11047. return [ paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY ];
  11048. },
  11049. stubCalculators = {
  11050. perpendicular: commonStubCalculator,
  11051. orthogonal: commonStubCalculator,
  11052. opposite: function (axis) {
  11053. var pi = paintInfo,
  11054. idx = axis == "x" ? 0 : 1,
  11055. areInProximity = {
  11056. "x": function () {
  11057. return ( (pi.so[idx] == 1 && (
  11058. ( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) ||
  11059. ( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) ||
  11060. ( (pi.so[idx] == -1 && (
  11061. ( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) ||
  11062. ( (pi.sx < pi.endStubX) && (pi.tx < pi.sx)))));
  11063. },
  11064. "y": function () {
  11065. return ( (pi.so[idx] == 1 && (
  11066. ( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) ||
  11067. ( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) ||
  11068. ( (pi.so[idx] == -1 && (
  11069. ( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) ||
  11070. ( (pi.sy < pi.endStubY) && (pi.ty < pi.sy)))));
  11071. }
  11072. };
  11073. if (!alwaysRespectStubs && areInProximity[axis]()) {
  11074. return {
  11075. "x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY],
  11076. "y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2]
  11077. }[axis];
  11078. }
  11079. else {
  11080. return [ paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY ];
  11081. }
  11082. }
  11083. };
  11084. // calculate Stubs.
  11085. var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis),
  11086. idx = paintInfo.sourceAxis == "x" ? 0 : 1,
  11087. oidx = paintInfo.sourceAxis == "x" ? 1 : 0,
  11088. ss = stubs[idx],
  11089. oss = stubs[oidx],
  11090. es = stubs[idx + 2],
  11091. oes = stubs[oidx + 2];
  11092. // add the start stub segment. use stubs for loopback as it will look better, with the loop spaced
  11093. // away from the element.
  11094. addSegment(segments, stubs[0], stubs[1], paintInfo);
  11095. // if its a loopback and we should treat it differently.
  11096. if (false &&params.sourcePos[0] == params.targetPos[0] && params.sourcePos[1] == params.targetPos[1]) {
  11097. // we use loopbackRadius here, as statemachine connectors do.
  11098. // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius,
  11099. // down by 2*radius, left by radius.
  11100. addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo);
  11101. addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
  11102. addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
  11103. addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo);
  11104. addSegment(segments, stubs[0], stubs[1], paintInfo);
  11105. }
  11106. else {
  11107. var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint),
  11108. midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint);
  11109. var orientations = { x: [ 0, 1 ], y: [ 1, 0 ] },
  11110. lineCalculators = {
  11111. perpendicular: function (axis) {
  11112. var pi = paintInfo,
  11113. sis = {
  11114. x: [
  11115. [ [ 1, 2, 3, 4 ], null, [ 2, 1, 4, 3 ] ],
  11116. null,
  11117. [ [ 4, 3, 2, 1 ], null, [ 3, 4, 1, 2 ] ]
  11118. ],
  11119. y: [
  11120. [ [ 3, 2, 1, 4 ], null, [ 2, 3, 4, 1 ] ],
  11121. null,
  11122. [ [ 4, 1, 2, 3 ], null, [ 1, 4, 3, 2 ] ]
  11123. ]
  11124. },
  11125. stubs = {
  11126. x: [ [ pi.startStubX, pi.endStubX ], null, [ pi.endStubX, pi.startStubX ] ],
  11127. y: [ [ pi.startStubY, pi.endStubY ], null, [ pi.endStubY, pi.startStubY ] ]
  11128. },
  11129. midLines = {
  11130. x: [ [ midx, pi.startStubY ], [ midx, pi.endStubY ] ],
  11131. y: [ [ pi.startStubX, midy ], [ pi.endStubX, midy ] ]
  11132. },
  11133. linesToEnd = {
  11134. x: [ [ pi.endStubX, pi.startStubY ] ],
  11135. y: [ [ pi.startStubX, pi.endStubY ] ]
  11136. },
  11137. startToEnd = {
  11138. x: [ [ pi.startStubX, pi.endStubY ], [ pi.endStubX, pi.endStubY ] ],
  11139. y: [ [ pi.endStubX, pi.startStubY ], [ pi.endStubX, pi.endStubY ] ]
  11140. },
  11141. startToMidToEnd = {
  11142. x: [ [ pi.startStubX, midy ], [ pi.endStubX, midy ], [ pi.endStubX, pi.endStubY ] ],
  11143. y: [ [ midx, pi.startStubY ], [ midx, pi.endStubY ], [ pi.endStubX, pi.endStubY ] ]
  11144. },
  11145. otherStubs = {
  11146. x: [ pi.startStubY, pi.endStubY ],
  11147. y: [ pi.startStubX, pi.endStubX ]
  11148. },
  11149. soIdx = orientations[axis][0], toIdx = orientations[axis][1],
  11150. _so = pi.so[soIdx] + 1,
  11151. _to = pi.to[toIdx] + 1,
  11152. otherFlipped = (pi.to[toIdx] == -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] == 1 && (otherStubs[axis][1] > otherStubs[axis][0])),
  11153. stub1 = stubs[axis][_so][0],
  11154. stub2 = stubs[axis][_so][1],
  11155. segmentIndexes = sis[axis][_so][_to];
  11156. if (pi.segment == segmentIndexes[3] || (pi.segment == segmentIndexes[2] && otherFlipped)) {
  11157. return midLines[axis];
  11158. }
  11159. else if (pi.segment == segmentIndexes[2] && stub2 < stub1) {
  11160. return linesToEnd[axis];
  11161. }
  11162. else if ((pi.segment == segmentIndexes[2] && stub2 >= stub1) || (pi.segment == segmentIndexes[1] && !otherFlipped)) {
  11163. return startToMidToEnd[axis];
  11164. }
  11165. else if (pi.segment == segmentIndexes[0] || (pi.segment == segmentIndexes[1] && otherFlipped)) {
  11166. return startToEnd[axis];
  11167. }
  11168. },
  11169. orthogonal: function (axis, startStub, otherStartStub, endStub, otherEndStub) {
  11170. var pi = paintInfo,
  11171. extent = {
  11172. "x": pi.so[0] == -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub),
  11173. "y": pi.so[1] == -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub)
  11174. }[axis];
  11175. return {
  11176. "x": [
  11177. [ extent, otherStartStub ],
  11178. [ extent, otherEndStub ],
  11179. [ endStub, otherEndStub ]
  11180. ],
  11181. "y": [
  11182. [ otherStartStub, extent ],
  11183. [ otherEndStub, extent ],
  11184. [ otherEndStub, endStub ]
  11185. ]
  11186. }[axis];
  11187. },
  11188. opposite: function (axis, ss, oss, es) {
  11189. var pi = paintInfo,
  11190. otherAxis = {"x": "y", "y": "x"}[axis],
  11191. dim = {"x": "height", "y": "width"}[axis],
  11192. comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"];
  11193. if (params.sourceEndpoint.elementId == params.targetEndpoint.elementId) {
  11194. var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub;
  11195. return {
  11196. "x": [
  11197. [ ss, _val ],
  11198. [ es, _val ]
  11199. ],
  11200. "y": [
  11201. [ _val, ss ],
  11202. [ _val, es ]
  11203. ]
  11204. }[axis];
  11205. }
  11206. else if (!comparator || (pi.so[idx] == 1 && ss > es) || (pi.so[idx] == -1 && ss < es)) {
  11207. return {
  11208. "x": [
  11209. [ ss, midy ],
  11210. [ es, midy ]
  11211. ],
  11212. "y": [
  11213. [ midx, ss ],
  11214. [ midx, es ]
  11215. ]
  11216. }[axis];
  11217. }
  11218. else if ((pi.so[idx] == 1 && ss < es) || (pi.so[idx] == -1 && ss > es)) {
  11219. return {
  11220. "x": [
  11221. [ midx, pi.sy ],
  11222. [ midx, pi.ty ]
  11223. ],
  11224. "y": [
  11225. [ pi.sx, midy ],
  11226. [ pi.tx, midy ]
  11227. ]
  11228. }[axis];
  11229. }
  11230. }
  11231. };
  11232. // compute the rest of the line
  11233. var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes);
  11234. if (p) {
  11235. for (var i = 0; i < p.length; i++) {
  11236. addSegment(segments, p[i][0], p[i][1], paintInfo);
  11237. }
  11238. }
  11239. // line to end stub
  11240. addSegment(segments, stubs[2], stubs[3], paintInfo);
  11241. }
  11242. // end stub to end (common)
  11243. addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo);
  11244. // write out the segments.
  11245. writeSegments(this, segments, paintInfo);
  11246. };
  11247. /*this.getPath = function () {
  11248. var _last = null, _lastAxis = null, s = [], segs = segments;
  11249. for (var i = 0; i < segs.length; i++) {
  11250. var seg = segs[i], axis = seg[4], axisIndex = (axis == "v" ? 3 : 2);
  11251. if (_last != null && _lastAxis === axis) {
  11252. _last[axisIndex] = seg[axisIndex];
  11253. }
  11254. else {
  11255. if (seg[0] != seg[2] || seg[1] != seg[3]) {
  11256. s.push({
  11257. start: [ seg[0], seg[1] ],
  11258. end: [ seg[2], seg[3] ]
  11259. });
  11260. _last = seg;
  11261. _lastAxis = seg[4];
  11262. }
  11263. }
  11264. }
  11265. return s;
  11266. };*/
  11267. };
  11268. _ju.extend(Flowchart, _jp.Connectors.AbstractConnector);
  11269. _jp.registerConnectorType(Flowchart, "Flowchart");
  11270. }).call(typeof window !== 'undefined' ? window : this);
  11271. /*
  11272. * jsPlumb
  11273. *
  11274. * Title:jsPlumb 2.3.0
  11275. *
  11276. * Provides a way to visually connect elements on an HTML page, using SVG.
  11277. *
  11278. * This file contains the code for the Bezier connector type.
  11279. *
  11280. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  11281. *
  11282. * http://jsplumbtoolkit.com
  11283. * http://github.com/sporritt/jsplumb
  11284. *
  11285. * Dual licensed under the MIT and GPL2 licenses.
  11286. */
  11287. ;
  11288. (function () {
  11289. "use strict";
  11290. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11291. _jp.Connectors.AbstractBezierConnector = function(params) {
  11292. params = params || {};
  11293. var showLoopback = params.showLoopback !== false,
  11294. curviness = params.curviness || 10,
  11295. margin = params.margin || 5,
  11296. proximityLimit = params.proximityLimit || 80,
  11297. clockwise = params.orientation && params.orientation === "clockwise",
  11298. loopbackRadius = params.loopbackRadius || 25,
  11299. isLoopbackCurrently = false,
  11300. _super;
  11301. this.overrideSetEditable = function() { return !isLoopbackCurrently; };
  11302. this._compute = function (paintInfo, p) {
  11303. var sp = p.sourcePos,
  11304. tp = p.targetPos,
  11305. _w = Math.abs(sp[0] - tp[0]),
  11306. _h = Math.abs(sp[1] - tp[1]);
  11307. if (!showLoopback || (p.sourceEndpoint.elementId !== p.targetEndpoint.elementId)) {
  11308. isLoopbackCurrently = false;
  11309. this._computeBezier(paintInfo, p, sp, tp, _w, _h);
  11310. } else {
  11311. isLoopbackCurrently = true;
  11312. // a loopback connector. draw an arc from one anchor to the other.
  11313. var x1 = p.sourcePos[0], y1 = p.sourcePos[1] - margin,
  11314. cx = x1, cy = y1 - loopbackRadius,
  11315. // canvas sizing stuff, to ensure the whole painted area is visible.
  11316. _x = cx - loopbackRadius,
  11317. _y = cy - loopbackRadius;
  11318. _w = 2 * loopbackRadius;
  11319. _h = 2 * loopbackRadius;
  11320. paintInfo.points[0] = _x;
  11321. paintInfo.points[1] = _y;
  11322. paintInfo.points[2] = _w;
  11323. paintInfo.points[3] = _h;
  11324. // ADD AN ARC SEGMENT.
  11325. _super.addSegment(this, "Arc", {
  11326. loopback: true,
  11327. x1: (x1 - _x) + 4,
  11328. y1: y1 - _y,
  11329. startAngle: 0,
  11330. endAngle: 2 * Math.PI,
  11331. r: loopbackRadius,
  11332. ac: !clockwise,
  11333. x2: (x1 - _x) - 4,
  11334. y2: y1 - _y,
  11335. cx: cx - _x,
  11336. cy: cy - _y
  11337. });
  11338. }
  11339. };
  11340. _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
  11341. return _super;
  11342. };
  11343. _ju.extend(_jp.Connectors.AbstractBezierConnector, _jp.Connectors.AbstractConnector);
  11344. var Bezier = function (params) {
  11345. params = params || {};
  11346. this.type = "Bezier";
  11347. var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
  11348. majorAnchor = params.curviness || 150,
  11349. minorAnchor = 10;
  11350. this.getCurviness = function () {
  11351. return majorAnchor;
  11352. };
  11353. this._findControlPoint = function (point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, soo, too) {
  11354. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  11355. // points around if so (code could be tightened up)
  11356. var perpendicular = soo[0] != too[0] || soo[1] == too[1],
  11357. p = [];
  11358. if (!perpendicular) {
  11359. if (soo[0] === 0) // X
  11360. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
  11361. else p.push(point[0] - (majorAnchor * soo[0]));
  11362. if (soo[1] === 0) // Y
  11363. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
  11364. else p.push(point[1] + (majorAnchor * too[1]));
  11365. }
  11366. else {
  11367. if (too[0] === 0) // X
  11368. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
  11369. else p.push(point[0] + (majorAnchor * too[0]));
  11370. if (too[1] === 0) // Y
  11371. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
  11372. else p.push(point[1] + (majorAnchor * soo[1]));
  11373. }
  11374. return p;
  11375. };
  11376. this._computeBezier = function (paintInfo, p, sp, tp, _w, _h) {
  11377. var geometry = this.getGeometry(), _CP, _CP2,
  11378. _sx = sp[0] < tp[0] ? _w : 0,
  11379. _sy = sp[1] < tp[1] ? _h : 0,
  11380. _tx = sp[0] < tp[0] ? 0 : _w,
  11381. _ty = sp[1] < tp[1] ? 0 : _h;
  11382. if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.controlPoints != null && geometry.controlPoints[0] != null && geometry.controlPoints[1] != null) {
  11383. _CP = geometry.controlPoints[0];
  11384. _CP2 = geometry.controlPoints[1];
  11385. }
  11386. else {
  11387. _CP = this._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint, paintInfo.so, paintInfo.to);
  11388. _CP2 = this._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint, paintInfo.to, paintInfo.so);
  11389. }
  11390. _super.setGeometry({controlPoints:[_CP, _CP2]}, true);
  11391. _super.addSegment(this, "Bezier", {
  11392. x1: _sx, y1: _sy, x2: _tx, y2: _ty,
  11393. cp1x: _CP[0], cp1y: _CP[1], cp2x: _CP2[0], cp2y: _CP2[1]
  11394. });
  11395. };
  11396. };
  11397. _ju.extend(Bezier, _jp.Connectors.AbstractBezierConnector);
  11398. _jp.registerConnectorType(Bezier, "Bezier");
  11399. }).call(typeof window !== 'undefined' ? window : this);
  11400. /*
  11401. * jsPlumb
  11402. *
  11403. * Title:jsPlumb 2.3.0
  11404. *
  11405. * Provides a way to visually connect elements on an HTML page, using SVG.
  11406. *
  11407. * This file contains the state machine connectors, which extend AbstractBezierConnector.
  11408. *
  11409. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  11410. *
  11411. * http://jsplumbtoolkit.com
  11412. * http://github.com/sporritt/jsplumb
  11413. *
  11414. * Dual licensed under the MIT and GPL2 licenses.
  11415. */
  11416. ;
  11417. (function () {
  11418. "use strict";
  11419. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11420. var _segment = function (x1, y1, x2, y2) {
  11421. if (x1 <= x2 && y2 <= y1) return 1;
  11422. else if (x1 <= x2 && y1 <= y2) return 2;
  11423. else if (x2 <= x1 && y2 >= y1) return 3;
  11424. return 4;
  11425. },
  11426. // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the
  11427. // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they
  11428. // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the
  11429. // 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
  11430. // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element
  11431. // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left.
  11432. //
  11433. // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are:
  11434. //
  11435. // 0 - absolute x
  11436. // 1 - absolute y
  11437. // 2 - proportional x in element (0 is left edge, 1 is right edge)
  11438. // 3 - proportional y in element (0 is top edge, 1 is bottom edge)
  11439. //
  11440. _findControlPoint = function (midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) {
  11441. // TODO (maybe)
  11442. // - if anchor pos is 0.5, make the control point take into account the relative position of the elements.
  11443. if (distance <= proximityLimit) return [midx, midy];
  11444. if (segment === 1) {
  11445. if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  11446. else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  11447. else return [ midx + (-1 * dx) , midy + (-1 * dy) ];
  11448. }
  11449. else if (segment === 2) {
  11450. if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  11451. else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  11452. else return [ midx + dx, midy + (-1 * dy) ];
  11453. }
  11454. else if (segment === 3) {
  11455. if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  11456. else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  11457. else return [ midx + (-1 * dx) , midy + (-1 * dy) ];
  11458. }
  11459. else if (segment === 4) {
  11460. if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
  11461. else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
  11462. else return [ midx + dx , midy + (-1 * dy) ];
  11463. }
  11464. };
  11465. var StateMachine = function (params) {
  11466. params = params || {};
  11467. this.type = "StateMachine";
  11468. var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
  11469. curviness = params.curviness || 10,
  11470. margin = params.margin || 5,
  11471. proximityLimit = params.proximityLimit || 80,
  11472. clockwise = params.orientation && params.orientation === "clockwise",
  11473. _controlPoint;
  11474. this._computeBezier = function(paintInfo, params, sp, tp, w, h) {
  11475. var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w,
  11476. _sy = params.sourcePos[1] < params.targetPos[1] ? 0 : h,
  11477. _tx = params.sourcePos[0] < params.targetPos[0] ? w : 0,
  11478. _ty = params.sourcePos[1] < params.targetPos[1] ? h : 0;
  11479. // now adjust for the margin
  11480. if (params.sourcePos[2] === 0) _sx -= margin;
  11481. if (params.sourcePos[2] === 1) _sx += margin;
  11482. if (params.sourcePos[3] === 0) _sy -= margin;
  11483. if (params.sourcePos[3] === 1) _sy += margin;
  11484. if (params.targetPos[2] === 0) _tx -= margin;
  11485. if (params.targetPos[2] === 1) _tx += margin;
  11486. if (params.targetPos[3] === 0) _ty -= margin;
  11487. if (params.targetPos[3] === 1) _ty += margin;
  11488. //
  11489. // these connectors are quadratic bezier curves, having a single control point. if both anchors
  11490. // are located at 0.5 on their respective faces, the control point is set to the midpoint and you
  11491. // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since
  11492. // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned
  11493. // at 'curviness' pixels away along the normal to the straight line connecting the two anchors.
  11494. //
  11495. // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes
  11496. // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node,
  11497. // for example, we might increase the distance the control point is away from the midpoint in a bid to
  11498. // steer it around that node. this will work within limits, but i think those limits would also be the likely
  11499. // limits for, once again, aesthetic good sense in the layout of a chart using these connectors.
  11500. //
  11501. // the second possible change is actually two possible changes: firstly, it is possible we should gradually
  11502. // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some
  11503. // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors
  11504. // with respect to how far their anchor is from the center of its respective face. this could either look cool,
  11505. // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time.
  11506. //
  11507. var _midx = (_sx + _tx) / 2,
  11508. _midy = (_sy + _ty) / 2,
  11509. segment = _segment(_sx, _sy, _tx, _ty),
  11510. distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)),
  11511. cp1x, cp2x, cp1y, cp2y,
  11512. geometry = _super.getGeometry();
  11513. if ((this.hasBeenEdited() || this.isEditing()) && geometry != null) {
  11514. cp1x = geometry.controlPoints[0][0];
  11515. cp1y = geometry.controlPoints[0][1];
  11516. cp2x = geometry.controlPoints[1][0];
  11517. cp2y = geometry.controlPoints[1][1];
  11518. }
  11519. else {
  11520. // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it
  11521. // will work by extending the control point to force the curve to be, um, curvier.
  11522. _controlPoint = _findControlPoint(_midx,
  11523. _midy,
  11524. segment,
  11525. params.sourcePos,
  11526. params.targetPos,
  11527. curviness, curviness,
  11528. distance,
  11529. proximityLimit);
  11530. cp1x = _controlPoint[0];
  11531. cp2x = _controlPoint[0];
  11532. cp1y = _controlPoint[1];
  11533. cp2y = _controlPoint[1];
  11534. _super.setGeometry({controlPoints:[_controlPoint, _controlPoint]}, true);
  11535. }
  11536. _super.addSegment(this, "Bezier", {
  11537. x1: _tx, y1: _ty, x2: _sx, y2: _sy,
  11538. cp1x: cp1x, cp1y: cp1y,
  11539. cp2x: cp2x, cp2y: cp2y
  11540. });
  11541. };
  11542. };
  11543. _ju.extend(StateMachine, _jp.Connectors.AbstractBezierConnector);
  11544. _jp.registerConnectorType(StateMachine, "StateMachine");
  11545. }).call(typeof window !== 'undefined' ? window : this);
  11546. /*
  11547. * jsPlumb
  11548. *
  11549. * Title:jsPlumb 2.3.0
  11550. *
  11551. * Provides a way to visually connect elements on an HTML page, using SVG.
  11552. *
  11553. * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
  11554. *
  11555. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  11556. *
  11557. * http://jsplumbtoolkit.com
  11558. * http://github.com/sporritt/jsplumb
  11559. *
  11560. * Dual licensed under the MIT and GPL2 licenses.
  11561. */
  11562. ;
  11563. (function () {
  11564. "use strict";
  11565. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11566. var STRAIGHT = "Straight";
  11567. var Straight = function (params) {
  11568. this.type = STRAIGHT;
  11569. var _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
  11570. this._compute = function (paintInfo, _) {
  11571. _super.addSegment(this, STRAIGHT, {x1: paintInfo.sx, y1: paintInfo.sy, x2: paintInfo.startStubX, y2: paintInfo.startStubY});
  11572. _super.addSegment(this, STRAIGHT, {x1: paintInfo.startStubX, y1: paintInfo.startStubY, x2: paintInfo.endStubX, y2: paintInfo.endStubY});
  11573. _super.addSegment(this, STRAIGHT, {x1: paintInfo.endStubX, y1: paintInfo.endStubY, x2: paintInfo.tx, y2: paintInfo.ty});
  11574. };
  11575. };
  11576. _ju.extend(Straight, _jp.Connectors.AbstractConnector);
  11577. _jp.registerConnectorType(Straight, STRAIGHT);
  11578. }).call(typeof window !== 'undefined' ? window : this);
  11579. /*
  11580. * jsPlumb
  11581. *
  11582. * Title:jsPlumb 2.3.0
  11583. *
  11584. * Provides a way to visually connect elements on an HTML page, using SVG.
  11585. *
  11586. * This file contains the SVG renderers.
  11587. *
  11588. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  11589. *
  11590. * http://jsplumbtoolkit.com
  11591. * http://github.com/sporritt/jsplumb
  11592. *
  11593. * Dual licensed under the MIT and GPL2 licenses.
  11594. */
  11595. ;
  11596. (function () {
  11597. // ************************** SVG utility methods ********************************************
  11598. "use strict";
  11599. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
  11600. var svgAttributeMap = {
  11601. "stroke-linejoin": "stroke-linejoin",
  11602. "stroke-dashoffset": "stroke-dashoffset",
  11603. "stroke-linecap": "stroke-linecap"
  11604. },
  11605. STROKE_DASHARRAY = "stroke-dasharray",
  11606. DASHSTYLE = "dashstyle",
  11607. LINEAR_GRADIENT = "linearGradient",
  11608. RADIAL_GRADIENT = "radialGradient",
  11609. DEFS = "defs",
  11610. FILL = "fill",
  11611. STOP = "stop",
  11612. STROKE = "stroke",
  11613. STROKE_WIDTH = "stroke-width",
  11614. STYLE = "style",
  11615. NONE = "none",
  11616. JSPLUMB_GRADIENT = "jsplumb_gradient_",
  11617. LINE_WIDTH = "strokeWidth",
  11618. ns = {
  11619. svg: "http://www.w3.org/2000/svg",
  11620. xhtml: "http://www.w3.org/1999/xhtml"
  11621. },
  11622. _attr = function (node, attributes) {
  11623. for (var i in attributes)
  11624. node.setAttribute(i, "" + attributes[i]);
  11625. },
  11626. _node = function (name, attributes) {
  11627. attributes = attributes || {};
  11628. attributes.version = "1.1";
  11629. attributes.xmlns = ns.xhtml;
  11630. return _jp.createElementNS(ns.svg, name, null, null, attributes);
  11631. },
  11632. _pos = function (d) {
  11633. return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px";
  11634. },
  11635. _clearGradient = function (parent) {
  11636. var els = parent.querySelectorAll(" defs,linearGradient,radialGradient");
  11637. for (var i = 0; i < els.length; i++)
  11638. els[i].parentNode.removeChild(els[i]);
  11639. },
  11640. _updateGradient = function (parent, node, style, dimensions, uiComponent) {
  11641. var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.instance.idstamp();
  11642. // first clear out any existing gradient
  11643. _clearGradient(parent);
  11644. // this checks for an 'offset' property in the gradient, and in the absence of it, assumes
  11645. // we want a linear gradient. if it's there, we create a radial gradient.
  11646. // it is possible that a more explicit means of defining the gradient type would be
  11647. // better. relying on 'offset' means that we can never have a radial gradient that uses
  11648. // some default offset, for instance.
  11649. // issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would
  11650. // not show gradients when the line was perfectly horizontal or vertical.
  11651. var g;
  11652. if (!style.gradient.offset)
  11653. g = _node(LINEAR_GRADIENT, {id: id, gradientUnits: "userSpaceOnUse"});
  11654. else
  11655. g = _node(RADIAL_GRADIENT, { id: id });
  11656. var defs = _node(DEFS);
  11657. parent.appendChild(defs);
  11658. defs.appendChild(g);
  11659. // the svg radial gradient seems to treat stops in the reverse
  11660. // order to how canvas does it. so we want to keep all the maths the same, but
  11661. // iterate the actual style declarations in reverse order, if the x indexes are not in order.
  11662. for (var i = 0; i < style.gradient.stops.length; i++) {
  11663. var styleToUse = uiComponent.segment == 1 || uiComponent.segment == 2 ? i : style.gradient.stops.length - 1 - i,
  11664. //stopColor = _ju.convertStyle(style.gradient.stops[styleToUse][1], true),
  11665. stopColor = style.gradient.stops[styleToUse][1],
  11666. s = _node(STOP, {"offset": Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color": stopColor});
  11667. g.appendChild(s);
  11668. }
  11669. var applyGradientTo = style.stroke ? STROKE : FILL;
  11670. node.setAttribute(applyGradientTo, "url(#" + id + ")");
  11671. },
  11672. _applyStyles = function (parent, node, style, dimensions, uiComponent) {
  11673. node.setAttribute(FILL, style.fill ? style.fill : NONE);
  11674. node.setAttribute(STROKE, style.stroke ? style.stroke : NONE);
  11675. if (style.gradient) {
  11676. _updateGradient(parent, node, style, dimensions, uiComponent);
  11677. }
  11678. else {
  11679. // make sure we clear any existing gradient
  11680. _clearGradient(parent);
  11681. node.setAttribute(STYLE, "");
  11682. }
  11683. if (style.strokeWidth) {
  11684. node.setAttribute(STROKE_WIDTH, style.strokeWidth);
  11685. }
  11686. // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
  11687. // the syntax in VML but is actually kind of nasty: values are given in the pixel
  11688. // coordinate space, whereas in VML they are multiples of the width of the stroked
  11689. // line, which makes a lot more sense. for that reason, jsPlumb is supporting both
  11690. // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
  11691. // VML, which will be the preferred method. the code below this converts a dashstyle
  11692. // attribute given in terms of stroke width into a pixel representation, by using the
  11693. // stroke's lineWidth.
  11694. if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) {
  11695. var sep = style[DASHSTYLE].indexOf(",") == -1 ? " " : ",",
  11696. parts = style[DASHSTYLE].split(sep),
  11697. styleToUse = "";
  11698. parts.forEach(function (p) {
  11699. styleToUse += (Math.floor(p * style.strokeWidth) + sep);
  11700. });
  11701. node.setAttribute(STROKE_DASHARRAY, styleToUse);
  11702. }
  11703. else if (style[STROKE_DASHARRAY]) {
  11704. node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]);
  11705. }
  11706. // extra attributes such as join type, dash offset.
  11707. for (var i in svgAttributeMap) {
  11708. if (style[i]) {
  11709. node.setAttribute(svgAttributeMap[i], style[i]);
  11710. }
  11711. }
  11712. },
  11713. _appendAtIndex = function (svg, path, idx) {
  11714. if (svg.childNodes.length > idx) {
  11715. svg.insertBefore(path, svg.childNodes[idx]);
  11716. }
  11717. else svg.appendChild(path);
  11718. };
  11719. /**
  11720. utility methods for other objects to use.
  11721. */
  11722. _ju.svg = {
  11723. node: _node,
  11724. attr: _attr,
  11725. pos: _pos
  11726. };
  11727. // ************************** / SVG utility methods ********************************************
  11728. /*
  11729. * Base class for SVG components.
  11730. */
  11731. var SvgComponent = function (params) {
  11732. var pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {};
  11733. _jp.jsPlumbUIComponent.apply(this, params.originalArgs);
  11734. this.canvas = null;
  11735. this.path = null;
  11736. this.svg = null;
  11737. this.bgCanvas = null;
  11738. var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""),
  11739. svgParams = {
  11740. "style": "",
  11741. "width": 0,
  11742. "height": 0,
  11743. "pointer-events": pointerEventsSpec,
  11744. "position": "absolute"
  11745. };
  11746. this.svg = _node("svg", svgParams);
  11747. if (params.useDivWrapper) {
  11748. this.canvas = _jp.createElement("div", { position : "absolute" });
  11749. _ju.sizeElement(this.canvas, 0, 0, 1, 1);
  11750. this.canvas.className = clazz;
  11751. }
  11752. else {
  11753. _attr(this.svg, { "class": clazz });
  11754. this.canvas = this.svg;
  11755. }
  11756. params._jsPlumb.appendElement(this.canvas, params.originalArgs[0].parent);
  11757. if (params.useDivWrapper) this.canvas.appendChild(this.svg);
  11758. var displayElements = [ this.canvas ];
  11759. this.getDisplayElements = function () {
  11760. return displayElements;
  11761. };
  11762. this.appendDisplayElement = function (el) {
  11763. displayElements.push(el);
  11764. };
  11765. this.paint = function (style, anchor, extents) {
  11766. if (style != null) {
  11767. var xy = [ this.x, this.y ], wh = [ this.w, this.h ], p;
  11768. if (extents != null) {
  11769. if (extents.xmin < 0) xy[0] += extents.xmin;
  11770. if (extents.ymin < 0) xy[1] += extents.ymin;
  11771. wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0);
  11772. wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0);
  11773. }
  11774. if (params.useDivWrapper) {
  11775. _ju.sizeElement(this.canvas, xy[0], xy[1], wh[0], wh[1]);
  11776. xy[0] = 0;
  11777. xy[1] = 0;
  11778. p = _pos([ 0, 0 ]);
  11779. }
  11780. else
  11781. p = _pos([ xy[0], xy[1] ]);
  11782. renderer.paint.apply(this, arguments);
  11783. _attr(this.svg, {
  11784. "style": p,
  11785. "width": wh[0] || 0,
  11786. "height": wh[1] || 0
  11787. });
  11788. }
  11789. };
  11790. return {
  11791. renderer: renderer
  11792. };
  11793. };
  11794. _ju.extend(SvgComponent, _jp.jsPlumbUIComponent, {
  11795. cleanup: function (force) {
  11796. if (force || this.typeId == null) {
  11797. if (this.canvas) this.canvas._jsPlumb = null;
  11798. if (this.svg) this.svg._jsPlumb = null;
  11799. if (this.bgCanvas) this.bgCanvas._jsPlumb = null;
  11800. if (this.canvas && this.canvas.parentNode)
  11801. this.canvas.parentNode.removeChild(this.canvas);
  11802. if (this.bgCanvas && this.bgCanvas.parentNode)
  11803. this.canvas.parentNode.removeChild(this.canvas);
  11804. this.svg = null;
  11805. this.canvas = null;
  11806. this.path = null;
  11807. this.group = null;
  11808. }
  11809. else {
  11810. // if not a forced cleanup, just detach from DOM for now.
  11811. if (this.canvas && this.canvas.parentNode) this.canvas.parentNode.removeChild(this.canvas);
  11812. if (this.bgCanvas && this.bgCanvas.parentNode) this.bgCanvas.parentNode.removeChild(this.bgCanvas);
  11813. }
  11814. },
  11815. reattach:function(instance) {
  11816. var c = instance.getContainer();
  11817. if (this.canvas && this.canvas.parentNode == null) c.appendChild(this.canvas);
  11818. if (this.bgCanvas && this.bgCanvas.parentNode == null) c.appendChild(this.bgCanvas);
  11819. },
  11820. setVisible: function (v) {
  11821. if (this.canvas) {
  11822. this.canvas.style.display = v ? "block" : "none";
  11823. }
  11824. }
  11825. });
  11826. /*
  11827. * Base class for SVG connectors.
  11828. */
  11829. _jp.ConnectorRenderers.svg = function (params) {
  11830. var self = this,
  11831. _super = SvgComponent.apply(this, [
  11832. {
  11833. cssClass: params._jsPlumb.connectorClass + (this.isEditable() ? " " + params._jsPlumb.editableConnectorClass : ""),
  11834. originalArgs: arguments,
  11835. pointerEventsSpec: "none",
  11836. _jsPlumb: params._jsPlumb
  11837. }
  11838. ]);
  11839. var _superSetEditable = this.setEditable;
  11840. this.setEditable = function(e) {
  11841. var result = _superSetEditable.apply(this, [e]);
  11842. _jp[result ? "addClass" : "removeClass"](this.canvas, this._jsPlumb.instance.editableConnectorClass);
  11843. };
  11844. _super.renderer.paint = function (style, anchor, extents) {
  11845. var segments = self.getSegments(), p = "", offset = [0, 0];
  11846. if (extents.xmin < 0) offset[0] = -extents.xmin;
  11847. if (extents.ymin < 0) offset[1] = -extents.ymin;
  11848. if (segments.length > 0) {
  11849. p = self.getPathData();
  11850. var a = {
  11851. d: p,
  11852. transform: "translate(" + offset[0] + "," + offset[1] + ")",
  11853. "pointer-events": params["pointer-events"] || "visibleStroke"
  11854. },
  11855. outlineStyle = null,
  11856. d = [self.x, self.y, self.w, self.h];
  11857. // outline style. actually means drawing an svg object underneath the main one.
  11858. if (style.outlineStroke) {
  11859. var outlineWidth = style.outlineWidth || 1,
  11860. outlineStrokeWidth = style.strokeWidth + (2 * outlineWidth);
  11861. outlineStyle = _jp.extend({}, style);
  11862. delete outlineStyle.gradient;
  11863. outlineStyle.stroke = style.outlineStroke;
  11864. outlineStyle.strokeWidth = outlineStrokeWidth;
  11865. if (self.bgPath == null) {
  11866. self.bgPath = _node("path", a);
  11867. _jp.addClass(self.bgPath, _jp.connectorOutlineClass);
  11868. _appendAtIndex(self.svg, self.bgPath, 0);
  11869. }
  11870. else {
  11871. _attr(self.bgPath, a);
  11872. }
  11873. _applyStyles(self.svg, self.bgPath, outlineStyle, d, self);
  11874. }
  11875. if (self.path == null) {
  11876. self.path = _node("path", a);
  11877. _appendAtIndex(self.svg, self.path, style.outlineStroke ? 1 : 0);
  11878. }
  11879. else {
  11880. _attr(self.path, a);
  11881. }
  11882. _applyStyles(self.svg, self.path, style, d, self);
  11883. }
  11884. };
  11885. };
  11886. _ju.extend(_jp.ConnectorRenderers.svg, SvgComponent);
  11887. // ******************************* svg segment renderer *****************************************************
  11888. // ******************************* /svg segments *****************************************************
  11889. /*
  11890. * Base class for SVG endpoints.
  11891. */
  11892. var SvgEndpoint = _jp.SvgEndpoint = function (params) {
  11893. var _super = SvgComponent.apply(this, [
  11894. {
  11895. cssClass: params._jsPlumb.endpointClass,
  11896. originalArgs: arguments,
  11897. pointerEventsSpec: "all",
  11898. useDivWrapper: true,
  11899. _jsPlumb: params._jsPlumb
  11900. }
  11901. ]);
  11902. _super.renderer.paint = function (style) {
  11903. var s = _jp.extend({}, style);
  11904. if (s.outlineStroke) {
  11905. s.strokeWidth = s.strokeWidth;
  11906. s.stroke = s.outlineStroke;
  11907. }
  11908. if (this.node == null) {
  11909. this.node = this.makeNode(s);
  11910. this.svg.appendChild(this.node);
  11911. }
  11912. else if (this.updateNode != null) {
  11913. this.updateNode(this.node);
  11914. }
  11915. _applyStyles(this.svg, this.node, s, [ this.x, this.y, this.w, this.h ], this);
  11916. _pos(this.node, [ this.x, this.y ]);
  11917. }.bind(this);
  11918. };
  11919. _ju.extend(SvgEndpoint, SvgComponent);
  11920. /*
  11921. * SVG Dot Endpoint
  11922. */
  11923. _jp.Endpoints.svg.Dot = function () {
  11924. _jp.Endpoints.Dot.apply(this, arguments);
  11925. SvgEndpoint.apply(this, arguments);
  11926. this.makeNode = function (style) {
  11927. return _node("circle", {
  11928. "cx": this.w / 2,
  11929. "cy": this.h / 2,
  11930. "r": this.radius
  11931. });
  11932. };
  11933. this.updateNode = function (node) {
  11934. _attr(node, {
  11935. "cx": this.w / 2,
  11936. "cy": this.h / 2,
  11937. "r": this.radius
  11938. });
  11939. };
  11940. };
  11941. _ju.extend(_jp.Endpoints.svg.Dot, [_jp.Endpoints.Dot, SvgEndpoint]);
  11942. /*
  11943. * SVG Rectangle Endpoint
  11944. */
  11945. _jp.Endpoints.svg.Rectangle = function () {
  11946. _jp.Endpoints.Rectangle.apply(this, arguments);
  11947. SvgEndpoint.apply(this, arguments);
  11948. this.makeNode = function (style) {
  11949. return _node("rect", {
  11950. "width": this.w,
  11951. "height": this.h
  11952. });
  11953. };
  11954. this.updateNode = function (node) {
  11955. _attr(node, {
  11956. "width": this.w,
  11957. "height": this.h
  11958. });
  11959. };
  11960. };
  11961. _ju.extend(_jp.Endpoints.svg.Rectangle, [_jp.Endpoints.Rectangle, SvgEndpoint]);
  11962. /*
  11963. * SVG Image Endpoint is the default image endpoint.
  11964. */
  11965. _jp.Endpoints.svg.Image = _jp.Endpoints.Image;
  11966. /*
  11967. * Blank endpoint in svg renderer is the default Blank endpoint.
  11968. */
  11969. _jp.Endpoints.svg.Blank = _jp.Endpoints.Blank;
  11970. /*
  11971. * Label overlay in svg renderer is the default Label overlay.
  11972. */
  11973. _jp.Overlays.svg.Label = _jp.Overlays.Label;
  11974. /*
  11975. * Custom overlay in svg renderer is the default Custom overlay.
  11976. */
  11977. _jp.Overlays.svg.Custom = _jp.Overlays.Custom;
  11978. var AbstractSvgArrowOverlay = function (superclass, originalArgs) {
  11979. superclass.apply(this, originalArgs);
  11980. _jp.jsPlumbUIComponent.apply(this, originalArgs);
  11981. this.isAppendedAtTopLevel = false;
  11982. var self = this;
  11983. this.path = null;
  11984. this.paint = function (params, containerExtents) {
  11985. // only draws on connections, not endpoints.
  11986. if (params.component.svg && containerExtents) {
  11987. if (this.path == null) {
  11988. this.path = _node("path", {
  11989. "pointer-events": "all"
  11990. });
  11991. params.component.svg.appendChild(this.path);
  11992. if (this.elementCreated) {
  11993. this.elementCreated(this.path, params.component);
  11994. }
  11995. this.canvas = params.component.svg; // for the sake of completeness; this behaves the same as other overlays
  11996. }
  11997. var clazz = originalArgs && (originalArgs.length == 1) ? (originalArgs[0].cssClass || "") : "",
  11998. offset = [0, 0];
  11999. if (containerExtents.xmin < 0) offset[0] = -containerExtents.xmin;
  12000. if (containerExtents.ymin < 0) offset[1] = -containerExtents.ymin;
  12001. _attr(this.path, {
  12002. "d": makePath(params.d),
  12003. "class": clazz,
  12004. stroke: params.stroke ? params.stroke : null,
  12005. fill: params.fill ? params.fill : null,
  12006. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12007. });
  12008. }
  12009. };
  12010. var makePath = function (d) {
  12011. return (isNaN(d.cxy.x) || isNaN(d.cxy.y)) ? "" : "M" + d.hxy.x + "," + d.hxy.y +
  12012. " L" + d.tail[0].x + "," + d.tail[0].y +
  12013. " L" + d.cxy.x + "," + d.cxy.y +
  12014. " L" + d.tail[1].x + "," + d.tail[1].y +
  12015. " L" + d.hxy.x + "," + d.hxy.y;
  12016. };
  12017. this.transfer = function(target) {
  12018. if (target.canvas && this.path && this.path.parentNode) {
  12019. this.path.parentNode.removeChild(this.path);
  12020. target.canvas.appendChild(this.path);
  12021. }
  12022. };
  12023. };
  12024. _ju.extend(AbstractSvgArrowOverlay, [_jp.jsPlumbUIComponent, _jp.Overlays.AbstractOverlay], {
  12025. cleanup: function (force) {
  12026. if (this.path != null) {
  12027. if (force)
  12028. this._jsPlumb.instance.removeElement(this.path);
  12029. else
  12030. if (this.path.parentNode)
  12031. this.path.parentNode.removeChild(this.path);
  12032. }
  12033. },
  12034. reattach:function(instance) {
  12035. if (this.path && this.canvas && this.path.parentNode == null)
  12036. this.canvas.appendChild(this.path);
  12037. },
  12038. setVisible: function (v) {
  12039. if (this.path != null) (this.path.style.display = (v ? "block" : "none"));
  12040. }
  12041. });
  12042. _jp.Overlays.svg.Arrow = function () {
  12043. AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Arrow, arguments]);
  12044. };
  12045. _ju.extend(_jp.Overlays.svg.Arrow, [ _jp.Overlays.Arrow, AbstractSvgArrowOverlay ]);
  12046. _jp.Overlays.svg.PlainArrow = function () {
  12047. AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.PlainArrow, arguments]);
  12048. };
  12049. _ju.extend(_jp.Overlays.svg.PlainArrow, [ _jp.Overlays.PlainArrow, AbstractSvgArrowOverlay ]);
  12050. _jp.Overlays.svg.Diamond = function () {
  12051. AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Diamond, arguments]);
  12052. };
  12053. _ju.extend(_jp.Overlays.svg.Diamond, [ _jp.Overlays.Diamond, AbstractSvgArrowOverlay ]);
  12054. // a test
  12055. _jp.Overlays.svg.GuideLines = function () {
  12056. var path = null, self = this, p1_1, p1_2;
  12057. _jp.Overlays.GuideLines.apply(this, arguments);
  12058. this.paint = function (params, containerExtents) {
  12059. if (path == null) {
  12060. path = _node("path");
  12061. params.connector.svg.appendChild(path);
  12062. self.attachListeners(path, params.connector);
  12063. self.attachListeners(path, self);
  12064. p1_1 = _node("path");
  12065. params.connector.svg.appendChild(p1_1);
  12066. self.attachListeners(p1_1, params.connector);
  12067. self.attachListeners(p1_1, self);
  12068. p1_2 = _node("path");
  12069. params.connector.svg.appendChild(p1_2);
  12070. self.attachListeners(p1_2, params.connector);
  12071. self.attachListeners(p1_2, self);
  12072. }
  12073. var offset = [0, 0];
  12074. if (containerExtents.xmin < 0) offset[0] = -containerExtents.xmin;
  12075. if (containerExtents.ymin < 0) offset[1] = -containerExtents.ymin;
  12076. _attr(path, {
  12077. "d": makePath(params.head, params.tail),
  12078. stroke: "red",
  12079. fill: null,
  12080. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12081. });
  12082. _attr(p1_1, {
  12083. "d": makePath(params.tailLine[0], params.tailLine[1]),
  12084. stroke: "blue",
  12085. fill: null,
  12086. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12087. });
  12088. _attr(p1_2, {
  12089. "d": makePath(params.headLine[0], params.headLine[1]),
  12090. stroke: "green",
  12091. fill: null,
  12092. transform: "translate(" + offset[0] + "," + offset[1] + ")"
  12093. });
  12094. };
  12095. var makePath = function (d1, d2) {
  12096. return "M " + d1.x + "," + d1.y +
  12097. " L" + d2.x + "," + d2.y;
  12098. };
  12099. };
  12100. _ju.extend(_jp.Overlays.svg.GuideLines, _jp.Overlays.GuideLines);
  12101. }).call(typeof window !== 'undefined' ? window : this);
  12102. /*
  12103. * jsPlumb
  12104. *
  12105. * Title:jsPlumb 2.3.0
  12106. *
  12107. * Provides a way to visually connect elements on an HTML page, using SVG.
  12108. *
  12109. * This file contains the 'vanilla' adapter - having no external dependencies other than bundled libs.
  12110. *
  12111. * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
  12112. *
  12113. * http://jsplumbtoolkit.com
  12114. * http://github.com/sporritt/jsplumb
  12115. *
  12116. * Dual licensed under the MIT and GPL2 licenses.
  12117. */
  12118. ;
  12119. (function () {
  12120. "use strict";
  12121. var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil,
  12122. _jk = root.Katavorio, _jg = root.Biltong;
  12123. var _getDragManager = function (instance, category) {
  12124. category = category || "main";
  12125. var key = "_katavorio_" + category;
  12126. var k = instance[key],
  12127. e = instance.getEventManager();
  12128. if (!k) {
  12129. k = new _jk({
  12130. bind: e.on,
  12131. unbind: e.off,
  12132. getSize: _jp.getSize,
  12133. getPosition: function (el, relativeToRoot) {
  12134. // if this is a nested draggable then compute the offset against its own offsetParent, otherwise
  12135. // compute against the Container's origin. see also the getUIPosition method below.
  12136. var o = instance.getOffset(el, relativeToRoot, el._katavorioDrag ? el.offsetParent : null);
  12137. return [o.left, o.top];
  12138. },
  12139. setPosition: function (el, xy) {
  12140. el.style.left = xy[0] + "px";
  12141. el.style.top = xy[1] + "px";
  12142. },
  12143. addClass: _jp.addClass,
  12144. removeClass: _jp.removeClass,
  12145. intersects: _jg.intersects,
  12146. indexOf: function(l, i) { return l.indexOf(i); },
  12147. scope:instance.getDefaultScope(),
  12148. css: {
  12149. noSelect: instance.dragSelectClass,
  12150. droppable: "jtk-droppable",
  12151. draggable: "jtk-draggable",
  12152. drag: "jtk-drag",
  12153. selected: "jtk-drag-selected",
  12154. active: "jtk-drag-active",
  12155. hover: "jtk-drag-hover",
  12156. ghostProxy:"jtk-ghost-proxy"
  12157. }
  12158. });
  12159. k.setZoom(instance.getZoom());
  12160. instance[key] = k;
  12161. instance.bind("zoom", k.setZoom);
  12162. }
  12163. return k;
  12164. };
  12165. var _animProps = function (o, p) {
  12166. var _one = function (pName) {
  12167. if (p[pName] != null) {
  12168. if (_ju.isString(p[pName])) {
  12169. var m = p[pName].match(/-=/) ? -1 : 1,
  12170. v = p[pName].substring(2);
  12171. return o[pName] + (m * v);
  12172. }
  12173. else return p[pName];
  12174. }
  12175. else
  12176. return o[pName];
  12177. };
  12178. return [ _one("left"), _one("top") ];
  12179. };
  12180. _jp.extend(root.jsPlumbInstance.prototype, {
  12181. animationSupported:true,
  12182. getElement: function (el) {
  12183. if (el == null) return null;
  12184. // here we pluck the first entry if el was a list of entries.
  12185. // this is not my favourite thing to do, but previous versions of
  12186. // jsplumb supported jquery selectors, and it is possible a selector
  12187. // will be passed in here.
  12188. el = typeof el === "string" ? el : el.length != null && el.enctype == null ? el[0] : el;
  12189. return typeof el === "string" ? document.getElementById(el) : el;
  12190. },
  12191. removeElement: function (element) {
  12192. _getDragManager(this).elementRemoved(element);
  12193. this.getEventManager().remove(element);
  12194. },
  12195. //
  12196. // this adapter supports a rudimentary animation function. no easing is supported. only
  12197. // left/top properties are supported. property delta args are expected to be in the form
  12198. //
  12199. // +=x.xxxx
  12200. //
  12201. // or
  12202. //
  12203. // -=x.xxxx
  12204. //
  12205. doAnimate: function (el, properties, options) {
  12206. options = options || {};
  12207. var o = this.getOffset(el),
  12208. ap = _animProps(o, properties),
  12209. ldist = ap[0] - o.left,
  12210. tdist = ap[1] - o.top,
  12211. d = options.duration || 250,
  12212. step = 15, steps = d / step,
  12213. linc = (step / d) * ldist,
  12214. tinc = (step / d) * tdist,
  12215. idx = 0,
  12216. _int = setInterval(function () {
  12217. _jp.setPosition(el, {
  12218. left: o.left + (linc * (idx + 1)),
  12219. top: o.top + (tinc * (idx + 1))
  12220. });
  12221. if (options.step != null) options.step(idx, Math.ceil(steps));
  12222. idx++;
  12223. if (idx >= steps) {
  12224. window.clearInterval(_int);
  12225. if (options.complete != null) options.complete();
  12226. }
  12227. }, step);
  12228. },
  12229. // DRAG/DROP
  12230. destroyDraggable: function (el, category) {
  12231. _getDragManager(this, category).destroyDraggable(el);
  12232. },
  12233. destroyDroppable: function (el, category) {
  12234. _getDragManager(this, category).destroyDroppable(el);
  12235. },
  12236. initDraggable: function (el, options, category) {
  12237. _getDragManager(this, category).draggable(el, options);
  12238. },
  12239. initDroppable: function (el, options, category) {
  12240. _getDragManager(this, category).droppable(el, options);
  12241. },
  12242. isAlreadyDraggable: function (el) {
  12243. return el._katavorioDrag != null;
  12244. },
  12245. isDragSupported: function (el, options) {
  12246. return true;
  12247. },
  12248. isDropSupported: function (el, options) {
  12249. return true;
  12250. },
  12251. isElementDraggable: function (el) {
  12252. el = _jp.getElement(el);
  12253. return el._katavorioDrag && el._katavorioDrag.isEnabled();
  12254. },
  12255. getDragObject: function (eventArgs) {
  12256. return eventArgs[0].drag.getDragElement();
  12257. },
  12258. getDragScope: function (el) {
  12259. return el._katavorioDrag && el._katavorioDrag.scopes.join(" ") || "";
  12260. },
  12261. getDropEvent: function (args) {
  12262. return args[0].e;
  12263. },
  12264. getUIPosition: function (eventArgs, zoom) {
  12265. // here the position reported to us by Katavorio is relative to the element's offsetParent. For top
  12266. // level nodes that is fine, but if we have a nested draggable then its offsetParent is actually
  12267. // not going to be the jsplumb container; it's going to be some child of that element. In that case
  12268. // we want to adjust the UI position to account for the offsetParent's position relative to the Container
  12269. // origin.
  12270. var el = eventArgs[0].el;
  12271. if (el.offsetParent == null) {
  12272. return null;
  12273. }
  12274. var finalPos = eventArgs[0].finalPos || eventArgs[0].pos;
  12275. var p = { left:finalPos[0], top:finalPos[1] };
  12276. if (el._katavorioDrag && el.offsetParent !== this.getContainer()) {
  12277. var oc = this.getOffset(el.offsetParent);
  12278. p.left += oc.left;
  12279. p.top += oc.top;
  12280. }
  12281. return p;
  12282. },
  12283. setDragFilter: function (el, filter, _exclude) {
  12284. if (el._katavorioDrag) {
  12285. el._katavorioDrag.setFilter(filter, _exclude);
  12286. }
  12287. },
  12288. setElementDraggable: function (el, draggable) {
  12289. el = _jp.getElement(el);
  12290. if (el._katavorioDrag)
  12291. el._katavorioDrag.setEnabled(draggable);
  12292. },
  12293. setDragScope: function (el, scope) {
  12294. if (el._katavorioDrag)
  12295. el._katavorioDrag.k.setDragScope(el, scope);
  12296. },
  12297. setDropScope:function(el, scope) {
  12298. if (el._katavorioDrop && el._katavorioDrop.length > 0) {
  12299. el._katavorioDrop[0].k.setDropScope(el, scope);
  12300. }
  12301. },
  12302. addToPosse:function(el, spec) {
  12303. var specs = Array.prototype.slice.call(arguments, 1);
  12304. var dm = _getDragManager(this);
  12305. _jp.each(el, function(_el) {
  12306. _el = [ _jp.getElement(_el) ];
  12307. _el.push.apply(_el, specs );
  12308. dm.addToPosse.apply(dm, _el);
  12309. });
  12310. },
  12311. setPosse:function(el, spec) {
  12312. var specs = Array.prototype.slice.call(arguments, 1);
  12313. var dm = _getDragManager(this);
  12314. _jp.each(el, function(_el) {
  12315. _el = [ _jp.getElement(_el) ];
  12316. _el.push.apply(_el, specs );
  12317. dm.setPosse.apply(dm, _el);
  12318. });
  12319. },
  12320. removeFromPosse:function(el, posseId) {
  12321. var specs = Array.prototype.slice.call(arguments, 1);
  12322. var dm = _getDragManager(this);
  12323. _jp.each(el, function(_el) {
  12324. _el = [ _jp.getElement(_el) ];
  12325. _el.push.apply(_el, specs );
  12326. dm.removeFromPosse.apply(dm, _el);
  12327. });
  12328. },
  12329. removeFromAllPosses:function(el) {
  12330. var dm = _getDragManager(this);
  12331. _jp.each(el, function(_el) { dm.removeFromAllPosses(_jp.getElement(_el)); });
  12332. },
  12333. setPosseState:function(el, posseId, state) {
  12334. var dm = _getDragManager(this);
  12335. _jp.each(el, function(_el) { dm.setPosseState(_jp.getElement(_el), posseId, state); });
  12336. },
  12337. dragEvents: {
  12338. 'start': 'start', 'stop': 'stop', 'drag': 'drag', 'step': 'step',
  12339. 'over': 'over', 'out': 'out', 'drop': 'drop', 'complete': 'complete',
  12340. 'beforeStart':'beforeStart'
  12341. },
  12342. animEvents: {
  12343. 'step': "step", 'complete': 'complete'
  12344. },
  12345. stopDrag: function (el) {
  12346. if (el._katavorioDrag)
  12347. el._katavorioDrag.abort();
  12348. },
  12349. addToDragSelection: function (spec) {
  12350. _getDragManager(this).select(spec);
  12351. },
  12352. removeFromDragSelection: function (spec) {
  12353. _getDragManager(this).deselect(spec);
  12354. },
  12355. clearDragSelection: function () {
  12356. _getDragManager(this).deselectAll();
  12357. },
  12358. trigger: function (el, event, originalEvent, payload) {
  12359. this.getEventManager().trigger(el, event, originalEvent, payload);
  12360. },
  12361. doReset:function() {
  12362. // look for katavorio instances and reset each one if found.
  12363. for (var key in this) {
  12364. if (key.indexOf("_katavorio_") === 0) {
  12365. this[key].reset();
  12366. }
  12367. }
  12368. }
  12369. });
  12370. var ready = function (f) {
  12371. var _do = function () {
  12372. if (/complete|loaded|interactive/.test(document.readyState) && typeof(document.body) != "undefined" && document.body != null)
  12373. f();
  12374. else
  12375. setTimeout(_do, 9);
  12376. };
  12377. _do();
  12378. };
  12379. ready(_jp.init);
  12380. }).call(typeof window !== 'undefined' ? window : this);